Lab of Mcsl054
Lab of Mcsl054
Lab of Mcsl054
Technologies Lab
Introduction
Objectives
Tomcat Installations and Setting
Running JSP Programs
Running Servlet Programs
XML Programming
List of Lab Assignments
Further Readings
Page Nos.
5
5
6
14
17
21
25
28
1.0 INTRODUCTION
In this section of lab course, you will have hands on experience of Advanced Internet
Technologies, which includes programming practices in Java Servlet and Java Server
Pages (JSP), web page security, and XML. This section is based on course MCS051:
Advanced Internet Technologies. A list of programming exercises (Lab Assignments)
is given at the end of this section. You will have to write programs to solve these
exercises and execute it during lab sessions.
Java Servlet technology and Java Server Pages (JSP) are server-side technologies.
They are now becoming the standard way to develop commercial web applications.
Java Technologies basic feature Servlet JSP bring the Write Once, Run Anywhere
paradigm to web applications. If, you apply effectively best practices, servlets and JSP
to help separate presentation from content, this will help in the understanding
applications and reduces complexity.
Before you begin programming/attempt programming, it is essential to learn how
container/web servers are to be installed to handle Servlet/JSP applications. In this
section, first you will learn about Jakarta Tomcat installation, then, about the
execution of Servlet and JSP programs.
The objective of XML design is to describe data and at the same time to focus on what
data is. You may not realise, but all that the XML does to create structures, store and
to send information. Now, it has started becoming evident that XML will be as
important to the future of Web Applications as HTML has been to the foundation of
Web Development. In this section, you will learn to create and view XML documents.
1.1 OBJECTIVES
After completing this lab section, you should be able to:
Lab Manual
Advanced Internet
Technologies Lab
Lab Manual
Now, start your server by double-clicking on shortcut to startup. You will find
window shown in Figure 5.
Advanced Internet
Technologies Lab
Now, your server is started. The next step is to, enter the URL http://localhost/ in your
browser and see whether you reach/are able to access the Tomcat welcome page or
not. Welcome page is shown in Figure 6.
If, you get an error message saying that the page could not be displayed or that the
server could not be found then, there is some problem in your installation and setting.
If this does not work, there are a couple of things to check:
Go through the error messages; it should help you find out the problem (e.g.,
JAVA_HOME not set properly or IIS already reserving port 80).
Lab Manual
Check whether the server appears to be running but you cannot access the home
page? There is a chance that your browser is using a proxy and you have not set
it to bypass proxies for local addresses. If this is the case then:
Advanced Internet
Technologies Lab
Tomcat check the modification dates of the class files of requested servlets, and reload
ones that have changed since they were loaded into the server's memory. If you dont
turn reloadable on for your development server, you have to restart the server every
time you recompile a servlet, which is already loaded into the server's memory.
Enabling the Invoker Servlet
As a beginner, you need to run your initial servlet programs without making any
change in your Web application's deployment descriptor file (in WEB-INF/web.xml
file). For this, you will have to get invoker servlet enabled. After this, you just drop
your servlet into
WEB-INF/classes and use the URL http://host/servlet/ServletName (or
http://host/webAppName /servlet/ServletName) once you start using your own Web
applications.
You have to, uncomment the following servlet and servlet-mapping elements in
install_dir/conf/web.xml as shown in Figure 10 and Figure 11, for enabling the
invoker servlet.Remember this is not Apache Tomcat-specific web.xml file which
goes in the WEB-INF directory of each Web application.
1.
<servlet>
<servlet-name>invoker</servlet-name>
<servlet-class>
org.apache.catalina.servlets.InvokerServlet
</servlet-class>
...
</servlet>
11
Lab Manual
2.
<servlet-mapping>
<servlet-name>invoker</servlet-name>
<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>
Set CLASSPATH
Servlets and JSP are not part of the Java 2 platform, standard edition that is why the
compiler (i.e., javac) you use for development does not know about Servlet and JSP,
and you will have to identify the servlet classes to the compiler. So, you have to set
your CLASSPATH properly, and attempt to compile servlets, tag libraries, Web app
listeners, or other classes that use the servlet and JSP, otherwise, APIs will fail with
error messages saying unknown classes. You need to include both files in your
CLASSPATH for standard Tomcat Server:
12
C:\Tomcat5.5\apache-tomcat-5.5.15\common\lib\servlet-api.jar, and
C:\Tomcat5.5\apache-tomcat-5.5.15\common\lib\jsp-api.jar
If, you have created your own development directory then you also need to put that
directory in the CLASSPATH. It will be good (learning purpose), for you to write
simple package less servlets. After you gain enough experience you have to use
packages for your applications development.
Advanced Internet
Technologies Lab
Now, you are at the stage where you can test your own html, servlet, and jsp programs
in Tomcat Server. But, before you test your own programs, I will suggest the
execution of some examples of Servlet and JSP page given by Tomcat.
Figure 12: Link to Servlet and JSP Example on Tomcat Default Page
Now you can try Some Simple HTML and JSP Page
First, verify that the server is running. If, the server is running, you have to make sure
that you can install and access simple HTML and JSP:
If, you can access an HTML page successfully, it will help you ensure that
HTML and JSP files are loaded in the right/correct directories, and the URLs
correspond make sure for you that in which directories,
If, you are able to successfully access a new JSP page then, it shows that you
have configured the Java compiler properly.
13
Lab Manual
</head>
Advanced Internet
Technologies Lab
<body>
<%
%>
<% out.println(Welcome to first JSP page); %>
<BR>
<%
out.println(Currently the day,date,and time is);
out.println( date );
%>
</body>
</html>
Save this Test.jsp file in C:\Tomcat5.5\apache-tomcat-5.5.15\webapps\ROOT
directory and access it with URL http://localhost/Test.jsp, you will get Web Page
shown in Figure 15a.
Now, let us see an example in which a java class is used for counting the number of
times this JSP is accessed.
Java Class File - Counter.java
public class Counter
15
Lab Manual
{
private static int counter;
public static int getCounter()
{
counter++;
return counter;
}
}
JSP File Cont.jsp
<html>
<body>
The page is:
<% out.println(Counter.getCounter());
%>
</body>
</html>
You have to compile Counter.java file and save Counter.class file in
C:\Tomcat5.5\apache-tomcat-5.5.15\webapps\ROOT\WEB-INF\classes directory.
Save Count.jsp in C:\Tomcat5.5\apache-tomcat-5.5.15\webapps\ROOT directory.Start
server and access URL : http://localhost/Count.jsp trough Internet Explorer , you
will get following screen :
16
The number of times you will access through URL : : http://localhost/Count.jsp will
increase by one The page is: 1, The page is: 2 etc.
Advanced Internet
Technologies Lab
17
Lab Manual
18
Save this HTML code in FirstServlet.html file. Now, you have an HTML code for
invoking TesrServlet program. Start your Tomcat and invoke the URL
C:\MyJava\FirstServlet.html. You will find following the form as the output asking
for your name. Enter a name into textfield and press Submit Query button, you will go
to URL http://localhost/servlet/TestServlet and you will find web page shown in
Figure 19a.
Advanced Internet
Technologies Lab
If, you are developing servlet applications which uses Packages and Utilities then, you
have to be more careful in terms of putting class files in appropriate directories both
during development and when deployed to the server. For example, if, you have a
package named myServlet then, compiling your application.java, put application.class
in install_dir/webapps/ROOT/WEB-INF/classes/myServlet. Once you have placed the
.class file of servlet in the proper directory, access it with the URL
http://localhost/servlet/myServlet.application.
Now, let us see one more servlet program. This program is for counting the number of
times this application is accessed. Here, we will use session tracing for this counting.
Servlet File AccessCount.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
19
Lab Manual
import java.net.*;
import java.util.*;
/** An example of session tracking. */
public class AccessCount extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType(text/html);
PrintWriter out = response.getWriter();
String title = Access Count Example By Session Tracking ;
String heading ;
//Creating HTTP Session
HttpSession session = request.getSession(true);
Integer Count = (Integer)session.getAttribute(Count);
if (Count == null) {
Count = new Integer(0);
heading = Welcome,for Fist time visit ;
}
else {
heading = Welcome Again;
Count = new Integer(Count.intValue() + 1);
}
session.setAttribute("Count", Count);
out.println(<HTML><HEAD><TITLE> Counting by Session
Tracing</TITLE></HEAD>");
out.println(<BODY BGCOLOR=GREEN>\n +
<H1 ALIGN=\"CENTER\>" + heading + </H1>\n +
<H2>Information on Your Session:</H2>\n +
<TABLE BORDER=1 ALIGN=\CENTER\>\n +
<TR BGCOLOR=RED>\n +
<TH>Information Type<TH>Value\n +
<TR>\n +
<TD>ID\n +
<TD> + session.getId() + \n +
<TR>\n +
<TD>Session Created at:\n +
<TD> +
new Date(session.getCreationTime()) + \n +
<TR>\n +
<TD>Last Time of Access at: \n +
<TD> +
new Date(session.getLastAccessedTime()) + \n +
<TR>\n +
<TD>Number of Previous Accesses:\n +
<TD> + Count + \n +
</TABLE>\n +
</BODY></HTML>);
}
} Compile AccessCount.java file and save AccessCoun.class file in
C:\Tomcat5.5\apache-tomcat-5.5.15\webapps\ROOT\WEB-INF\classes directory.
Now aaccess URL http://localhost/servlet/AccessCount. For the first access of
AccessCount page you will get the screen given in Figure 19b.
20
Advanced Internet
Technologies Lab
Lab Manual
Some Concepts
While writing XML documents take care of the following. Though it is discussed in
the course MCS-051, it will be very useful while writing XML documents:
i)
Similar to HTML, start tags are angle bracket enclosed, and end tags are angle
bracket enclosed with a prepended forward slash.
ii) An entity started by a start tag and ended by an end tag is called an element.
iii) Elements can contain other elements. In our example, the Student element
contains two BCA_Student elements.
iv) An element can contain a mix of different elements.
22
v) An XML file must contain exactly one element at the top level. In our example,
the Student is the top level.
Advanced Internet
Technologies Lab
As you know XML, allows the programmer/author to define their own tags and own
document structure.
While defining your own tag you should take care of that:
For example With XML, the tag <myLetter> is different from the tag
<myletter>.
Opening and closing tags must therefore, be written with the same case:
For example, i is incorrect and ii is correct.
Lab Manual
If you see Test.xml file using Internet Explorer you will find following screen:
XML Parsers
You need parsers to break up your document into its component pieces and make
them accessible to other parts of a program. Some parsers check for well-formedness,
24
and some check for document validity. However, if you just want to check that your
XML is both well formed and valid, all you need is an XML validator.
Advanced Internet
Technologies Lab
SAX: The Simple API for XMLSAX is a well-known parser written by David
Megginson, et al. (http://www.megginson.com/SAX/index.html)
Exercise 2.
Session 2:
Exercise 3.
Write a servlet program that takes your name and address from an
HTML Form and displays it.
25
Lab Manual
Exercise 4.
Write a servlet program that displays current date and time. Your servlet
should also indicate the number of times it has been assessed since it
has been loaded.
Exercise 5.
Session 3:
Exercise 6.
Exercise 7.
Write a program, using servlet and JDBC which takes students roll
number and provides student information, which includes the name of
the student, the address, email-id, program of study, and year of
admission. You have to use a database to store students information.
Exercise 8.
Session 4:
Exercise 9.
Exercise 10. Write a JSP program to output, "Welcome to JSP world. The time now
is: system current time. Use a scriptlet for the complete string, including
the HTML tags.
Exercise 11. write a JSP page that display a randomly generated number in first visit
to this page and repeat displaying this same number in subsequent
visits.
Session 5:
Exercise 12. Write a JSP page to output the values returned by System.getProperty for
various system properties such as java.version, java.home, os.name,
user.name, user.home, user.dir etc. Each property should be displayed
in a separate row.
Exercise 13. Write a JSP page to use either <jsp:include> or <jsp:forward> depending
upon the value of a Boolean variable.
Exercise 14. Write a JSP page using <jsp:forward> to go to a servlet program which
display your name, date of birth and address.
Session 6:
Exercise 15. Create an HTML form to take customer information (Name, Address,
Mobile No.). Write a JSP program to validate this information of
customers.
Exercise 16. Write a JSP program using <jsp:include> to include the program
written in Exercise 9.
26
th
Exercise 17. Create a database of students who are in the 5 Semester of the MCA
program with you at your study center. Write a program using JSP and
JDBC to display the name and address of those students who are born
after 1985.
Advanced Internet
Technologies Lab
Session 7:
Exercise 18. Write a JSP program which display a web page containing your personal
information such as: Name, Date of Birth, Sex, Area of Interest,
Specialisation and a paragraph explaining what you want to be in the
next five years.
Exercise 19. Develop an application that collects/maintains the product information of
an electronics goods production company, in a database. Write a JSP
page to retrieve (to display) selective this information in database on
demand. Make necessary assumptions to develop this application.
Session 8:
Exercise 20.The following example is a note to Ramu from Deenu, stored in XML:
<note>
<to> Ramu </to>
<from>Deenu</from>
<heading>Festival Wishes</heading>
<body>May God give you all the happiness</body>
</note>
Extend this document by adding some more information in this document.
Exercise 21. Imagine that this is the description of a book:
My First Servlet
Introduction to Servlet
What is Servlet
What are the advantages of Servlet
Servlet Initialisation
Servlet Realoading
Destroying a Servlet
27
Lab Manual
Visual Basic
Programming
B.Tech
Mohan
Naveen
Java
Programming
M.Tech
Robert
John
Sudhansh
ASP
Programming
MSc
Neeta
Ravi
1.7
28
FURTHER READINGS
1.
Head First Servlet and JSP By Bryan Basham, Kathy Sierra, and Bert Bates,
O. Reilly publication First Edition Eighth India Reprint- 2006.
2.
http://www.w3schools.com/xml/default.asp
3.
http://www.w3.org/XML/
4.
http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Servlets.html
5.
http://tomcat.apache.org/
6.
http://www.coreservlets.com/Apache-Tomcat-Tutorial/
Introduction
Objectives
Installing OpenGL
Creating a Project in VC++ 6.0 and Running
an OpenGL Application
2.4 Basics of OpenGL
2.5 Introduction to OpenGL Primitives
2.6 Example Programs
2.7 Implementation of Line Clipping Algorithm
2.8 OpenGL Function for 3-D Transformations and Viewing
2.9 Implementation of Ray-Tracing Algorithm
2.10 Introduction to VRML
2.11 Lab Assignments
2.12 Further Readings
Page Nos.
29
29
30
31
35
41
45
50
53
56
58
61
65
2.0 INTRODUCTION
In this section of the lab course, you will have hands on experience of Computer
graphics programming C language and visualisation of these graphics using OpenGL
graphics software. This section is based on course MCS053: Computer Graphics and
Multimedia. Before getting into problem solving using C you will learn with the use
of the following:
What is OpenGL?
A list of programming problems is given session wise at the end of this section.
2.1 OBJECTIVES
After completing this lab section, you should be able to:
Lab Manual
2.2
INSTALLING OPENGL
It is a straightforward and cost free process to obtain the OpenGL software for almost
any computer platform. Here, we will discuss how to access the software for each of
the major platforms. On the Internet we can get enough information about OpenGL.
The Internet site http://www.opengl.org/gives us a rich source of information about
OpenGL and a starting point for downloading software. Some on-line manuals are
also available at Silicon Graphics site: http://www.sgi.com/software/opengl/manual.
html. The book OpenGL Programming Guide, by Mason Woo, Jacki Neider, and Tom
Davis (1999, currently in its 3rd edition), is one of the essential sources of information
about using OpenGL, and gives pointers on obtaining and installing the software.
Need for OpenGL
With any system, you start with a C\C++ compiler and install appropriate OpenGL
header files (.h) and libraries. Three Libraries associated with header files are required
for the use of OpenGL:
OpenGL (The basic API tool)
GLU (the OpenGL Utility Library)
GLUT (the OpenGL Utility Toolkit, a windowing tool kit that handles window
system operations).
Typically, files associated with each library are:
Adding Header Files: We place (add) the 3 header files: Gl.h, Glu.h, and Glut.h in a
gl subdirectory of the include directory of your compiler. Thus, in each application
program we write the following include statements:
#include <gl/Gl.h>
#include <gl/Glu.h>
#include <gl/Glut.h>
Adding Library Files: Now, you have to add the appropriate OpenGL library (.lib and
.dll) files to your project so that the linker can find them, in order to run your program
successfully.
MS Visual C++ (5.0 or later version) is a suitable environment for using OpenGL. If
you are working with MS Visual C++ i.e., win32 console application, there is no
need to build a Graphical User Interface (GUI): as the input from the keyboard and
output of text take place through the separate console window.
The library files are available on the Microsoft ftp site:
ftp://ftp.microsoft.com/softlib/mslfiles/opengl95.exe , which includes gl.h, glu.h,
glu32.lib, opengl32.lib, glu32.dll and opengl32.dll.
The glut library files is available on the site:
http://reality.sgi.com/opengl/glut3/glutdlls.zip which includes glut.h, glut32.lib, and
glut32.dll.
When these files have been downloaded, place all the three (.lib) files and all the three
(.dll) files in some suitable directory (if they are not already there). For example, if we
30
are using MS Visual C++, add all (.lib) files in c:\ Program Files\Microsoft Visual
studio/VC98/lib then, place the all (.dll) files in c:\WinNT\System32 directory.
Thus, to run an OpenGL Application on your system, you need the following:
1) MS Visual C++ (5.0 or later version)
2) Library files: Static(.lib) and Dynamic (.dll) and
3) Header files (.h)
Static Libraries:
Dynamic Libraries:
Header Files:
glut.h : Available at OpenGL web sites, copy this file to the above
folder.
Lab Manual
x)
xi)
xii)
xiii)
xiv)
xv)
xvi)
xvii)
xviii)
In the "Object/Library modules" enter the names of the three .lib files
glu32.lib, glut32.lib and opengl32.lib.
Press OK.
Now goto File new
Choose C++ Source file.
Name it GLExample (for example).
Press OK.
Type your code in that source file.
Press F7 to build.
Press Ctrl+F5 to run
Let us consider the step-by-step procedure (as describe above) to execute an example
program in VC++ 6.0.
Step: 1-2: After Opening VC++ 6.0, and choosing File menu, you will see the
following window:
Figure 1: After Opening VC++ 6.0 and Choosing New from File Menu
Step:3-5: In the Projects tab choose: Win32 Console Application. Type your Project
name (For example OpenGLExample). Click OK Application.
Figure 2: Selecting Project Tab Menu from Title Bar and Choosing Win32 Console
Figure 3: After Typing the Names of the Three .lib files. glu32.lib glut32.lib opengl32.lib in the
Object/Library modules.
Step:12-15: Go to filenew. Now choose C++ source file. Give file name as
GLExample (for
example)
Figure 4: After selecting File Menu Tab & Select New. Now Type your File Name in the File
Name Title Bar (say GLExample).
Figure 5: After writing your code in the work space provided, & press F7 to build your file.
33
Lab Manual
OpenGL emerged from Silicon Graphics Inc. (SGI) in 1992 and has become a widely
adopted graphics Application Programming Interface (API). An industry consortium,
Architecture Review Board (ARB), is responsible for guiding the evolution of this
software. OpenGL provides a set of drawing tools through a collection of functions
that are known as within an application. OpenGL is a library of functions for fast 3D
rendering. That means you provide the data in an OpenGL-useable form and OpenGL
will show this data on the screen (render it).
It is developed by many companies and it is free to use. You can develop OpenGLapplications without licensing. It is easy to install and use as we have already
discussed in section 2.2. It is easily available (usually through free downloads over the
Internet) for all types of computer systems.
One basic advantage of using OpenGL for a Computer Graphics course is its
hardware- and system-independent interface. An OpenGL-application will work on
every platform, as long as there is an installed implementation.
The OpenGL API is the premier environment for developing portable, interactive 2D
and 3D graphics applications. A low-level, vendor-neutral software interface, the
OpenGL API is sometimes called the assembler language of computer graphics. In
addition to providing enormous flexibility and functionality, Applications in markets
such as CAD, content creation, energy, entertainment, game development,
manufacturing, medical, and VRML have benefited from the characteristics of
platform accessibility and depth of functionality of the OpenGL API.
Because OpenGL is system independent, there are no functions to create windows
etc., but there are helper functions for each platform. A very useful thing is GLUT.
What is GLUT?
An OpenGL Utility Toolkit (GLUT) is a complete API written by Mark Kilgard
which lets you create windows and handle messages. It exists for several platforms,
that means that a program which uses GLUT can be compiled on many platforms
without (or at least with very few) changes in the code. Thus, GLUT does include
functions to open a window on whatever system you are using.
The following code by using OpenGL Utility Toolkit can open the initial window for
drawing:
#include <windows.h> // use as needed for your system
#include <gl/gl.h>
#include <gl/glu.h>
#include <gl/glut.h>
void main(int argc, char** argv)
{
glutInit(&argc, argv); // initialise the toolkit
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // set display mode
glutInitWindowSize(640,480);
// set window size
glutInitWindowPosition(100,100); // set window position on your screen
glutCreateWindow("OpenGL Window"); // Open the screen window
glutDisplayFunc(myDisplay);
// register redraw function
myInit();
// additional initialisations as necessary
glutMainLoop();
// go into a perpetual loop
}
35
Lab Manual
The first five functions of main () use the OpenGL Utility Toolkit to initialise and
display the screen window in which your program will produce graphics. You can
copy these functions as your first graphics program and run, it will open the initial
window for drawing. A brief description of these five functions is as follows:
values between 0.0 and 1.0, inclusive. The value 0.0 corresponds to the minimum
amount of that colour while 1.0 corresponds to the maximum amount of that colour. A
common correspondence between colour value and displayed colour are listed in the
following table:
Table 1: A correspondence between colour-value and displayed colour. The last column of this
table indicates the command used for corresponding colour.
Colour Value
0,0,0
0,0,1
0,1,0
0,1,1
1,0,0
1,0,1
1,1,0
1,1,1
Displayed
Black
Blue
Green
Cyan
Red
Magenta
Yellow
White
Command used
glColour3f(0.0, 0.0, 0.0);
glColour3f(0.0, 0.0, 1.0);
glColour3f(0.0, 1.0, 0.0);
glColour3f(0.0, 1.0, 1.0);
glColour3f(1.0, 0.0, 0.0);
glColour3f(1.0, 0.0, 1.0);
glColour3f(1.0, 1.0, 0.0);
glColour3f(1.0, 1.0, 1.0);
The pixel value (0,1,1) means that the Red component is off, but both green and
blue are on. In most displays, the contributions from each component are added
together, so (1,1,0) would repersent the adddition of red and green light, that produces
a Yellow colour. As expected, equal amount of red, green, and blue, (1,1,1), produce
white.
OpenGL Data Types
To become more independent of the platform and programming language, OpenGL
provides it's own data types. In the following list you can find a summary of the most
important data types and their equivalent in standard C:
Table 2: Command suffixes and argument data types.
OpenGL
Data
Type
Glbyte
Glshort
GLint, GLsizei
Glfloat, GLclampf
GLdouble,
GLclampd
GLubyte,
GLboolean
GLushort
GLuint, GLenum,
GLbitfield
Internal
Representation
8-bit integer
16-bit integer
32-bit integer
32-bit floating point
64-bit floating point
8-bit unsigned integer
16-bit unsigned integer
32-bit unsigned integer
Defined as C C Literal
Type
Suffix
Signed char
b
Short
s
Long
I
Float
f
Double
d
Unsigned char
ub
Unsigned short
Unsigned long
us
ui
Thus, All the OpenGL datatypes begin with "GL". For example GLfloat, GLint and so
on. There are also many symbolic constants, they all begin with "GL_", like
GL_POINTS, GL_LINES, GL_POLYGON etc. To draw such objects in OpenGL, we
pass it a list of vertices. The list occurs between the two OpenGL function calls
glBegin() and glEnd(). The argument of glBegin() determines which object is drawn.
For example, the following command sequence draw a line.
glBegin(GL_LINES);
// use constant GL_LINES here
glVertex2i(200,200); // Draw 1st vertical line
glVertex2i(200,400);
glEnd();
37
Lab Manual
A function using the suffix i expects a 32-bit integer, but your system might translate
int as a 16-bit integer. Thus, when you compile your program on a new system, Glint,
Glfloat, etc. will be associated with the appropriate C/C++ types. Thus, it is safer to
write same code, written above, as a generic function drawLineInt( ) :
Void drawLineInt(Glint x1, Glint y1,Glint x2, Glint y2)
{
glBegin(GL_LINES);
// use constant GL_LINES here
glVertex2i(200,200); // Draw 1st vertical line
glVertex2i(200,400);
glEnd();
}
Commands Needed to Work With OpenGL
Now, let us see the commands you need in reshape and at the beginning of
display.
There are two (ok, in reality there are three) matrices. The current one is controlled by
glMatrixMode(). You can call it either with GL_PROJECTION or
GL_MODELVIEW. In Reshape, you specify a new projection matrix. After turning it
current, you load an identity matrix into it, that means deleting the former projection
matrix. Now, you can apply a new field of view by using a glu* command:
gluPerspective. You pass the y-angle of view, the aspect ratio (the windows witdth /
height), and a near and far clipping distance. The objects or parts of objects, which are
not between those distances, will not be visible. You should be careful in this process,
dont take a too small near clipping distance, otherwise you could get wrong-looking
results. After this, you make the modelview matrix currrent and also load an identity
matrix.
Display has to clear the colour buffer. Therefore you have to:
1.glClear(GL_COLOUR_BUFFER_BIT).
2.After the initialization of GLUT, you should have defined a clear colour using
glClearColour(). It takes four arguments, red, green and blue and an alpha value. Set
alpha = 0.0.To get clear red, you would call glClearColour(1.0,0.0,0.0,0.0);
Drawing the object.
3.Last but not least you define the "viewport", the area on the window where OpenGL
shall paint to. Therefore you use glViewport(0,0,x,y); with x and y as the size of your
window: You get them from the reshape parameters. Here is how to define the
function headers of the two routines:
void Reshape ( int x, int y );
void Display ( void );
A simple OpenGL Program
The following program will open a window and render a triangle in 3-space from a
particular viewpoint:
After clearing the colourbuffer, you can pass some data to OpenGL. It is very simple:
You specify some vertices, which are used in a certain way. The way is defined by
glBegin(). Now we will use GL_POLYGON as a parameter which tells OpenGL to
use the following vertices as corners of one polygon.
After passing the data to OpenGL, you have to call glEnd().
38
To provide a vertex , you can call one of some glVertex*() routines. * stands for a
combination of the number of arguments (two-dimensional, three-dimensional or
four-dimensional) + the data type (f for float, d for double and i for int).
To specify a 3d vertex with integer coordinates, you call glVertex3i().
To finish rendering, you must call glFlush() at the end of your display-function.
Just call glVertex*() three times between glBegin and glEnd.
To change the current colour in RGB(A)-mode, you call glColour*(). Again * stands
for the number of arguments (three for RGB and four for RGBA)+ the data type. If
you take a floating-point type as parameters, note that 1.0 is full intensity for the
colour component. Also note, that colours are blended, when they are different for one
or more vertices in the polygon.If you want to add some vertices to our polygon, you
must note that OpenGL cannot render concave polygons (for performance reasons).
The following program merely opens a window and draws a rectangle in it.
/******************************************/
/* A Very Simple OpenGL Example!
*/
/******************************************/
#include <windows.h> /* obviously you would need to change this to your native
library
if you're compiling under unix */
#include <gl\gl.h>
#include<gl\glu.h>
#include <gl\glut.h>
void init(void);
void display(void);
int main (int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(250, 250);
glutInitWindowPosition(100, 100);
glutCreateWindow("My First OpenGL Application");
init();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
void init(void)
{
glClearColour(0.0, 0.0, 0.0, 0.0);
glColour3f(0.0, 0.0, 1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-10.0, 10.0, -10.0, 10.0, -10.0, 10.0);
}
void display(void)
{
glClear(GL_COLOUR_BUFFER_BIT);
glRectf(-5.0, 5.0, 5.0, -5.0);
glutSwapBuffers();
}
/******************************************************/
Now, Let us go through this program step-by-step:
39
Lab Manual
1. First, you called the glutInit function, which provides general initialisation for the
GLUT library:
int main (int argc, char **argv)
{
glutInit(&argc, argv);
2. Next you initialise the display mode:
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
This tells OpenGL that you want a double-buffered window, with RGB colour.
3. The next few lines create the window:
glutInitWindowSize(250, 250);
glutInitWindowPosition(100, 100);
glutCreateWindow("My First OpenGL Application");
As you can see, with GLUT this is fairly straightforward.
4. Now it is time to initialise OpenGL. Here, s the code:
void init(void)
{
glClearColour(0.0, 0.0, 0.0, 0.0); /* set the background (clearing) colour to
RGB(0,0,0) -- black */
glColour3f(0.0, 0.0, 1.0); /*set the foreground colour to blue */
glMatrixMode(GL_PROJECTION); /* Initialise the matrix state */
glLoadIdentity();
glOrtho(-10.0, 10.0, -10.0, 10.0, -10.0, 10.0);
}
In OpenGL, matrices are used to manage the view. There are two matrix
modelprojection and modelview. Projection is used to set up the viewport and
clipping boundry, while modelview is used to rotate, translate and scale objects
quickly.
Let us take a look at these two lines:
glLoadIdentity();
glOrtho(-10.0, 10.0, -10.0, 10.0, -10.0, 10.0);
glLoadIdentity() loads the identity matrix into the current matrix state (in this case the
projection matrix). You can consider this the resetting matrix. It resets everything
back to zero.
5. Next comes the call to glOrtho.
This function sets up a clipping volume.You can think of a clipping volume as a box
in which your drawing commands are rendered. As the viewer, we are positioned
outside the box, looking in the front. What we see is whatever is inside the box,
projected onto the flat surface that is the side.
Anything outside the box is invisible.The glOrtho function creates an orthographic
view.
The arguments for glOrtho are as follows:
void glOrtho(double left, double right, double bottom, double top,double near, double
far);
6. Now, let us continue with the application:
glutDisplayFunc(display);
glutMainLoop();
40
The first function sets the function that GLUT will use whenever it needs to update
the view. We then call glutMainLoop() which actually runs the program. From this
point on, our work is done; GLUT will handle the details of managing the window
and calling our painting function to display it.
Lab Manual
void myInit(void)
{
glClearColour(1.0,1.0,1.0,0.0);
// set white background colour
glColour3f(0.0f, 0.0f, 0.0f);
// setting the drawing colour
glPointSize(4.0);
// One dot is a 4 by 4 pixel
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 800.0, 0.0, 600.0);
}
// *********************** myDisplay() ***********
void myDisplay(void)
{
glClear(GL_COLOUR_BUFFER_BIT);
// clear the screen
glBegin(GL_POLYGON);
glVertex2i(100,100);
// Draw these five points as a polygon vertices.
glVertex2i(100,300);
glVertex2i(400,300);
glVertex2i(600,150);
glVertex2i(400,100);
glEnd();
glFlush();
// send all output to the display
}
// ****************** main function ********************
void main(int argc, char** argv)
{
glutInit(&argc, argv); // initialise the toolkit
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // set display mode
glutInitWindowSize(800,600);
// set window size
glutInitWindowPosition(100,100); // set window position on your screen
glutCreateWindow("OpenGL Window"); // Open the screen window
glutDisplayFunc(myDisplay);
// register redraw function
myInit();
glutMainLoop();
// go into a perpetual loop
}
If, here you had used GL_POINTS instead of GL_POLYGON as an argument to the
glBegin(), the primitive would have been simply draw the five points. The results of
running the program appear in following figure:
The argument to glBegin() describes what type of primitive you want to draw. There
are ten possible arguments:
42
Value
GL_POINTS
GL_LINES
GL_LINE_STRIP
GL_LINE_LOOP
Meaning
Individual points
Pairs of vertices interpreted as individual line segments
Series of connected line segments
Same as above, with a segment added between last and
first vertices
GL_TRIANGLES
Triples of vertices interpreted as triangle
GL_TRIANGLE_STRIP Linked strip of triangle
GL_TRIANGLE_FAN
Linked fan of triangles
GL_QUADS
Quadruples of vertices interpreted as four- sided polygons
GL_QUAD_STRIP
Linked strip of quadrilaterals
GL_POLYGON
Boundary of a simple, convex polygon
glEnd() indicates when you wish to stop drawing that type of primitive. This is
necessary because there can be an arbitrary number of vertices for a type of primitive.
Assume that n vertices (v0,v1,v2,v3,.vn-1) are described between a glbegin() and
glEnd().
1)
GL_POINTS: Takes the listed vertices one at a time and draws a separate point
for each of the n vertices.
2)
GL_LINES: Takes the listed vertices two at a time and draws a separate line
for each.
3)
4)
5)
GL_POLYGON: Draws a polygon based on the given list of points v0,v1,..vn1 as vertices. n must be at least 3, or nothing is drawn.
6)
7)
8)
9)
10)
Lab Manual
Each geometric object is described by a set of vertices and the type of the
primitive to be drawn. The primitive type determines whether and how the
vertices are connected.
Specifying Vertices
With OpenGL, all geometric objects are ultimately described as an ordered set of
vertices. The command glVertex*() is used to specify a vertex.
void glVertex{234}{sifd}[v](TYPE coords);
This command is used to specifying a vertex for describing a geometric object. You
can supply upto 4 coordinates (x,y,z,w) for a particular vertex or at least two (x,y) by
selecting the appropriate version of the command. If you use a version that does not
explicitly specify z or w, z is understood to be 0 and w as 1. This command are
effective only between glBegin() and glEnd().
Here are some example of uses of glVertex*():
glVertex2s(1, 2);
glVertex3d(0.0, 0.0, 3.1415926535898);
glVertex4f(2.3, 2.0, -4.2, 2.0);
GLdouble vector[3] = {3.0, 10.0, 2033.0};
glVertex3dv(vector);
The first example represents a vertex with 3-D coordinates (1,2,0).(Remember that,
the z-coordinate is understood to be 0).
The coordinates in the second example are (0.0, 0.0, 3.1415926535898) (doubleprecision floating-point number).
The third example represents a vertex with 3-D coordinates (1.15,1.0,-2.1) as a
homogeneous coordinate.
(Note that x,y, and z-coordinates are divided by w, in a homogeneous coordinate
system).
In the final example, dvect is a pointer to an array of three double-precision floating
point numbers.
It is necessary to call the command glFlush() to ensure that all previously issued
commands are executed. glFlush() is generally called at the end of a sequence of
drawing commands to ensure all objects in the scene are drawn.
The following example illustrates the different results of some of the primitive types
applied to the set of vertices.
Making Point Drawing: To draw a point we use GL_POINTS as the argument to
GLBegin( ). Thus to draw a two points, we use the following commands:
glBegin(GL_POINTS)
{
glVertex2d(100,130);
glVertex2d(100,200);
glEnd(); }
Making Line Drawing: To draw a line we use GL_LINES as the argument to
GLBegin( ). Thus to draw a four lines, two horizontal and two vertival (tic-tac-toe, we
use the following commands:
glBegin(GL_LINES)
glVertex2i(20,40); // 1st horizontal line
glVertex2d(80,40);
44
Lab Manual
46
Figure 8: The Output of the Program, which draw a centered square with a triangle on each
side of a square
Figure 9: The Output of the Program, when rotate left using keyboard letter L
Lab Manual
Displaying Lines:
With OpenGL, you can specify lines with different widths. That is, lines can be drawn
with alternating dots and dashes, and so on. This is known as stippled (dotted or
dashed) lines.
Void glLineWidth()(Glfloat width);
This command sets the width in pixels for rendered lines; width must be greater than
0.0 and by default is 1.0.
The actual rendering of lines is affected if either antialiasing or multisampling is
enabled. Without antialiasing, widths of 1, 2, and 3 draw lines 1, 2, and 3 pixels wide.
With aliasing enabled, noninteger line widths are possible.
You can obtain the range of supported aliased line width by using
GL_ALIASED_WIDTH_RANGE with glGetFloatv(). To determine the supported
minimum and maximum sizes of antialiased line widths, and what granularity your
implementation supports, call glGetFloatv(), with
GL_SMOOTH_LINE_WIDTH_RANGE and
GL_SMOOTH_LINE_WIDTH_GRANULARITY
Stippled Lines:
Suppose one wants a line to be drawn with a dot-dash pattern (stippled lines). To
make stippled lines, you use the command glLineStipple() to define pattern.
Void glLineStipple(Glint factor, Glushort pattern);
This command sets the current stippling pattern for lines. The pattern argument is a
16-bit series of 0s and 1s, and its repeated as necessary to stipple a given line. A 1
indicates that drawing occurs, and a 0 indicates that drawing does not occur, on a
pixel-by-pixel basis. A pattern is scanned from the low-order bit up to high-order bit.
The pattern can be stretched out by using factor, which multiplies each subseries of
consecutive 1s and 0s. Thus, if three consecutive 1s appear in the pattern, they are
stretched to six if factor is 2. Factor lies between 1 and 256. Line stippling must be
enabled by passing GL_LINE_STIPPLE to glEnable(); and it is disabled by passing
the same argument to glDisable().
For example, consider the following sequence of command:
glLineStiple(2,0x3F07);
glEnable(GL_LINE_STIPPLE);
Here, pattern is given in Hexadecimal notation, which is equivalent to
0011111100000111 in binary. The variable factor specify how much to enlarge
pattern. Each bit in the pattern is repeated factor times (remember low-order bit is
used first for drawing). Thus, the pattern 0x3f07 with factor 2 yields
00001111111111110000000000111111. That is a line would be drawn with 6 pixel
on; then 10 pixel off; 12 on and 4 off. The following table shows a results of stippled
line for various patterns and factors.
Table 4:Stippled lines for a given pattern
PATTERN
0x3F07
0xAAAA
0xAAAA
48
FACTOR
2
1
2
RESULT
------------------------------------__ __ __ __ __ __ __ __ __ __
The following program illustrates the result of drawing for a different stippled pattern
and line widths.
// *************************************************************
// Program:3: To draw a stippled line with different Stippled pattern and line width
// *************************************************************
#include <windows.h>
#include <gl/gl.h>
#include <gl/glu.h>
#include <gl/glut.h>
#define drawOneLine(x1,y1,x2,y2) glBegin(GL_LINES); \
glVertex2f((x1),(y1)); glVertex2f((x2),(y2)); glEnd();
void init(void)
{
glClearColour(0.0,0.0,0.0,0.0);
glShadeModel(GL_FLAT);
}
void display(void)
{
int i;
glClear(GL_COLOUR_BUFFER_BIT);
glColour3f(1.0,1.0,1.0);
glEnable(GL_LINE_STIPPLE);
//** 1st row-line in the output,3 line, each with different stipple
glLineStipple(1,0x00FF);
// ****dashed line
drawOneLine(50.0,125.0,150.0,125.0);
glLineStipple(1,0x0101);
// *** dotted line
drawOneLine(150.0,125.0,250.0,125.0);
glLineStipple(1,0xAAAA);
// *** dash/dot/dash
drawOneLine(250.0,125.0,350.0,125.0);
//** 2nd line in the output,3 wide line, each with different stipple
glLineWidth(8.0);
glLineStipple(1,0x00FF);
// ****dashed line
drawOneLine(50.0,100.0,150.0,100.0);
glLineStipple(1,0x0101);
// *** dotted line
drawOneLine(150.0,100.0,250.0,100.0);
glLineStipple(1,0xAAAA);
// *** dash/dot/dash
drawOneLine(250.0,100.0,350.0,100.0);
glDisable(GL_LINE_STIPPLE);
glFlush();
}
void reshape(int w, int h)
{
glViewport(0,0,(GLsizei) w, (GLsizei) h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,(GLdouble) w, 0.0, (GLdouble) h);
49
Lab Manual
}
int main(int argc, char** argv)
{
glutInit(&argc, argv); // initialise the toolkit
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // set display mode
glutInitWindowSize(400,150);
// set window size
glutInitWindowPosition(100,100); // set window position on your screen
glutCreateWindow(argv[0]);// Open the screen window
init();
glutDisplayFunc(display);
// register redraw function
glutReshapeFunc(reshape);
glutMainLoop();
// go into a perpetual loop
return 0;
}
The result of running this program-3 appears in the Figure 10:
3)
If both endpoints of a line is inside the clipping boundaries, then this line is
totally visible (i.e. line P1P2).
4) If both endpoints of a line are outside the clipping boundaries, then this line
may be totally invisible (i.e. line P3P4).
5) All other lines cross one/more clipping boundaries, and may require
calculation of multiple intersection points.
1000
0001
Window 0010
0000
0101
0100
1010
0110
Now, we use these endpoints code to determine whether the line segment lies
completely inside the clipping window or outside the window edge. In this algorithm,
we divide the line clipping process into two phases:
1) Identify those lines which intersect the clipping window and so need to be
clipped, and
2) Perform the clipping.
All lines fall into one of the following clipping categories:
Case-1: (Visible):- If both 4-bit codes of the endpoints are (0000), then the line lies
completely inside the clip window (i.e. line P1P2).
Case-2: (invisible):- If the bitwise logical AND of the endpoints code is not equal to
(0000), then the line lies completely outside the clip window, so are trivially rejected
(i.e. line P3P4).
Case-3:( Clipping candidate):- If the bitwise logical AND of the endpoints code is
equal to (0000), then the line is to be clipped with one/more window edges (i.e. line
PQ).
51
Lab Manual
P4
P3
P1
P2
Figure 12: The line segments having end points P1P2 (i.e Visible), P3P4 (i.e. invisible) and
PQ(i.e.Clipping candidate) against a rectangular clipping window.
Following Figure-11 shows how inside-outside test can be carried out, to check
how a point P is positioned relative to the window. A single 8-bit word code is
used: four of its bits are used to capture the four pieces of information. Point P is
tested against each window boundary, if P lies outside the boundary, the proper bit of
code is set to 1 to represent TRUe. The first code is initialised to 0, and then its
individual bits are set as appropriate using a bitwise OR operation. The values 8, 4, 2,
and 1 are simple masks. For instance, since 8 is 00001000 in binary, bitwise OR-ing a
value with 8, sets the fourth bit from the right end to 1.
/****************************************
unsigned char code=0; /* Initially all bits are set to 0
.
If(P.x< Window.l) code |= 8; // set bit 3
If(P.y< Window.b) code |= 4; // set bit 2
If(P.x< Window.r) code |= 2; // set bit 1
If(P.y< Window.t) code |= 1; // set bit 0
/************************************************
The following is a pseudocode for Cohen-Sutherland line clipping algorithm. The
point 2 represents 2D point and RealRect holds a rectangular window. (See Figure13).
/*******************************************************
Top
p1
dely
window
p2
delx
bottom
Left
Right
}
else
// p2 is outside
{
if (p2 is to the left) chop against the left edge
else if (p2 is to the right) chop against the right edge
else if (p2 is below) chop against the bottom edge
else if (p2 is above) chop against the top edge
}
}while (1);
}
/*****************************************************
Here, each time the do loop is executed, the code for each end point is recomputed
and tested. When trivial acceptance and trivial rejection fail, the algorithm tests
whether p1 is outside the window, and if it is, that end of the segment is clipped to a
window boundary. If p1 is inside the window, then p2 must be outside, so p2 is
clipped to a window boundary.
Lab Manual
m1 m5
m2 m6
m3 m7
m4 m8
m9 m13
m10 m14
m11 m15
m12 m16
If, you are programming in C and you declare a matrix as m[4][4], then the element
m[i][j] reperesents ith column and jth row of the OpenGL transformation matrix. One
way to avoid confusion between column and row is to declare your matrix as m[16].
You can also avoid this confusion by calling the OpenGL command
glLoadTransposeMatrix*() and glMultTransposeMatrix*(), which use rowmajor(the standard C convension) matrices as arguments.
void glLoadTransposeMatrix{fd}(const TYPE *m);
This command sets the 16 values of the current matrix to those specified by m, whose
values are stored in row-major order. glLoadTransposeMatrix*(m) has the same
effect as glLoadMatrix*(mT).
void glMultTransposeMatrix{fd}(const TYPE *m);
Multiplies the matrix specified by the 16 values pointed to by m by the current matrix
and stores the result as the current matrix. glMultTransposeMatrix*(m) has the same
effect as glMultMatrix*(mT).
There are 3 OpenGL commands for modeling transformations: glTranslate*(),
glRotate*(), and glScale*(). All these commands are equivalent to producing an
appropriate translation, rotation, or scaling matrix, and then calling glMultMatrix*()
with that matrix as the argument.
void glTranslate{fd}(TYPE x, TYPE y, TYPE z);
This command multiplies the current matrix by a matrix that moves (translates) an
object by the given x, y, and z values (or moves the local coordinate system by the
same amounts). Note that glTranslatef(0.0,0.0,0.0) implies an identity operation- that
is , it has no effect on an object or its local coordinate system.
void glRotate{fd}(TYPE angle, TYPE x, TYPE y, TYPE z);
This command multiplies the current matrix by a matrix that rotates an object (or the
local coordinate system) in a counter clockwise direction about the ray from the origin
through the point (x, y, z). The angle parameter specifies the angle of rotation in
degrees. For example: glRotatef(45.0,0.0,0.0,1.0) rotates a given object by 45 degrees
about the z-axis. And if the angle amount is zero, the glRotate*() command has no
effect.
void glScale{fd}(TYPE x, TYPE y, TYPE z);
This command multiplies the current matrix by a matrix that stretches, shrinks, or
reflects an object along the axes. Each x, y, and z coordinate of every point in the
object is multiplied by the corresponding argument x, y, or z. With the local coordinate
system approach, the local coordinate axes are stretched, shrunk, or reflected by the x,
y, and z factors, and the associated object is stretched by them.
54
Out of these three modeling transformation, only glScale*() changes the size of an
object: scaling with value greater than 1.0 stretches an object, and the value less than
1.0 shrinks it. Scaling with a 1.0 value reflects an object across the axis.
glScale(1.0,1.0,1.0) indicates an identity operation.
Viewport Transformation
Viewport transformation is analogous to choosing the size of the developed
photograph. By default, OpenGL sets the viewport to be the entire pixel rectangle of
the initial program window. The command glViewport (GLint x, GLint y, GLsizei
width, GLsizei height) is used to change the size of the drawing region. The x and y
parameters specify the upper left corner of the viewport, and width and height are the
size of the viewport rectangle. This command is often used for the function to handle
window reshape events. By default the initial viewport values are (0,0,winWidth,
winHeight), where winWidth and winHeight specify the size of the window.
Projection Transformation:
Before using any of the transformation command, you have to call
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
so that the commands affect the projection matrix, rather than the model-view matrix,
so that you can avoid compound projection transformations. The purpose of the
projection transformation is to defrine a viewing volume, which is used in two ways.
The viewing volume determines how an object is projected onto the screen (by using a
perspective or an orthographic projection), and it defines which objects or portions of
objects are clipped out of the final image.
Perspective Projection:
In perspective projections, the further an object is from the camera, the smallest looks
and the nearer object looks bigger. This occurs because the viewing volume for a
perspective projection is a frustum of a pyramid. The command to define a frustum,
glFrustum(), calculates a matrix that accomplishes perspective projection and
multiplies the current projection matrix (typically the identity matrix) by it.
Void glFrustum(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top,
Gldouble
near, Gldouble far);
This command creates a matrix for a perspective-view frustum and multiplies the
current matrix by it. The frustums viewing volume is defined by the parameters:
(left, bottom, -near) and (right, top, -near) specifies the (x,y,z) coordinates of the
lower-left and upper-right corners, respectively of the near clipping plane; near and far
give the distances from the viewpoint to the near and far clipping planes. Both
distances must be positive.
Orthographic Projection
With an orthographic projection, the viewing volume is shaped like a box. Unlike
perspective projection, the size of the viewing volume does not change from one end
to the other. Therefore, distance from the "camera" does not affect how large an object
appears.
The command to create an orthographic viewing volume is
void glOrtho(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top,
GLdouble near, GLdouble far).
The arguments left and right specify the coordinates for the left and right vertical
clipping planes. The arguments bottom and top specifies the coordinates for the
55
Lab Manual
bottom and top horizontal clipping planes. The arguments near and far specifies the
distances to the nearer and farther depth clipping planes. These distances are negative
if the plane is to be behind the viewer.
One of the main problems in the rendering of 3-D scenes is the elimination of hidden
surfaces, i.e., surfaces that are not visible from the position of the eye. This problem is
tackled in various ways. For example, in the z-buffer method, a depth value is
associated with each pixel on the screen. If the depth of the point under consideration
from the view plane (the projection screen) is less than the stored depth at that pixel,
the pixel is assigned the colour of the point and the depth value is updated to the new
value. The process continues in this way.
Ray tracing is an extension of, ray-casting, a common hidden-surface removal
method. It is not only looking for the visible surface for each pixel but also by
collecting intensity contributions as the ray intersects the surfaces, as shown in Figure
14. It tries to mimic actual physical effects associated with the propagation of light.
In ray casting, a ray of light is followed from the eye position through the point on the
view plane corresponding to the pixel. For each surface in the scene, the distance the
ray must travel before it intersects that surface is calculated, using elementary or
advanced mathematical methods. The surface with the shortest distance is the nearest
one, therefore, it blocks the others and is the visible surface. Ray casting is therefore, a
hidden surface removal method. Here, we will discuss the basic ray tracing algorithm,
which is mainly concern with visible surface detection, shadow effects, transparency
and multiple light source elimination.
56
S1
S4
T1
T2
R1
R3
S3
R2
S3
R1
S2
S1
(a)
R3
S2
T3
R2
S4
R4
(b)
Figure 15: (a) Reflection R and Refraction T path through a scene (b) Binary Tracing tree
The basic ray-tracing algorithm is concerned with one ray per pixel. At the first level,
we need to test each surface in the scene to determine whether it is intersected by the
ray or not. If the surface is intersected, we calculate the distance from the pixel to the
surface-intersection point. The surface yielding the smallest intersection distance is
identified as the visible surface for that pixel. The ray can be reflected off the visible
surface along a specular path (if the angle of reflection is equal to the angle of
incidence). If the surface is transparent, the ray can be transmitted through the surface
in the direction of refraction. Reflection and refraction rays are referred to as
secondary rays.
The above procedure is repeated for each secondary ray. At the second level, objects
are tested for intersection with the secondary ray and the nearest surface along a
secondary ray path is used to produce the next level of reflection refraction paths.
As the ray from a pixel moves through the scene, the intersected surfaces at each level
are added to form a binary tracing tree, as shown in Figure15b. In this Figure, the left
branches indicate the reflection paths and the right branches indicate the transmission
paths. A path in the tree is terminated if, it reaches the maximum depth value of the
tree set by the user or if, the ray strikes a light source. The intensity to be assigned to a
pixel is determined by combining the intensity contributions starting at the bottom
(terminal nodes) of its ray-tracing tree. Surface intensity calculated at each node in the
tree is attenuated by the distance of the node from its parent node (surface at the next
high level) and is added to the parent surface. Pixel intensity is the sum of the
attenuated intensities at the root node of the binary ray-tracing tree. If, the pixel does
not intersect any surface, then the pixel is assigned to the background intensity. If, a
pixel intersects a non-reflecting light source, the pixel is assigned the intensity of the
source.
57
Lab Manual
Sound libraries
Object libraries
Specifications
Tutorials
Books
and more...
First, you have to obtain a tool for VRML. There are freely downloadable versions
of products such as Caligari worldSpace, Intervista WorldView and TGS WebSpace.
Some allow you to browse in 3D, while others allow for various levels of 3D creation
and VRML authoring.
After you have installed and configured your VRML application, you can load a
VRML file the same way you access an HTML file: either by clicking on a link or
typing a URL and hitting return. If, you typed the URL into your VRML application,
then the file will be loaded. Well-structured VRML files will allow your VRML
browser to load the file in pieces, which has the advantage that you can start exploring
right away while the browser fetches more detailed objects and those that are not
currently in your view.
HTML and VRML
As we know WWW is based on HTTP (Hyper Text Transfer Protocol). The HTML
(Hyper Text Markup Language) is used to describe how the text, images, sound and
video are represented across different types of computers that are connected to the
Internet. HTML allows text and graphics to be displayed together using a two
dimensional pages (X and Y planes only). Whereas VRML is a format that describes
how three-dimensional environments can be explored and created on the www. Thus,
58
VRML is 3D (i.e., using X, Y and Z space) whereas HTML is 2D (i.e., using X and
Y planes only). Since, 2D is a subset of 3D, any 2D object can be easily represented
in 3D environment. Thus, VRML allows 2D home pages to expand into 3D home
worlds.
VRML allows much more interaction than HTML. When viewing two-dimensional
home pages, your options are basically limited to jumping from page to page and
looking at images from a fixed, pre-determined perspective. When visiting VRML
worlds, however, you can freely choose the perspective from which to view the
world.
VRML FILE FORMATE
VRML is a text file format where, e.g., vertices and edges for a 3D polygon can be
specified along with the surface colour, image-mapped textures, shininess,
transparency, and so on. URLs can be associated with graphical components so that a
web browser might fetch a web-page or a new VRML file from the Internet when the
user clicks on the specific graphical component.
VRML text files use a .wrl extension. Text files format may often be compressed
using gzip so that they transfer over the Internet more quickly.
You can view VRML files using a VRML browser:
A VRML helper-application, and
a VRML plug-in to an HTML browser.
You can view VRML files from your local hard disk, or from the Internet
You can construct VRML files using:
A text editor,
a world builder application
a 3D modeler and format translator, and
a shape generator (like, a Perl script).
Advantages of using text editor
No new software to be bought
access to all VRML features, and
detailed control of world efficiency
Disadvantages of using text editor:
Hard to author complex 3D shapes, and
requires knowledge of VRML syntax
Advantages of using world builder:
Easy 3-D drawing and animating user interface, and
little need to learn VRML syntax
Disadvantages of using world builder:
May not support all VRML features, and
may not produce most efficient VRML
Advantages of using a 3D modeler and format translator:
Very powerful drawing and animating features, and
can make photo-realistic images too
Lab Manual
60
61
Lab Manual
Session 3:
Exercise 7. WAP in C/C++ to implement a DDA Line-drawing algorithm (without
using inbuilt line() function).
Exercise 8. WAP in C/C++ to implement a Bresenhams Circle generation algorithm
(without using inbuilt circle() function).
Exercise 9. WAP in C/C++ to draw the convex Polygon ( a polygon is convex if a line
connecting any two points of the polygon lies entirely within it) and fill a
color in it.
Session 4:
Exercise 10. WAP in C/C++ using OpenGL to draw a tic-toc-tie board as shown in the
following figure.
Figure-1
Exercise 11. Modify your program-2 for thick lines and stippled lines as shown in
Figure 2(a), 2(b).
Figure 2(a)
Figure 2(b)
Exercise 12. WAP in C/C++ using OpenGL to draw a hard wire house as shown in
Figure3. Use basic primitive of openGL.
120
40
40
100
Figure-3
Session 5:
Exercise 13.WAP in C/C++ using OpenGL to draw a checkerboard by writing a
routing checkerboard (int size) that draws the checkerboard as shown in
Figure 4. Place the checkerboard with its lower-left corner at (0,0) and
each of the 64 square, where W and B represents white and black colour,
respectively.
62
W
B
W
B
W
B
W
B
B
W
B
W
B
W
B
W
W
B
W
B
W
B
W
B
B
W
B
W
B
W
B
W
W
B
W
B
W
B
W
B
B
W
B
W
B
W
B
W
W
B
W
B
W
B
W
B
B
W
B
W
B
W
B
W
Figure 4
Exercise 14. WAP in C/C++ using OpenGL to draw a stippled line with different
stipped pattern and line Width. You can use various pattern and factors
as follows:
Pattern
0x7733
0x5555
0xFF00
0xFF00
0x3333
Factor
1
1
1
2
3
E
A
C
X
Figure 5
63
Lab Manual
Session 7:
Exercise 19. WAP in C/C++ using OpenGL commands to perform a 3-Dimensional
combined transformation, such as translation, rotation and reflection, on a given
triangle.
Exercise 20. WAP in C/C++ using OpenGL commands to perform the following
sequence of transformation:
i. Scale the given image (say Triangle ABC) x direction to be one-half as large
and then rotate counterclockwise by 900 about the origin.
ii. Rotate counterclockwise about the origin by 900 and then Scale the x direction
to be one-half as large.
iii. Translate down unit, right unit, and then rotate counterclockwise by 450.
Exercise 21. A square ABCD is given with vertices A(x1,y1),B(x2,y2),C(x3,y3), and
D(x4,y4).
WAP in C/C++ to illustrate the effect of a) x-shear b) y-shear c) xyshear on the given square, when x-shearing factor, a=2 and y-shearing
factor, b=3.
Session 8:
Exercise 22. WAP in C/C++ to show that a reflection about the y=x is equivalent to a
reflection relative the x-axis followed by a counterclockwise rotation of
900.
Exercise 23. Familiarize yourself with various OpenGL commands for parallel &
Perspective projections.
Session 9:
Exercise 24. WAP in C/C++ to generate Fractal images (for example you can use
Koch curve or Hilbert curves).
Exercise 25. WAP in C/C++ using OpenGL commands to perform a ray-tracing
algorithm.
Exercise 26. Familiarise yourself with 3-D viewing using OpenGL library functions
primitives.
Session 10:
Exercise 27. Download the VRML plug in on your system and familiarise your self
with various features of VRML.
Example 28. Download the samples of VRML. For example, a cube, and experience
its rotations. Now, edit this file and change the modeling parameters.
Observe the effects of these changes.
64