Vous êtes sur la page 1sur 39

Laboratory Course (Advanced Internet Technologies & Computer Graphics and Multimedia)

PART-I: MCS-051 (Advanced Internet Technologies)

Q1. Develop a web page using servlet and JDBC to display the details of books on topic DBMS

available in library. Make necessary assumptions.

Ans:

1
Q2. Write a program using JDBC and JSP to display the name, address and account number of all the

saving account holders of a branch of a Bank, having balance of Rs. 5000/- or more in their account.

Make necessary assumptions.

Ans.

Program for Customer Login Page

//signin.html

<html>

<title><signin></title>

<form method="Get" action="Check">

<FONT SIZE="20" FACE="courier" COLOR=blue>

<body bgcolor="#E7E7EF"><br><br><br>

<center><table>

<tr><td><h3>Account No</h3></td><td ><input type=text name="user"></td></tr>

<tr><td><h3>Password</h3></td><td><input type=password name="pass"></td></tr>

<tr><th COLSPAN="2"><input type=submit value="SUBMIT" name="SUBMIT"></th></tr>

</table></center>

</body>

2
</html>

Servlet program to verify the user

//Check.java

import javax.servlet.*;

import java.io.*;

import java.sql.*;

import javax.servlet.http.*;

public class Check extends HttpServlet {

public void service(HttpServletRequest request, HttpServletResponse response)

throws ServletException, java.io.IOException {

PrintWriter out=response.getWriter();

String acno=request.getParameter("user");

System.out.println(acno);

String pass=request.getParameter("pass");

HttpSession session=request.getSession();

session.setAttribute("sess",acno);

try{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection con = DriverManager.getConnection("jdbc:odbc:ques");

Statement st=con.createStatement();

ResultSet rs=st.executeQuery("select * from bank where pass='"+pass+"' and Acno="+acno );

if(rs.next())

{ String s1=rs.getString(1);

out.println("name"+s1);

RequestDispatcher rd=request.getRequestDispatcher("/user.jsp");

rd.forward(request,response);

}else

{ RequestDispatcher rd=request.getRequestDispatcher("signin.html");

rd.forward(request,response);

3
}

catch(Exception e){

}}}

User operation page

//user.jsp

<html>

<body bgcolor="#ccccdd">

<%

String acno=(String)session.getAttribute("sess");

System.out.println(acno);

%><center>

<a href="debit.html">Debit the Amount</a><br>

<a href="credit.html">Credit the Amount</a><br>

<a href="month.jsp">Monthly Record</a><br>

</center>

</body>

</html>

Credit Design Page

//credit.html

<html>

<Head> <center>Welcome to the credit page</center></head>

<form action="credit.jsp">

<body bgcolor="#ccccdd"><center><table>

<tr><td>Enter the Account NO</td><td><input type="text" name="ac"></td></tr>

<tr><td>Enter the Amount</td><td><input type="text" name="amnt"></td></tr>

<tr><td><input type="submit" value="credit"></tr></td></table></center>

</body> </form>

</html>

4
Debit Design Page

//debit.html

<html>

<Head><center> Welcome to the Debit page</center></head>

<form action="debit.jsp">

<body bgcolor="#ccccdd"><center><table>

<tr><td>Enter the Account NO</td><td><input type="text" name="ac"></td></tr>

<tr><td>Enter the Amount</td><td><input type="text" name="amnt"></td></tr>

<tr><td><input type="submit" value="Debit"></td></tr></table></center>

</body>

</form>

</html>

Program to Credit the Amount and Display the balance

//credit.jsp

<html>

<%@ page import="java.sql.*"%>

<%@ page import="java.util.*"%>

<%

String amount=request.getParameter("amnt");

int iamount=Integer.parseInt(amount);

String acnt=request.getParameter("ac");

int acno=Integer.parseInt(acnt);

String type="Credit";

Calendar calendar = new GregorianCalendar();

System.out.println("YEAR: " + calendar.get(Calendar.YEAR));

System.out.println("MONTH: " + calendar.get(Calendar.MONTH));

System.out.println("DATE: " + calendar.get(Calendar.DATE));

String

dor =String.valueOf(calendar.get(Calendar.DATE))+"/"+String.valueOf(calendar.get

5
(Calendar.M

ONTH))+"/"+String.valueOf(calendar.get(Calendar.YEAR));

try{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection con = DriverManager.getConnection("jdbc:odbc:ques");

Statement st=con.createStatement();

ResultSet rs=st.executeQuery("select * from bank where Acno="+acno);

int totbal=0;

while(rs.next())

{ int s1=rs.getInt(5);

totbal=s1-iamount;

if(totbal<=0)

{out.println("Your amount is credited you have to pay Rs"+totbal);

}else

{out.println("Your amount is credited Your balance is"+totbal);

}}

PreparedStatement pstmt = con.prepareStatement("update bank set

balance=? where Acno="+acno); pstmt.setInt(1,totbal);

int i = pstmt.executeUpdate();

PreparedStatement pstmt1 = con.prepareStatement("insert into month values(?,?,?,?,?)");

pstmt1.setString(1,dor);

pstmt1.setInt(2,totbal);

pstmt1.setInt(3,acno);

pstmt1.setString(4,type);

pstmt1.setInt(5,iamount);

int i1 = pstmt1.executeUpdate();

catch(Exception e){

}%></html>

6
Program to Credit the Amount and Display the balance

//debit.jsp

<html>

<body>

<%@ page import="java.sql.*"%>

<%@ page import="java.util.*"%>

<%

String amount=request.getParameter("amnt");

int iamount=Integer.parseInt(amount);

String acnt=request.getParameter("ac");

int acno=Integer.parseInt(acnt);

String type="Debit";

Calendar calendar = new GregorianCalendar();

System.out.println("YEAR: " + calendar.get(Calendar.YEAR));

System.out.println("MONTH: " + calendar.get(Calendar.MONTH));

System.out.println("DATE: " + calendar.get(Calendar.DATE));

String dor =String.valueOf(calendar.get(Calendar.DATE))+"/"+String.valueOf(calendar.get(Calendar.M

ONTH))+"/"+String.valueOf(calendar.get(Calendar.YEAR));

try{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection con = DriverManager.getConnection("jdbc:odbc:ques");

Statement st=con.createStatement();

ResultSet rs=st.executeQuery("select * from bank where Acno="+acno);

int totbal=0;

while(rs.next())

{ int s1=rs.getInt(5);

if(s1>=500)

{totbal=s1-iamount;

out.println("Amount is Debited successfully");

7
out.println("Your balance is"+totbal);

}else{

out.println("Your balance is less than 500,You can't debit the amount");

totbal=s1;

}PreparedStatement pstmt = con.prepareStatement("update bank set balance=?

where Acno="+acno); pstmt.setInt(1,totbal);

int i = pstmt.executeUpdate();

PreparedStatement pstmt1 = con.prepareStatement("insert into month values(?,?,?,?,?)");

pstmt1.setString(1,dor);

pstmt1.setInt(2,totbal);

pstmt1.setInt(3,acno);

pstmt1.setString(4,type);

pstmt1.setInt(5,iamount);

int i1 = pstmt1.executeUpdate();

catch(Exception e){

}%></html>

Program to print the monthly Report

//month.jsp

<html>

<%@ page import="java.sql.*"%>

<%String acno=(String)session.getAttribute("sess");

System.out.println(acno);

int chk=Integer.parseInt(acno);

int l=0;

int rowcu=0;

int totalRecords=0;

8
ResultSetMetaData rsmt=null;

ResultSet datars=null;

try{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection

cot=DriverManager.getConnection("jdbc:odbc:ques");

Statement stmtt=cot.createStatement();

Statement rowc=cot.createStatement();

Statement datas=cot.createStatement();

ResultSet resultt=stmtt.executeQuery("select * from month");

ResultSet resucourow=datas.executeQuery("select * from month

where Acno="+chk);

int x=0;

while(resucourow.next()){

x++;

resultt.next();

rsmt=resultt.getMetaData();

l=rsmt.getColumnCount();

System.out.println("Column Count"+l);

System.out.println("Column Count Rowssss "+x);

datars=rowc.executeQuery("select * from month where

Acno="+chk);

}catch(Exception e1){

}%>

<table border="1" bordercolorlight="#CCCC99" bordercolordark="#999966">

<tr>

<%for(int v=1;v<=l;v++){System.out.println("l value"+l);String

cnames=rsmt.getColumnName(v);%>

9
<td width="50%"><font face="Arial, Helvetica" color = 'red'

size='5'><b><i><%=cnames.toUpperCase()%></i></b></font></td>

<%}%>

</tr><%

while(datars.next()){%>

<tr><%for(int vc=1;vc<=l;vc++){%>

<td width="50%"><font face="Arial,

Helvetica"><%=datars.getString(vc)%></font></td><%

}</html> }%>

Q3. Write a JSP program using JDBC to keep records of personal information of its employees. The

program should provide facility of view details of employees, modify their details and add details of

new employees. Design appropriate User Interface and implement proper validation mechanism for

proper and correct data entry. Make necessary assumptions.

Ans.

Add new employees:-

<!DOCTYPE html>

<html>

<head>

<meta charset="ISO-8859-1">

<title>Insert title here</title>

</head>

<body>

<h1>Add New Employee</h1>

<form action="SaveServlet" method="post">

<table>

<tr><td>Name:</td><td><input type="text" name="name"/></td></tr>

<tr><td>Password:</td><td><input type="password" name="password"/></td></tr>

<tr><td>Email:</td><td><input type="email" name="email"/></td></tr>

10
<tr><td>Country:</td><td>

<select name="country" style="width:150px">

<option>India</option>

<option>USA</option>

<option>UK</option>

<option>Other</option>

</select>

</td></tr>

<tr><td colspan="2"><input type="submit" value="Save Employee"/></td></tr>

</table>

</form>

<br/>

<a href="ViewServlet">view employees</a>

</body>

</html>

Update details:-

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet("/EditServlet")

public class EditServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

11
PrintWriterout=response.getWriter();

out.println("<h1>Update Employee</h1>");

String sid=request.getParameter("id");

int id=Integer.parseInt(sid);

Empe=EmpDao.getEmployeeById(id);

out.print("<form action='EditServlet2' method='post'>");

out.print("<table>");

out.print("<tr><td></td><td><input type='hidden' name='id' value='"+e.getId()+"'/></td></tr>");

out.print("<tr><td>Name:</td><td><input type='text' name='name' value='"+e.getName()+"'/></td

></tr>");

out.print("<tr><td>Password:</td><td><input type='password' name='password' value='"+e.getPas

sword()+"'/>

</td></tr>");

out.print("<tr><td>Email:</td><td><input type='email' name='email' value='"+e.getEmail()+"'/></td

></tr>");

out.print("<tr><td>Country:</td><td>");

out.print("<select name='country' style='width:150px'>");

out.print("<option>India</option>");

out.print("<option>USA</option>");

out.print("<option>UK</option>");

out.print("<option>Other</option>");

out.print("</select>");

out.print("</td></tr>");

out.print("<tr><td colspan='2'><input type='submit' value='Edit & Save '/></td></tr>");

out.print("</table>");

out.print("</form>");

out.close();

12
View Details :-

import java.io.IOException;

import java.io.PrintWriter;

import java.util.List;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet("/ViewServlet")

public class ViewServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriterout=response.getWriter();

out.println("<a href='index.html'>Add New Employee</a>");

out.println("<h1>Employees List</h1>");

List<Emp> list=EmpDao.getAllEmployees();

out.print("<table border='1' width='100%'");

out.print("<tr><th>Id</th><th>Name</th><th>Password</th><th>Email</th><th>Country</th>

<th>Edit</th><th>Delete</th></tr>");

for(Empe:list){

out.print("<tr><td>"+e.getId()+"</td><td>"+e.getName()+"</td><td>"+e.getPassword()+"</td>

<td>"+e.getEmail()+"</td><td>"+e.getCountry()+"</td><td><a href='EditServlet?id="+e.getId()

+"'>edit</a></td>

<td><a href='DeleteServlet?id="+e.getId()+"'>delete</a></td></tr>");

out.print("</table>");

out.close();

13
}

Output:-

Add new employee

Update

14
View

Q4.Create an XML document for keeping MCA students information at a study centre of IGNOU.

Ans.

15
PART-II: MCS-053 (Computer Graphics and Multimedia)

Q1. Write a program in C/C++ using OpenGL to draw a Triangle of orange colour and inside

that draw a Circle of green colour.

Ans.

#include <windows.h>

#include <gl/glut.h>

#include <math.h>

const float PI=3.14;

void drawCircle(){

glBegin(GL_LINE_LOOP);

glColor3f(1.0,0.0,0.0);

for(int i =0; i <= 300; i++){

double angle = 2 * PI * i / 300;

double x = 5*cos(angle);

16
double y = 5*sin(angle);

glVertex2d(x,y);

glEnd();

void drawRect(){

glColor3f(0.0,0.0,1.0);

glRectf(-5.0,5.0,5.0,-5.0);

void init(void){

glClearColor(0.0,1.0,0.0,0.0);

glMatrixMode(GL_PROJECTION);

glLoadIdentity();

glOrtho(-10.0,10.0,-10.0,10.0,-10.0,10.0);

void display(void)

glClear(GL_COLOR_BUFFER_BIT);

drawRect();

drawCircle();

glutSwapBuffers();

int main(int argc, char** argv){

glutInit(&argc,argv);

glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);

glutInitWindowSize(320,320);

glutInitWindowPosition(50,50);

glutCreateWindow("2D Shapes");

init();

17
glutDisplayFunc(display);

glutMainLoop();

return 0;

Output :-

Ans.

#include<Windows.h>

// for MS Windows

#include<GL\glut.h>

// GLUT, include glu.h and gl.h

//Note: GLglut.h path depending on the system in use

void init()

// Set display window color to as glClearColor(R,G,B,Alpha)

18
glClearColor(0.5, 0.9, 0.4, 0.0);

// Set projection parameters.

glMatrixMode(GL_PROJECTION);

// Set 2D Transformation as gluOrtho2D(Min Width, Max Width, Min Height, Max Height)

gluOrtho2D(0.0, 800, 0.0, 600);

glVertex2i(100, 350);

glVertex2i(300, 350);

glEnd();

// Front Wall

glColor3f(0.7, 0.2, 0.3);

glBegin(GL_POLYGON);

glVertex2i(100, 350);

glVertex2i(300, 350);

glVertex2i(300, 100);

glVertex2i(100, 100);

glEnd();

// Front Door

glColor3f(0.7, 0.2, 0.9);

glBegin(GL_POLYGON);

glVertex2i(150, 250);

glVertex2i(250, 250);

glVertex2i(250, 100);

glVertex2i(150, 100);

glEnd();

// Front Door Lock

glColor3f(0.3, 0.7, 0.9);

glPointSize(15);

glBegin(GL_POINTS);

19
glVertex2i(170, 170);

glEnd();

//side Wall

glColor3f(0.1, 0.2, 0.3);

glBegin(GL_POLYGON);

glVertex2i(300, 350);

glVertex2i(700, 350);

glVertex2i(700, 100);

glVertex2i(300, 100);

glEnd();

// line of window one

glColor3f(0.1, 0.7, 0.5);

glLineWidth(5);

glBegin(GL_LINES);

glVertex2i(390, 320);

glVertex2i(390, 230);

glVertex2i(330, 273);

glVertex2i(450, 273);

glEnd();

// window two

glColor3f(0.2, 0.4, 0.3);

glBegin(GL_POLYGON);

glVertex2i(530, 320);

glVertex2i(650, 320);

glVertex2i(650, 230);

glVertex2i(530, 230);

glEnd();

20
// lines of window two

glColor3f(0.1, 0.7, 0.5);

glLineWidth(5);

glBegin(GL_LINES);

glVertex2i(590, 320);

glVertex2i(590, 230);

glVertex2i(530, 273);

glVertex2i(650, 273);

glEnd();

// Entrance Path

glColor3f(0.3, 0.5, 0.7);

glLineWidth(3);

glBegin(GL_POLYGON);

glVertex2i(150, 100);

glVertex2i(250, 100);

glVertex2i(210, 0);

glVertex2i(40, 0);

glEnd();

// Process all OpenGL routine s as quickly as possible

glFlush();

int main(int argc, char ** argv)

// Initialize GLUT

21
// window one

glColor3f(0.2, 0.4, 0.3);

glBegin(GL_POLYGON);

glVertex2i(330, 320);

glVertex2i(450, 320);

glVertex2i(450, 230);

glVertex2i(330, 230);

glEnd();

void home()

//Roof

glClear(GL_COLOR_BUFFER_BIT); // Clear display window

// Set line segment color as glColor3f(R,G,B)

glColor3f(0.3, 0.5, 0.8);

glBegin(GL_POLYGON);

glVertex2i(200, 500);

glVertex2i(600, 500);

glVertex2i(700, 350);

glVertex2i(300, 350);

glEnd();

// Top of Front Wall

glColor3f(0.1, 0.5, 0.0);

glBegin(GL_TRIANGLES);

glVertex2i(200, 500);

glutInit(&argc, argv);

// Set display mode

glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);

// Set top - left display window position.

22
glutInitWindowPosition(100, 100);

// Set display window width and height

glutInitWindowSize(800, 600);

// Create display window with the given title

glutCreateWindow("2D House in OpenGL ");

// Execute initialization procedure

init();

// Send graphics to display window

glutDisplayFunc(home);

// Display everything and wait.

glutMainLoop();

Q3. Write a program in C or C++ to implement Scan-Line Polygon Filling Algorithm.

Ans.

// CPP program to illustrate

// Scanline Polygon fill Algorithm

#include <stdio.h>

#include <math.h>

#include <GL/glut.h>

#define maxHt 800

#define maxWd 600

#define maxVer 10000

FILE *fp;

// Start from lower left corner

typedef struct edgebucket

int ymax; //max y-coordinate of edge

float xofymin; //x-coordinate of lowest edge point updated only in aet

23
float slopeinverse;

}EdgeBucket;

typedef struct edgetabletup

// the array will give the scanline number

// The edge table (ET) with edges entries sorted

// in increasing y and x of the lower end

int countEdgeBucket; //no. of edgebuckets

EdgeBucket buckets[maxVer];

}EdgeTableTuple;

EdgeTableTuple EdgeTable[maxHt], ActiveEdgeTuple;

// Scanline Function

void initEdgeTable()

int i;

for (i=0; i<maxHt; i++)

EdgeTable[i].countEdgeBucket = 0;

ActiveEdgeTuple.countEdgeBucket = 0;

void printTuple(EdgeTableTuple *tup)

int j;

if (tup->countEdgeBucket)

printf("\nCount %d-----\n",tup->countEdgeBucket);

for (j=0; j<tup->countEdgeBucket; j++)

printf(" %d+%.2f+%.2f",

24
tup->buckets[j].ymax, tup->buckets[j].xofymin,tup->buckets[j].slopeinverse);

}}

void printTable()

int i,j;

for (i=0; i<maxHt; i++)

if (EdgeTable[i].countEdgeBucket)

printf("\nScanline %d", i);

printTuple(&EdgeTable[i]);

/* Function to sort an array using insertion sort*/

void insertionSort(EdgeTableTuple *ett)

int i,j;

EdgeBucket temp;

for (i = 1; i < ett->countEdgeBucket; i++)

temp.ymax = ett->buckets[i].ymax;

temp.xofymin = ett->buckets[i].xofymin;

temp.slopeinverse = ett->buckets[i].slopeinverse;

j = i - 1;

while ((temp.xofymin < ett->buckets[j].xofymin) && (j >= 0))

ett->buckets[j + 1].ymax = ett->buckets[j].ymax;

ett->buckets[j + 1].xofymin = ett->buckets[j].xofymin;

ett->buckets[j + 1].slopeinverse = ett->buckets[j].slopeinverse;

j = j - 1;

25
}

ett->buckets[j + 1].ymax = temp.ymax;

ett->buckets[j + 1].xofymin = temp.xofymin;

ett->buckets[j + 1].slopeinverse = temp.slopeinverse;

void storeEdgeInTuple (EdgeTableTuple *receiver,int ym,int xm,float slopInv)

// both used for edgetable and active edge table..

// The edge tuple sorted in increasing ymax and x of the lowerend.

(receiver->buckets[(receiver)->countEdgeBucket]).ymax = ym;

(receiver->buckets[(receiver)->countEdgeBucket]).xofymin = (float)xm;

(receiver->buckets[(receiver)->countEdgeBucket]).slopeinverse = slopInv;

// sort the buckets

insertionSort(receiver);

(receiver->countEdgeBucket)++;

void storeEdgeInTable (int x1,int y1, int x2, int y2)

{float m,minv;

int ymaxTS,xwithyminTS, scanline; //ts stands for to store

if (x2==x1)

minv=0.000000;

else

m = ((float)(y2-y1))/((float)(x2-x1));

// horizontal lines are not stored in edge table

if (y2==y1)

26
return;

minv = (float)1.0/m;

printf("\nSlope string for %d %d & %d %d: %f",x1,y1,x2,y2,minv);

if (y1>y2)

scanline=y2;

ymaxTS=y1;

xwithyminTS=x2;

else

scanline=y1;

ymaxTS=y2;

xwithyminTS=x1;

// the assignment part is done..now storage..

storeEdgeInTuple(&EdgeTable[scanline],ymaxTS,xwithyminTS,minv);

void removeEdgeByYmax(EdgeTableTuple *Tup,int yy)

{int i,j;

for (i=0; i< Tup->countEdgeBucket; i++)

if (Tup->buckets[i].ymax == yy)

printf("\nRemoved at %d",yy);

for ( j = i ; j < Tup->countEdgeBucket -1 ; j++ )

Tup->buckets[j].ymax =Tup->buckets[j+1].ymax;

27
Tup->buckets[j].xofymin =Tup->buckets[j+1].xofymin;

Tup->buckets[j].slopeinverse = Tup->buckets[j+1].slopeinverse;

Tup->countEdgeBucket--;

i--;

void updatexbyslopeinv(EdgeTableTuple *Tup)

int i;

for (i=0; i<Tup->countEdgeBucket; i++)

(Tup->buckets[i]).xofymin =(Tup->buckets[i]).xofymin + (Tup->buckets[i]).slopeinverse;

void ScanlineFill()

/* Follow the following rules:

1. Horizontal edges: Do not include in edge table

2. Horizontal edges: Drawn either on the bottom or on the top.

3. Vertices: If local max ormin, then count twice, else count

once.

4. Either vertices at local minima or at local maxima are drawn.*/

int i, j, x1, ymax1, x2, ymax2, FillFlag = 0, coordCount;

// we will start from scanline 0;

// Repeat until last scanline:

for (i=0; i<maxHt; i++)//4. Increment y by 1 (next scan line)

28
// 1. Move from ET bucket y to the

// AET those edges whose ymin = y (entering edges)

for (j=0; j<EdgeTable[i].countEdgeBucket; j++)

storeEdgeInTuple(&ActiveEdgeTuple,EdgeTable[i].buckets[j].

ymax,EdgeTable[i].buckets[j].xofymin,

EdgeTable[i].buckets[j].slopeinverse);

printTuple(&ActiveEdgeTuple);

// 2. Remove from AET those edges for

// which y=ymax (not involved in next scan line)

removeEdgeByYmax(&ActiveEdgeTuple, i);

//sort AET (remember: ET is presorted)

insertionSort(&ActiveEdgeTuple);

printTuple(&ActiveEdgeTuple);

//3. Fill lines on scan line y by using pairs of x-coords from AET

j = 0;

FillFlag = 0;

coordCount = 0;

x1 = 0;

x2 = 0;

ymax1 = 0;

ymax2 = 0;

while (j<ActiveEdgeTuple.countEdgeBucket)

if (coordCount%2==0)

x1 = (int)(ActiveEdgeTuple.buckets[j].xofymin);

ymax1 = ActiveEdgeTuple.buckets[j].ymax;

29
if (x1==x2)

/* three cases can arrive-

1. lines are towards top of the intersection

2. lines are towards bottom

3. one line is towards top and other is towards bottom

*/

if

(((x1==ymax1)&&(x2!=ymax2))||((x1!=ymax1)&&(x2==ymax2)))

x2 = x1;

ymax2 = ymax1;

}else

{coordCount++;

else

coordCount++;

else

x2 = (int)ActiveEdgeTuple.buckets[j].xofymin;

ymax2 = ActiveEdgeTuple.buckets[j].ymax;

FillFlag = 0;

// checking for intersection...

if (x1==x2)

30
/*three cases can arive-

1. lines are towards top of the intersection

2. lines are towards bottom

3. one line is towards top and other is towards bottom

*/

if

(((x1==ymax1)&&(x2!=ymax2))||((x1!=ymax1)&&(x2==ymax2)))

x1 = x2;

ymax1 = ymax2;

else

coordCount++;

FillFlag = 1;

else

coordCount++;

FillFlag = 1;

if(FillFlag)

//drawing actual lines...

glColor3f(0.0f,0.7f,0.0f);

glBegin(GL_LINES);

glVertex2i(x1,i);

glVertex2i(x2,i);

31
glEnd();

glFlush();

// printf("\nLine drawn from %d,%d to %d,%d",x1,i,x2,i);

j++;

// 5. For each nonvertical edge remaining in AET, update x for new y

updatexbyslopeinv(&ActiveEdgeTuple);

printf("\nScanline filling complete");

void myInit(void)

glClearColor(1.0,1.0,1.0,0.0);

glMatrixMode(GL_PROJECTION);

glLoadIdentity();

gluOrtho2D(0,maxHt,0,maxWd);

glClear(GL_COLOR_BUFFER_BIT);

void drawPolyDino()

glColor3f(1.0f,0.0f,0.0f);

int count = 0,x1,y1,x2,y2;

rewind(fp);

while(!feof(fp) )

count++;

if (count>2)

32
{

x1 = x2;

y1 = y2;

count=2;

if (count==1)

{fscanf(fp, "%d,%d", &x1, &y1);

else

fscanf(fp, "%d,%d", &x2, &y2);

printf("\n%d,%d", x2, y2);

glBegin(GL_LINES);

glVertex2i( x1, y1);

glVertex2i( x2, y2);

glEnd();

storeEdgeInTable(x1, y1, x2, y2);//storage of edges in edge table.

glFlush();

}}}

void drawDino(void)

{initEdgeTable();

drawPolyDino();

printf("\nTable");

printTable();

ScanlineFill();//actual calling of scanline filling..

void main(int argc, char** argv)

fp=fopen ("PolyDino.txt","r");

33
if ( fp == NULL )

printf( "Could not open file" ) ;

return;

glutInit(&argc, argv);

glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);

glutInitWindowSize(maxHt,maxWd);

glutInitWindowPosition(100, 150);

glutCreateWindow("Scanline filled dinosaur");

myInit();

glutDisplayFunc(drawDino);

glutMainLoop();

fclose(fp);

Output:-

Q4. Write a program in C/C++ to implement Cohen-Sutherland line clipping algorithm. In this

implementation consider two cases of a line: totally visible, totally invisible, against the rectangular

clipping window.

Ans.

// C++ program to implement Cohen Sutherland algorithm for line clipping.

34
#include <iostream>

using namespace std;

// Defining region codes

const int INSIDE = 0; // 0000

const int LEFT = 1; // 0001

const int RIGHT = 2; // 0010

const int BOTTOM = 4; // 0100

const int TOP = 8; // 1000

// Defining x_max, y_max and x_min, y_min for

// clipping rectangle. Since diagonal points are

// enough to define a rectangle

const int x_max = 10;

const int y_max = 8;

const int x_min = 4;

const int y_min = 4;

// Function to compute region code for a point(x, y)

int computeCode(double x, double y)

// initialized as being inside

int code = INSIDE;

if (x < x_min) // to the left of rectangle

code |= LEFT;

else if (x > x_max) // to the right of rectangle

code |= RIGHT;

if (y < y_min) // below the rectangle

code |= BOTTOM;

else if (y > y_max) // above the rectangle

code |= TOP;

return code;

35
}

// Implementing Cohen-Sutherland algorithm

// Clipping a line from P1 = (x2, y2) to P2 = (x2, y2)

void cohenSutherlandClip(double x1, double y1,

double x2, double y2)

// Compute region codes for P1, P2

int code1 = computeCode(x1, y1);

int code2 = computeCode(x2, y2);

// Initialize line as outside the rectangular window

bool accept = false;

while (true)

if ((code1 == 0) && (code2 == 0))

// If both endpoints lie within rectangle

accept = true;

break;

else if (code1 & code2)

// If both endpoints are outside rectangle,

// in same region

break;

else

// Some segment of line lies within the

// rectangle

36
int code_out;

double x, y;

// At least one endpoint is outside the

// rectangle, pick it.

if (code1 != 0)

code_out = code1;

else

code_out = code2;

// Find intersection point;

// using formulas y = y1 + slope * (x - x1),

// x = x1 + (1 / slope) * (y -y1)

if (code_out & TOP)

// point is above the clip rectangle

x = x1 + (x2 - x1) * (y_max - y1) / (y2 - y1);

y = y_max;

else if (code_out & BOTTOM)

// point is below the rectangle

x = x1 + (x2 - x1) * (y_min - y1) / (y2 - y1);

y = y_min;

else if (code_out & RIGHT)

// point is to the right of rectangle

y = y1 + (y2 - y1) * (x_max - x1) / (x2 - x1);

x = x_max;

37
else if (code_out & LEFT)

// point is to the left of rectangle

y = y1 + (y2 - y1) * (x_min - x1) / (x2 - x1);

x = x_min;

// Now intersection point x,y is found

// We replace point outside rectangle

// by intersection point

if (code_out == code1)

x1 = x;

y1 = y;

code1 = computeCode(x1, y1);

else

x2 = x;

y2 = y;

code2 = computeCode(x2, y2);

if (accept)

cout <<"Line accepted from " << x1 << ", "

<< y1 << " to "<< x2 << ", " << y2 << endl;

// Here the user can add code to display the rectangle

// along with the accepted (portion of) lines

38
}

Else

cout << "Line rejected" << endl;

// Driver code

int main()

// First Line segment

// P11 = (5, 5), P12 = (7, 7)

cohenSutherlandClip(5, 5, 7, 7);

// Second Line segment

// P21 = (7, 9), P22 = (11, 4)

cohenSutherlandClip(7, 9, 11, 4);

// Third Line segment

// P31 = (1, 5), P32 = (4, 1)

cohenSutherlandClip(1, 5, 4, 1);

return 0;

Output:-

Line accepted from 5.00,5.00 to 7.00,7.00

Line accepted from 7.80,8.00 to 10.00,5.25

Line rejected

39

Vous aimerez peut-être aussi