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

CG Lab Assignement

The document outlines several lab assignments for a Computer Science and Engineering course, focusing on graphics programming. Each assignment includes a problem statement, aim, objectives, and code implementations for tasks such as ray tracing, maze generation, celestial mechanics simulation, and cloth simulation. The assignments aim to enhance understanding of computer graphics concepts and physics-based simulations.

Uploaded by

Piyush Rawat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

CG Lab Assignement

The document outlines several lab assignments for a Computer Science and Engineering course, focusing on graphics programming. Each assignment includes a problem statement, aim, objectives, and code implementations for tasks such as ray tracing, maze generation, celestial mechanics simulation, and cloth simulation. The assignments aim to enhance understanding of computer graphics concepts and physics-based simulations.

Uploaded by

Piyush Rawat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

DEPARTMENT OF COMPUTER

SCIENCE & ENGINEERING

Fast Learner Lab Assignment

Student Name: Abhishek Mishra UID: 22BCS10735


Branch: BE - CSE Section/Group: 605-‘A’
Semester: 6th Date of Performance:10/04/25
Subject Name: CG with Lab Subject Code: 22CSH-352

PROBLEM-1
1. Problem Statement: Implement a ray-tracing renderer to simulate realistic
lighting effects, including shadows and reflections.
2. Aim: To simulate realistic light behavior in computer graphics.
3. Objective: Understand ray tracing concepts, including intersections, light
reflection, and refraction for photorealistic rendering.
4. Code:
#include <graphics.h>
#include <cmath>
#include <iostream>
#include <conio.h>
using namespace std;

const int WIDTH = 640;


const int HEIGHT = 480;

struct Vec3 {
float x, y, z;
Vec3(float x_=0, float y_=0, float z_=0) : x(x_), y(y_), z(z_) {}

Vec3 operator + (const Vec3& v) const { return Vec3(x + v.x, y + v.y, z + v.z); }
Vec3 operator - (const Vec3& v) const { return Vec3(x - v.x, y - v.y, z - v.z); }
Vec3 operator * (float s) const { return Vec3(x * s, y * s, z * s); }
Vec3 operator / (float s) const { return Vec3(x / s, y / s, z / s); }

float dot(const Vec3& v) const { return x*v.x + y*v.y + z*v.z; }


Vec3 normalize() const {
float mag = sqrt(x*x + y*y + z*z);
return Vec3(x/mag, y/mag, z/mag);
}
DEPARTMENT OF COMPUTER
SCIENCE & ENGINEERING

};
struct Sphere {
Vec3 center;
float radius;
int color;
Sphere(Vec3 c, float r, int col) : center(c), radius(r), color(col) {}
bool intersect(const Vec3& rayOrig, const Vec3& rayDir, float &t) {
Vec3 oc = rayOrig - center;
float a = rayDir.dot(rayDir);
float b = 2.0 * oc.dot(rayDir);
float c = oc.dot(oc) - radius * radius;
float discriminant = b*b - 4*a*c;
if (discriminant < 0) return false;
else {
t = (-b - sqrt(discriminant)) / (2*a);
return t > 0;
}}
};
int applyLighting(int color, float intensity) {
int r = min(255, int((color >> 16 & 255) * intensity));
int g = min(255, int((color >> 8 & 255) * intensity));
int b = min(255, int((color & 255) * intensity));
return COLOR(r, g, b);
}
void drawRayTracedScene() {
Vec3 camPos(0, 0, 0);
float viewportSize = 1.0;
float projectionPlaneZ = 1.0;

Sphere sphere(Vec3(0, 0, 5), 1.2, RGB(255, 0, 0));


Vec3 lightPos(2, 2, 0);
for (int x = -WIDTH/2; x < WIDTH/2; x++) {
for (int y = -HEIGHT/2; y < HEIGHT/2; y++) {
float px = x * viewportSize / WIDTH;
float py = y * viewportSize / HEIGHT;
Vec3 dir(px, py, projectionPlaneZ);
dir = dir.normalize();
float t;
if (sphere.intersect(camPos, dir, t)) {
Vec3 hitPoint = camPos + dir * t;
DEPARTMENT OF COMPUTER
SCIENCE & ENGINEERING

Vec3 normal = (hitPoint - sphere.center).normalize();


Vec3 lightDir = (lightPos - hitPoint).normalize();

float diff = max(0.0f, normal.dot(lightDir));


int shadedColor = applyLighting(sphere.color, diff);

putpixel(x + WIDTH/2, HEIGHT/2 - y, shadedColor);


} else {
putpixel(x + WIDTH/2, HEIGHT/2 - y, COLOR(30, 30, 30)); // Background
}
}
}}
int main() {
initwindow(WIDTH, HEIGHT, "Ray Tracing Simulation");
drawRayTracedScene();
getch();
closegraph();
return 0;
}
5. Output:
DEPARTMENT OF COMPUTER
SCIENCE & ENGINEERING

PROBLEM-2
1.Problem Statement: Create a 3D maze generator and solver, visualized using
perspective transformations and real-time rendering.

2.Aim: To generate and navigate complex 3D environments.


3.Objective: Implement maze generation algorithms and explore pathfinding
techniques in 3D space.
4.Code:
#include <graphics.h>
#include <cstdlib>
#include <ctime>
#include <stack>
#include <vector>

const int cols = 20;


const int rows = 20;
const int cellSize = 20;

struct Cell {
int x, y;
bool visited;
bool walls[4]; // top, right, bottom, left
Cell(int x_=0, int y_=0) {
x = x_;
y = y_;
visited = false;
for (int i = 0; i < 4; i++) walls[i] = true;
}
int index(int x, int y) {
if (x < 0 || y < 0 || x >= cols || y >= rows) return -1;
return x + y * cols;
}
void draw(int offsetX, int offsetY, bool fillCell = false) {
int x1 = x * cellSize + offsetX;
int y1 = y * cellSize + offsetY;
int x2 = x1 + cellSize;
DEPARTMENT OF COMPUTER
SCIENCE & ENGINEERING

int y2 = y1 + cellSize;

setcolor(WHITE);
if (walls[0]) line(x1, y1, x2, y1); // top
if (walls[1]) line(x2, y1, x2, y2); // right
if (walls[2]) line(x2, y2, x1, y2); // bottom
if (walls[3]) line(x1, y2, x1, y1); // left
if (fillCell) {
setfillstyle(SOLID_FILL, LIGHTBLUE);
bar(x1+1, y1+1, x2-1, y2-1);
}}
};
std::vector<Cell> grid;
std::stack<Cell*> stack;
Cell* current;
Cell* getNeighbor(Cell* cell) {
std::vector<Cell*> neighbors;
int x = cell->x;
int y = cell->y;

int indices[] = {
cell->index(x, y-1), // top
cell->index(x+1, y), // right
cell->index(x, y+1), // bottom
cell->index(x-1, y) // left
};
for (int i = 0; i < 4; i++) {
int idx = indices[i];
if (idx != -1 && !grid[idx].visited)
neighbors.push_back(&grid[idx]);
}
if (!neighbors.empty()) {
int r = rand() % neighbors.size();
return neighbors[r];
}
return NULL;
}
void removeWalls(Cell* a, Cell* b) {
int dx = a->x - b->x;
DEPARTMENT OF COMPUTER
SCIENCE & ENGINEERING

int dy = a->y - b->y;


if (dx == 1) {
a->walls[3] = false;
b->walls[1] = false;
} else if (dx == -1) {
a->walls[1] = false;
b->walls[3] = false;
}
if (dy == 1) {
a->walls[0] = false;
b->walls[2] = false;
} else if (dy == -1) {
a->walls[2] = false;
b->walls[0] = false;
}}
void generateMaze(int offsetX, int offsetY) {
for (int i = 0; i < grid.size(); i++) {
grid[i].draw(offsetX, offsetY);
}
current->visited = true;
current->draw(offsetX, offsetY, true);
Cell* next = getNeighbor(current);
if (next != NULL) {
next->visited = true;
stack.push(current);
removeWalls(current, next);
current = next;
} else if (!stack.empty()) {
current = stack.top();
stack.pop();
}
}
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
srand(time(0));
for (int y = 0; y < rows; y++)
for (int x = 0; x < cols; x++)
grid.push_back(Cell(x, y));
DEPARTMENT OF COMPUTER
SCIENCE & ENGINEERING

current = &grid[0];
int offsetX = 50;
int offsetY = 50;
// Generate maze
while (true) {
cleardevice();
generateMaze(offsetX, offsetY);
delay(20);
if (stack.empty()) break;
}
// Final Maze Display
for (int i = 0; i < grid.size(); i++)
grid[i].draw(offsetX, offsetY);
getch();
closegraph();
return 0;

5.Output
DEPARTMENT OF COMPUTER
SCIENCE & ENGINEERING

PROBLEM-3
1.Problem Statement: Create an interactive simulation of celestial mechanics for
planets orbiting a star system with gravity effects.
2.Aim: To visualize gravitational force interactions in a dynamic celestial system.
3.Objective: Apply physics formulas for gravitational forces and simulate realistic
orbital paths in 2D or 3D.
4.Code:
#include <graphics.h>
#include <cmath>
#include <vector>
#include <ctime>
#include <cstdlib>
#define G 0.1 // Gravitational constant (scaled for screen simulation)
#define NUM_PLANETS 3
#define TIME_STEP 1
struct Body {
double x, y; // Position
double vx, vy; // Velocity
double mass;
int radius;
int color;

void updatePosition() {
x += vx * TIME_STEP;
y += vy * TIME_STEP;
}
void draw() {
setcolor(color);
setfillstyle(SOLID_FILL, color);
fillellipse(x, y, radius, radius);
}
};
int main() {
int gd = DETECT, gm;
DEPARTMENT OF COMPUTER
SCIENCE & ENGINEERING

initgraph(&gd, &gm, "");


// Create central star
Body star = {getmaxx() / 2.0, getmaxy() / 2.0, 0, 0, 50000, 12, YELLOW};
// Create orbiting planets
std::vector<Body> planets;
planets.push_back({star.x + 100, star.y, 0, 2.5, 20, 5, RED});
planets.push_back({star.x + 180, star.y, 0, 1.8, 30, 6, GREEN});
planets.push_back({star.x + 250, star.y, 0, 1.4, 25, 6, CYAN});
while (!kbhit()) {
cleardevice();
// Draw the star
setfillstyle(SOLID_FILL, YELLOW);
star.draw();
// Update and draw each planet
for (int i = 0; i < planets.size(); i++) {
Body &p = planets[i];
// Calculate distance to star
double dx = star.x - p.x;
double dy = star.y - p.y;
double dist = sqrt(dx * dx + dy * dy);
if (dist == 0) continue;
// Gravitational force
double force = G * star.mass * p.mass / (dist * dist);
double acc = force / p.mass;
// Acceleration components
double ax = acc * (dx / dist);
double ay = acc * (dy / dist);
// Update velocity
p.vx += ax * TIME_STEP;
p.vy += ay * TIME_STEP;
// Update position
p.updatePosition();
// Draw planet
p.draw();
}
DEPARTMENT OF COMPUTER
SCIENCE & ENGINEERING

delay(20); // Delay for smooth animation


}
closegraph();
return 0;
}
5.Output:
DEPARTMENT OF COMPUTER
SCIENCE & ENGINEERING

PROBLEM-4
1.Problem Statement: Develop a cloth simulation that reacts to user inputs and
simulates realistic fabric behavior.
2.Aim: To simulate flexible materials using physics-based techniques.
3.Objective: Learn to model forces like tension, shear, and gravity to create
realistic cloth simulations.
4.Code:
#include <graphics.h>
#include <vector>
#include <math.h>
#include <conio.h>

const int cols = 20;


const int rows = 15;
const int spacing = 20;
const int iterations = 5;
const float gravity = 0.4;
const float damping = 0.99;

struct Point {
float x, y;
float oldx, oldy;
bool pinned;
Point(float _x, float _y, bool pin = false) {
x = _x;
y = _y;
oldx = _x;
oldy = _y;
pinned = pin;
}
void update() {
if (pinned) return;
float vx = (x - oldx) * damping;
float vy = (y - oldy) * damping;
oldx = x;
DEPARTMENT OF COMPUTER
SCIENCE & ENGINEERING

oldy = y;
x += vx;
y += vy + gravity;
}
void draw() {
circle(x, y, 2);
floodfill(x, y, WHITE);
}
void constrain(float minX, float maxX, float minY, float maxY) {
if (x < minX) x = minX;
if (x > maxX) x = maxX;
if (y < minY) y = minY;
if (y > maxY) y = maxY;
}};
struct Stick {
Point *p1, *p2;
float length;
Stick(Point *a, Point *b) {
p1 = a;
p2 = b;
float dx = p2->x - p1->x;
float dy = p2->y - p1->y;
length = sqrt(dx * dx + dy * dy);
}
void update() {
float dx = p2->x - p1->x;
float dy = p2->y - p1->y;
float dist = sqrt(dx * dx + dy * dy);
float diff = length - dist;
float percent = diff / dist / 2;
float offsetX = dx * percent;
float offsetY = dy * percent;
if (!p1->pinned) {
p1->x -= offsetX;
p1->y -= offsetY;
}
if (!p2->pinned) {
p2->x += offsetX;
DEPARTMENT OF COMPUTER
SCIENCE & ENGINEERING

p2->y += offsetY;
}}
void draw() {
line(p1->x, p1->y, p2->x, p2->y);
}
};
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
std::vector<Point> points;
std::vector<Stick> sticks;

int startX = 100, startY = 50;


// Create grid of points
for (int y = 0; y < rows; y++) {
for (int x = 0; x < cols; x++) {
bool pin = (y == 0) && (x == 0 || x == cols - 1); // pin corners
points.push_back(Point(startX + x * spacing, startY + y * spacing, pin));
}
}
// Connect horizontal and vertical sticks
for (int y = 0; y < rows; y++) {
for (int x = 0; x < cols; x++) {
int i = y * cols + x;
if (x < cols - 1)
sticks.push_back(Stick(&points[i], &points[i + 1]));
if (y < rows - 1)
sticks.push_back(Stick(&points[i], &points[i + cols]));
}
}
while (!kbhit()) {
cleardevice();
// Update positions
for (int i = 0; i < points.size(); i++)
points[i].update();

// Constraint solving
for (int it = 0; it < iterations; it++) {
DEPARTMENT OF COMPUTER
SCIENCE & ENGINEERING

for (int j = 0; j < sticks.size(); j++)


sticks[j].update();
for (int k = 0; k < points.size(); k++)
points[k].constrain(0, getmaxx(), 0, getmaxy());
}
// Draw sticks
setcolor(WHITE);
for (int i = 0; i < sticks.size(); i++)
sticks[i].draw();
// Draw points
setcolor(WHITE);
for (int i = 0; i < points.size(); i++)
points[i].draw();
delay(20);
}
closegraph();
return 0;

5.Output:
DEPARTMENT OF COMPUTER
SCIENCE & ENGINEERING

PROBLEM-5
1.Problem Statement: Build a 3D game engine with basic physics, lighting, and
camera movement.
2.Aim: To integrate multiple computer graphics concepts into a functional game
engine.
3.Objective: Combine graphics, physics, and interactivity to create a versatile game
development framework.
4.Code:
#include <graphics.h>
#include <conio.h>
#include <stdlib.h>
#include <math.h>

// Target structure
struct Target {
int x, y, radius;
int speed;
};
// Global variables
int shooterX = 300, shooterY = 400;
int bulletX = -1, bulletY = -1;
int bulletSpeed = 10;
bool bulletFired = false;
Target target = {50, 100, 20, 5};
// Function to draw the shooter
void drawShooter() {
setcolor(WHITE);
rectangle(shooterX - 20, shooterY, shooterX + 20, shooterY + 10);
rectangle(shooterX - 5, shooterY - 20, shooterX + 5, shooterY);
}
// Function to draw the bullet
void drawBullet() {
if (bulletFired) {
setcolor(RED);
circle(bulletX, bulletY, 3);
}}
// Function to draw the moving target
DEPARTMENT OF COMPUTER
SCIENCE & ENGINEERING

void drawTarget() {
setcolor(GREEN);
circle(target.x, target.y, target.radius);
}
// Function to move the target horizontally
void moveTarget() {
target.x += target.speed;
if (target.x >= getmaxx() - target.radius || target.x <= target.radius) {
target.speed = -target.speed;
}}
// Function to move the bullet
void moveBullet() {
if (bulletFired) {
bulletY -= bulletSpeed;
if (bulletY < 0) bulletFired = false;
}}
// Check if bullet hits the target
bool checkCollision() {
if (!bulletFired) return false;
int dx = bulletX - target.x;
int dy = bulletY - target.y;
int distance = sqrt(dx * dx + dy * dy);
return distance < target.radius;
}
// Game rendering loop
void gameLoop() {
cleardevice();
drawShooter();
drawTarget();
drawBullet();
moveTarget();
moveBullet();

if (checkCollision()) {
outtextxy(250, 200, "Target Hit!");
bulletFired = false;
target.x = rand() % (getmaxx() - 40) + 20;
}
delay(30);
}
DEPARTMENT OF COMPUTER
SCIENCE & ENGINEERING

int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");

outtextxy(10, 10, "Use Left/Right Arrow Keys to Move | SPACE to Shoot | ESC to Exit");

while (1) {
if (kbhit()) {
char ch = getch();
if (ch == 27) break; // ESC to exit
if (ch == 75 && shooterX > 30) shooterX -= 10; // Left Arrow
if (ch == 77 && shooterX < getmaxx() - 30) shooterX += 10; // Right Arrow
if (ch == ' ' && !bulletFired) {
bulletFired = true;
bulletX = shooterX;
bulletY = shooterY - 20;
} }
gameLoop();
}
closegraph();
return 0;
}

5.Output:

You might also like