0% found this document useful (0 votes)
12 views

Computer Graphics Group Assignment 2

The document describes code for clipping lines and polygons using the Cohen-Sutherland algorithm. It includes code to: 1. Get user input for the coordinates of the clipping window and line/polygon vertices. 2. Draw the original and clipped shapes. 3. Clip lines by checking if points fall outside the window and adjusting if needed. 4. Clip polygons by looping through window edges to add intersection points between edges and shape sides to the new clipped vertex list.

Uploaded by

klli234ad
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Computer Graphics Group Assignment 2

The document describes code for clipping lines and polygons using the Cohen-Sutherland algorithm. It includes code to: 1. Get user input for the coordinates of the clipping window and line/polygon vertices. 2. Draw the original and clipped shapes. 3. Clip lines by checking if points fall outside the window and adjusting if needed. 4. Clip polygons by looping through window edges to add intersection points between edges and shape sides to the new clipped vertex list.

Uploaded by

klli234ad
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Dammarice Marura BUS-242-001/2020

Gideon Lesia BUS-242-025/2020


Isadia Nzuma BUS-242-043/2020
Samson Oyugi BUS-242-045/2020

5. LINE CLIPING USING COHEN-SUTHERLAND ALGORITHM


// Import the graphics and scanner packages
import java.awt.Graphics;
import javax.swing.JFrame;
import java.util.Scanner;

public class Line {


// Define the variables
double m = 0; // The slope of the line
double xmin = 0; // The minimum x-coordinate of the clipping window
double ymin = 0; // The minimum y-coordinate of the clipping window
double xmax = 0; // The maximum x-coordinate of the clipping window
double ymax = 0; // The maximum y-coordinate of the clipping window
double x1 = 0; // The x-coordinate of the first point of the line
double y1 = 0; // The y-coordinate of the first point of the line
double x2 = 0; // The x-coordinate of the second point of the line
double y2 = 0; // The y-coordinate of the second point of the line

// The constructor
Line() {
// Create a graphics frame
JFrame frame = new JFrame("Clipping");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

// Create a scanner object


Scanner sc = new Scanner(System.in);

// Get the user input


System.out.print("Enter the xmin: ");
xmin = sc.nextDouble();
System.out.print("Enter the ymin: ");
ymin = sc.nextDouble();
System.out.print("Enter the xmax: ");
xmax = sc.nextDouble();
System.out.print("Enter the ymax: ");
ymax = sc.nextDouble();
System.out.print("Enter x1: ");
x1 = sc.nextDouble();
System.out.print("Enter y1: ");
y1 = sc.nextDouble();
System.out.print("Enter x2: ");
x2 = sc.nextDouble();
System.out.print("Enter y2: ");
y2 = sc.nextDouble();

// Get the graphics object


Graphics g = frame.getGraphics();

// Draw the clipping window


g.drawRect((int)xmin, (int)ymin, (int)(xmax - xmin), (int)(ymax - ymin));

// Draw the original line


g.drawLine((int)x1, (int)y1, (int)x2, (int)y2);

// Calculate the slope of the line


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

// Clip the line using the Cohen-Sutherland algorithm


// Check if the line is parallel to the left or right edge
if (x1 == x2) {
// Clip the line to the left or right edge
x1 = x2 = Math.min(Math.max(x1, xmin), xmax);
// Clip the y-coordinates to the window boundaries
y1 = Math.min(Math.max(y1, ymin), ymax);
y2 = Math.min(Math.max(y2, ymin), ymax);
}
// Check if the line is parallel to the top or bottom edge
else if (y1 == y2) {
// Clip the line to the top or bottom edge
y1 = y2 = Math.min(Math.max(y1, ymin), ymax);
// Clip the x-coordinates to the window boundaries
x1 = Math.min(Math.max(x1, xmin), xmax);
x2 = Math.min(Math.max(x2, xmin), xmax);
}
// Otherwise, use the Cohen-Sutherland algorithm
else {
// Check if the first point is outside the window
if (x1 < xmin) {
// Clip the left edge
y1 = y1 + m * (xmin - x1);
x1 = xmin;
}
if (y1 < ymin) {
// Clip the bottom edge
x1 = x1 + (ymin - y1) / m;
y1 = ymin;
}
if (x1 > xmax) {
// Clip the right edge
y1 = y1 - m * (x1 - xmax);
x1 = xmax;
}
if (y1 > ymax) {
// Clip the top edge
x1 = x1 - (y1 - ymax) / m;
y1 = ymax;
}

// Check if the second point is outside the window


if (x2 < xmin) {
// Clip the left edge
y2 = y2 + m * (xmin - x2);
x2 = xmin;
}
if (y2 < ymin) {
// Clip the bottom edge
x2 = x2 + (ymin - y2) / m;
y2 = ymin;
}
if (x2 > xmax) {
// Clip the right edge
y2 = y2 - m * (x2 - xmax);
x2 = xmax;
}
if (y2 > ymax) {
// Clip the top edge
x2 = x2 - (y2 - ymax) / m;
y2 = ymax;
}
}

// Draw the clipped line


g.drawLine((int)x1, (int)y1, (int)x2, (int)y2);

// Print the coordinates of the clipped line


System.out.println("After clipping: " + x1 + ", " + y1 + ", " + x2 + ", " + y2);
}
// The main method
public static void main(String[] args) {
// Create an instance of Line
Line p = new Line();
}
}
6. POLYGON CLIPPING USING COHEN-SUTHERLAND ALGORITHM
// Import the graphics and scanner packages
import java.awt.Graphics;
import javax.swing.JFrame;
import java.util.Scanner;

public class Poly {


// Define the variables
double m = 0; // The slope of the line
double xmin = 0; // The minimum x-coordinate of the clipping window
double ymin = 0; // The minimum y-coordinate of the clipping window
double xmax = 0; // The maximum x-coordinate of the clipping window
double ymax = 0; // The maximum y-coordinate of the clipping window
double x1 = 0; // The x-coordinate of the first point of the polygon
double y1 = 0; // The y-coordinate of the first point of the polygon
double x2 = 0; // The x-coordinate of the second point of the polygon
double y2 = 0; // The y-coordinate of the second point of the polygon
double x3 = 0; // The x-coordinate of the third point of the polygon
double y3 = 0; // The y-coordinate of the third point of the polygon
double x4 = 0; // The x-coordinate of the fourth point of the polygon
double y4 = 0; // The y-coordinate of the fourth point of the polygon
double x5 = 0; // The x-coordinate of the fifth point of the polygon
double y5 = 0; // The y-coordinate of the fifth point of the polygon

// The constructor
Poly() {
// Create a graphics frame
JFrame frame = new JFrame("Clipping");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

// Create a scanner object


Scanner sc = new Scanner(System.in);

// Get the user input


System.out.print("Enter the xmin: ");
xmin = sc.nextDouble();
System.out.print("Enter the ymin: ");
ymin = sc.nextDouble();
System.out.print("Enter the xmax: ");
xmax = sc.nextDouble();
System.out.print("Enter the ymax: ");
ymax = sc.nextDouble();
System.out.print("Enter x1: ");
x1 = sc.nextDouble();
System.out.print("Enter y1: ");
y1 = sc.nextDouble();
System.out.print("Enter x2: ");
x2 = sc.nextDouble();
System.out.print("Enter y2: ");
y2 = sc.nextDouble();
System.out.print("Enter x3: ");
x3 = sc.nextDouble();
System.out.print("Enter y3: ");
y3 = sc.nextDouble();
System.out.print("Enter x4: ");
x4 = sc.nextDouble();
System.out.print("Enter y4: ");
y4 = sc.nextDouble();
System.out.print("Enter x5: ");
x5 = sc.nextDouble();
System.out.print("Enter y5: ");
y5 = sc.nextDouble();

// Get the graphics object


Graphics g = frame.getGraphics();

// Draw the clipping window


g.drawRect((int)xmin, (int)ymin, (int)(xmax - xmin), (int)(ymax - ymin));

// Draw the original polygon


g.drawLine((int)x1, (int)y1, (int)x2, (int)y2);
g.drawLine((int)x2, (int)y2, (int)x3, (int)y3);
g.drawLine((int)x3, (int)y3, (int)x4, (int)y4);
g.drawLine((int)x4, (int)y4, (int)x5, (int)y5);
g.drawLine((int)x5, (int)y5, (int)x1, (int)y1);

// Clip the polygon using the Sutherland-Hodgman algorithm


// Define an array of vertices for the polygon
double[][] vertices = {{x1, y1}, {x2, y2}, {x3, y3}, {x4, y4}, {x5, y5}};
// Define an array of edges for the clipping window
double[][] edges = {{xmin, ymin, xmax, ymin}, {xmax, ymin, xmax, ymax}, {xmax, ymax,
xmin, ymax}, {xmin, ymax, xmin, ymin}};
// Loop through each edge of the clipping window
for (double[] edge : edges) {
// Define the variables for the edge
double x1e = edge[0]; // The x-coordinate of the first point of the edge
double y1e = edge[1]; // The y-coordinate of the first point of the edge
double x2e = edge[2]; // The x-coordinate of the second point of the edge
double y2e = edge[3]; // The y-coordinate of the second point of the edge
// Define a temporary array to store the new vertices
double[][] temp = new double[vertices.length * 2][2];
// Define a counter for the new vertices
int k = 0;
// Loop through each vertex of the polygon
for (int i = 0; i < vertices.length; i++) {
// Define the variables for the current vertex
double x1v = vertices[i][0]; // The x-coordinate of the current vertex
double y1v = vertices[i][1]; // The y-coordinate of the current vertex
// Define the variables for the next vertex
double x2v = vertices[(i + 1) % vertices.length][0]; // The x-coordinate of the next
vertex
double y2v = vertices[(i + 1) % vertices.length][1]; // The y-coordinate of the next
vertex
// Check if the current vertex is inside the edge
boolean inside1 = (x2e - x1e) * (y1v - y1e) - (y2e - y1e) * (x1v - x1e) >= 0;
// Check if the next vertex is inside the edge
boolean inside2 = (x2e - x1e) * (y2v - y1e) - (y2e - y1e) * (x2v - x1e) >= 0;
// If both vertices are inside the edge, add the next vertex to the new vertices
if (inside1 && inside2) {
temp[k][0] = x2v;
temp[k][1] = y2v;
k++;
}
// If the current vertex is inside the edge and the next vertex is outside the edge, add the
intersection point to the new vertices
else if (inside1 && !inside2) {
// Calculate the intersection point using the parametric equation of the line
double t = ((x1e - x1v) * (y1e - y2e) - (y1e - y1v) * (x1e - x2e)) / ((x1v - x2v) * (y1e
- y2e) - (y1v - y2v) * (x1e - x2e));
double x = x1v + t * (x2v - x1v);
double y = y1v + t * (y2v - y1v);
temp[k][0] = x;
temp[k][1] = y;
k++;
}
// If the current vertex is outside the edge and the next vertex is inside the edge, add the
intersection point and the next vertex to the new vertices
else if (!inside1 && inside2) {
// Calculate the intersection point using the parametric equation of the line
double t = ((x1e - x1v) * (y1e - y2e) - (y1e - y1v) * (x1e - x2e)) / ((x1v - x2v) * (y1e
- y2e) - (y1v - y2v) * (x1e - x2e));
double x = x1v + t * (x2v - x1v);
double y = y1v + t * (y2v - y1v);
temp[k][0] = x;
temp[k][1] = y;
k++;
temp[k][0] = x2v;
temp[k][1] = y2v;
k++;
}
// If both vertices are outside the edge, do nothing
}
// Copy the new vertices to the original vertices array
vertices = new double[k][2];
for (int i = 0; i < k; i++) {
vertices[i][0] = temp[i][0];
vertices[i][1] = temp[i][1];
}
}

// Draw the clipped polygon


for (int i = 0; i < vertices.length; i++) {
g.drawLine((int)vertices[i][0], (int)vertices[i][1], (int)vertices[(i + 1) % vertices.length]
[0], (int)vertices[(i + 1) % vertices.length][1]);
}

// Print the coordinates of the clipped polygon


System.out.print("After clipping: ");
for (int i = 0; i < vertices.length; i++) {
System.out.print(vertices[i]);}}}
7. 3D TRANSFORMATION
import java.awt.*;
import java.util.Scanner;
import javax.swing.JFrame;

public class Main extends JFrame {

int maxx, maxy, midx, midy;


Graphics g;

public Main() {
super("3D Transformation");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 600);
setVisible(true);
maxx = getWidth();
maxy = getHeight();
midx = maxx / 2;
midy = maxy / 2;
g = getGraphics();
}

public void axis() {


g.setColor(Color.blue);
g.drawLine(midx, 0, midx, maxy);
g.drawLine(0, midy, maxx, midy);
}

public void bar3d(int x1, int y1, int x2, int y2, int z, int c) {
g.setColor(new Color(c, c, c));
int[] x = {x1, x2, x2, x1, x1};
int[] y = {y1, y1, y2, y2, y1};
g.fillPolygon(x, y, 5);
int[] x3 = {x1, x1 + z, x2 + z, x2, x1};
int[] y3 = {y1, y1 - z, y1 - z, y1, y1};
g.fillPolygon(x3, y3, 5);
int[] x4 = {x2, x2 + z, x2 + z, x2, x2};
int[] y4 = {y1, y1 - z, y2 - z, y2, y1};
g.fillPolygon(x4, y4, 5);
}

public void draw() {


Scanner sc = new Scanner(System.in);
System.out.println("3D Transformation");
System.out.println(" 1.Translation");
System.out.println(" 2.Scaling");
System.out.println(" 3.Rotation");
System.out.println(" 4.Exit");
System.out.println("Enter your choice:");
int ch = sc.nextInt();
switch (ch) {
case 1: {
clear();
axis();
bar3d(midx + 50, midy - 100, midx + 60, midy - 90, 10, 1);
System.out.println("Enter the translation factor:");
int x = sc.nextInt();
int y = sc.nextInt();
clear();
axis();
bar3d(midx + 50, midy - 100, midx + 60, midy - 90, 10, 1);
System.out.println("After translation");
bar3d(midx + x + 50, midy - (y + 100), midx + x + 60, midy - (y + 90), 10, 1);
break;
}
case 2: {
axis();
bar3d(midx + 50, midy - 100, midx + 60, midy - 90, 5, 1);
System.out.println("Enter the scaling factor:");
int x = sc.nextInt();
int y = sc.nextInt();
int z = sc.nextInt();
clear();
axis();
bar3d(midx + 50, midy - 100, midx + 60, midy - 90, 5, 1);
System.out.println("After scaling");
bar3d(midx + (x * 50), midy - (y * 100), midx + (x * 60), midy - (y * 90), 5 * z, 1);
break;
}
case 3: {
System.out.println("Enter the rotation angle:");
int t = sc.nextInt();
int x1 = (int) (50 * Math.cos(t * (Math.PI / 180)) - 100 * Math.sin(t * (Math.PI /
180)));
int y1 = (int) (50 * Math.sin(t * (Math.PI / 180)) + 100 * Math.cos(t * (Math.PI /
180)));
int x2 = (int) (60 * Math.cos(t * (Math.PI / 180)) - 90 * Math.sin(t * (Math.PI / 180)));
int y2 = (int) (60 * Math.sin(t * (Math.PI / 180)) + 90 * Math.cos(t * (Math.PI /
180)));
System.out.println(" 1.z-axis");
System.out.println(" 2.x-axis");
System.out.println(" 3.y-axis");
System.out.println("Enter your choice:");
int choice = sc.nextInt();
switch (choice) {
case 1: {
clear();
axis();
System.out.println("After rotation about z-axis");
bar3d(midx + x1, midy - y1, midx + x2, midy - y2, 5, 1);
break;
}
case 2: {
clear();
axis();
System.out.println("After rotation about x-axis");
bar3d(midx + 50, midy - x1, midx + 60, midy - x2, 5 - y1, 1);
break;
}
case 3: {
clear();
axis();
System.out.println("After rotation about y-axis");
bar3d(midx + y1, midy - 100, midx + y2, midy - 90, 5 - x1, 1);
break;
}
}
break;
}
case 4: {
System.exit(0);
}
}
}

public void clear() {


g.setColor(Color.white);
g.fillRect(0, 0, maxx, maxy);
}

public static void main(String[] args) {


Main m = new Main();
m.draw();
}
}
8. COMPOSITE 2D TRANSFORMATION
# Import the necessary modules
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
import math

# Define the vertices of the object


vertices = (
(1, -1, -1),
(1, 1, -1),
(-1, 1, -1),
(-1, -1, -1),
(1, -1, 1),
(1, 1, 1),
(-1, -1, 1),
(-1, 1, 1)
)
# Define the edges of the object
edges = (
(0,1),
(0,3),
(0,4),
(2,1),
(2,3),
(2,7),
(6,3),
(6,4),
(6,7),
(5,1),
(5,4),
(5,7)
)

# Define the colors of the object


colors = (
(1,0,0),
(0,1,0),
(0,0,1),
(0,1,0),
(1,1,1),
(0,1,1),
(1,0,0),
(0,1,0),
(0,0,1),
(1,0,0),
(1,1,1),
(0,1,1),
)

# Define a function to draw the object


def Cube():
glBegin(GL_LINES)
for edge in edges:
for vertex in edge:
glColor3fv(colors[vertex])
glVertex3fv(vertices[vertex])
glEnd()

# Input the object coordinates


x = float(input("Enter x coordinate: "))
y = float(input("Enter y coordinate: "))
az = float(input("Enter z coordinate: "))
w = float(input("Enter w coordinate: "))
p = float(input("Enter p coordinate: "))
q = float(input("Enter q coordinate: "))

# Translation
tx = float(input("Enter the translation factor tx: "))
ty = float(input("Enter the translation factor ty: "))

# Rotation
ra = float(input("Enter the radian value ra: "))
# Calculate theta value
theta = (float)(3.14*ra)/180
# Calculate the x,y,p,q values
x = x*math.cos(theta) - y*math.sin(theta)
y = x*math.sin(theta) + y*math.cos(theta)
p = p*math.cos(theta) - q*math.sin(theta)
q = p*math.sin(theta) + q*math.cos(theta)

# Scaling
sx = float(input("Enter the scaled factor sx: "))
sy = float(input("Enter the scaled factor sy: "))
# Transform the coordinates
x = x*sx
y = y*sy
az = az*sx
w = w*sy
p = p*sx
q = q*sy

# Reflection
# Choose the axis of reflection
axis = input("Enter the axis of reflection (x, y or both): ")
if axis == "x":
# Along x-axis
theta = (float)(90*(3.14/180))
elif axis == "y":
# Along y-axis
theta = (float)(270*(3.14/180))
elif axis == "both":
# Along both-axis
theta = (float)(180*(3.14/180))
else:
# Invalid input
print("Invalid axis")
exit()
# Calculate the x,y,p,q values
x = x*math.cos(theta) - y*math.sin(theta)
y = x*math.sin(theta) + y*math.cos(theta)
p = p*math.cos(theta) - q*math.sin(theta)
q = p*math.sin(theta) + q*math.cos(theta)

# Shearing
# Choose the direction of shearing
direction = input("Enter the direction of shearing (x or y): ")
if direction == "x":
# Along x-direction
xls = float(input("Enter the shearing factor xls: "))
# Transform the coordinates
y=y
x = x + (xls*y)
w=w
az = az + (xls*w)
q=q
p = p + (xls*q)
elif direction == "y":
# Along y-direction
yls = float(input("Enter the shearing factor yls: "))
# Transform the coordinates
x=x
y = y + (yls*x)
az = az
w = w + (yls*az)
p=p
q = q + (yls*p)
else:
# Invalid input
print("Invalid direction")
exit()

# Initialize pygame and set the display mode


pygame.init()
display = (800,600)
pygame.display.set_mode(display, DOUBLEBUF|OPENGL)

# Set the perspective and the view angle


gluPerspective(45, (display[0]/display[1]), 0.1, 50.0)
glTranslatef(0.0,0.0, -10)

# Move and rotate the original coordinate position


glTranslatef(tx, ty, 0)
glRotatef(theta, x, y, 0)

# Draw the object


Cube()

# Main loop
while True:
# Handle the events
pygame.event.pump()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
# Update the display only once per frame
pygame.display.flip()
pygame.time.wait(10)
For the above output we used the values below

Enter x coordinate: 1
Enter y coordinate: 1
Enter z coordinate: 1
Enter w coordinate: 1
Enter p coordinate: 1
Enter q coordinate: 1
Enter the translation factor tx: -2
Enter the translation factor ty: -2
Enter the radian value ra: -30
Enter the scaled factor sx: 0.5
Enter the scaled factor sy: 0.5
Enter the axis of reflection (x, y or both): y
Enter the direction of shearing (x or y): x
Enter the shearing factor xls: 0.3
9 3D PROJECTIONS
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
import math

s = int(input("Enter the number of sides: "))


d = int(input("Enter the depth value: "))
angle = 360 / s
radius = 1
points = []

for i in range(s):
x = radius * math.cos(math.radians(i * angle))
y = radius * math.sin(math.radians(i * angle))
points.append((x, y, 0))

points.extend([(x, y, d) for x, y, _ in points])

colors = (
(1, 0, 0),
(0, 1, 0),
(0, 0, 1),
(1, 1, 0),
(1, 0, 1),
(0, 1, 1),
)

edges = []
for i in range(s):
edges.append((i, (i + 1) % s))
edges.append((i, i + s))
edges.append((i + s, (i + 1) % s + s))

faces = []
for i in range(s):
faces.append((i, (i + 1) % s, (i + 1) % s + s, i + s))
faces.append(tuple(range(s)))
faces.append(tuple(range(s, 2 * s)))

def draw3d():
glBegin(GL_QUADS)
for i, face in enumerate(faces):
color = colors[i % len(colors)]
glColor3fv(color)
for vertex in face:
glVertex3fv(points[vertex])
glEnd()

glBegin(GL_LINES)
glColor3fv((0, 0, 0))
for edge in edges:
for vertex in edge:
glVertex3fv(points[vertex])
glEnd()

pygame.init()
display = (800, 600)
pygame.display.set_mode(display, DOUBLEBUF | OPENGL)

gluPerspective(45, (display[0] / display[1]), 0.1, 50.0)


glTranslatef(0.0, 0.0, -5)

while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()

glRotatef(1, 3, 1, 1)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
draw3d()
pygame.display.flip()
pygame.time.wait(10)
For the above output we used the values below
Enter the number of sides: 4
Enter the depth value: 1

You might also like