BBBBBBB

Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

Simple Particle System 2023-24

CHAPTER 1

INTRODUCTION TO SIMPLE PARTICLE SYSTEM

1.1 Introduction

A simple particle system in computer graphics is a technique used to simulate fuzzy phenomena such
as fire, smoke, and explosions. In this mini project, we create a basic particle system to visualize particles
emitting from a source, moving according to physics-based rules. Each particle has properties like
position, velocity, lifespan, and color, which are updated over time to produce dynamic and realistic
effects. The project involves initializing particles, updating their states, and rendering them to create
visually appealing animations. This hands-on experience helps understand the fundamental concepts of
particle systems and their applications in graphics programming.

1.2 Overview of Computer Graphics

The term computer graphics has been used in a broad sense to describe “almost everything on
computers that is not text or sound. It is one of the most powerful and interesting facts of computer.There is
a lot that you can do apart from drawing figures of various shapes.

Today, computers and computer-generated images touch many aspects of daily life. Computer image is
found on television, in newspapers, for example in weather reports, in all kindsof medical investigation
and surgical procedures. A well-constructed graph can present complex statistics in a form that is easier
to understand and interpret. In the media such graphs are used to illustrate papers, reports, and other
presentation material.

Many powerful tools have been developed to visualize data. Computer generated imagery can be
categorized into several different types: 2D, 3D, 5D, and animated graphics. As technology has improved,
3D computer graphics have become more common, but 2D computer graphics are still widely used.
Computer graphics has emerged as a sub-field of computer sciencewhich studies methods for digitally
synthesizing and manipulating visual content. Over the past decade, other specialized fields have been
developed like information visualization, and scientific visualization more concerned with “the
visualization of three-dimensional phenomena” (architectural, meteorological, medical, biological, etc.),
where emphasis is on realistic renderings of volumes, surfaces, illumination sources, and so forth, perhaps
with a dynamic (time component).

Dept. of CSE, RIT Hassan Page 1


Simple Particle System 2023-24

1.3 History of Computer Graphics

Computer graphics has experienced significant advancements since its inception in the mid-20th
century.

Early Beginnings (1940s-1960s):

• The concept of computer graphics emerged with the development of the first electronic
computers in the 1940s.

• In 1963, Ivan Sutherland's Sketchpad introduced interactive graphics, allowing users to


draw and manipulate objects on a screen using a light pen.

Rise of 2D Graphics (1970s):

• The 1970s saw the development of raster graphics systems, enabling the representation
of images as grids of pixels.

• The release of the video game "Pong" by Atari in 1972 demonstrated the potential of
interactive computer graphics in entertainment.

Advent of 3D Graphics (1980s):

• The 1980s marked the introduction of dedicated graphics hardware and algorithms for
rendering 3D objects, improving the realism of images.

• The 1982 movie "Tron" showcased the use of computer-generated imagery (CGI) in
film.

Graphics Software and Standards (1990s):

• The 1990s saw the development of powerful graphics software like Adobe Photoshop
and 3D Studio Max.

• The OpenGL standard, established in 1992, facilitated cross-platform development of


3D graphics applications.

Modern Era and Real-Time Graphics (2000s-Present):

• The rise of powerful graphics processing units (GPUs) in the 2000s enabled real-time
rendering of complex 3D graphics, impacting video games, virtual reality (VR), and
augmented reality (AR).

• Recent advancements in real-time ray tracing and the integration of artificial


intelligence (AI) have brought unprecedented levels of realism to interactive graphics.

Dept. of CSE, RIT Hassan Page 2


Simple Particle System 2023-24

Throughout its history, computer graphics has continually pushed the boundaries of visual content
creation, transforming industries such as entertainment, design, and science. The field continues to evolve,
driven by innovations in hardware, software, and algorithms.

1.4 Applications of Computer Graphics

Nowadays Computer Graphics used in almost all the areas ranges from science, engineering, medicine,
business, industry government, art, entertainment, education, and training.

1.4.1 CG in the field of CAD

Computer Aided design methods are routinely used in the design of buildings, automobiles,
aircraft, watercraft, spacecraft computers, textiles, and many other applications.

1.4.2 CG in Presentation Graphics

Another major application area presentation graphics used to produce illustrations for reports
or generate slides. Presentation graphics is commonly used to summarize financial, statistical,
mathematical, scientific data for research reports and other types of reports.2D and 3D bar chart
to illustrate some mathematical or statistical report.

1.4.3 CG in computer Art


CG methods are widely used in both fine art and commercial art applications. Artists use a
variety of computer methods including special purpose hardware, artist’s paintbrush program,
other pain packages, desktop packages, mathematics packages, animation packages that
provide facility for designing object motion. Ex: cartoons decision is an example of computer
art which uses CG.

1.4.4 Image Processing


Concerned with fundamentally different operations. In CG a computer is used to create a
picture. Image processing on the other hand applies techniques to modify existing pictures such
as photo scans, TV scans. Artists use a variety of computer methods including special purpose
hardware, artist’s paintbrush program, other pain packages, desktop packages, mathematics
packages, animation packages that provide facility for designing object motion. Ex: cartoons
decision is an example of computer art which uses CG.

Dept. of CSE, RIT Hassan Page 3


Simple Particle System 2023-24

1.4.5 User Interface


It is a common for software packages to provide a graphical interface. A major component of
a graphical interface is a window manager that allows a user to display multiple window area.
Interface also displays menus, icons for fast selection and processing.

1.4.6 Education and Training


Computer generated models of physical, financial, economic system often act as education
aids. For some training application special system are designed. Ex: specialized system for
simulator for practice sessions or training of ship captain, aircraft pilots and traffic control.

1.5 Statement of the Project


This project involves developing a basic particle system to simulate phenomena such as fire, smoke,
and explosions. The system initializes particles with properties like position, velocity, lifespan, and color.
Physics-based rules are implemented to update these particle states over time. The particles are then
rendered dynamically, creating realistic and visually appealing animations. Through this project, we
explore the fundamental concepts of particle systems in computer graphics. Additionally, it provides
hands-on experience in graphics programming and particle system implementation.

1.6 Objectives
A. Understand Particle Systems: Gain a comprehensive understanding of particle systems and their
applications in computer graphics.

B. Initialize Particles: Develop the ability to initialize particles with properties such as position,
velocity, lifespan, and color.

C. Implement Physics-Based Rules: Learn to apply physics-based rules to update particle states over
time for realistic behavior.

D. Rendering Techniques: Explore techniques for rendering particles dynamically to create visually
appealing animations.

E. Simulation of Natural Phenomena: Simulate natural phenomena like fire, smoke, and explosions
using particle systems.

F. Programming Skills: Enhance programming skills in graphics programming by implementing and


managing particle systems.

Dept. of CSE, RIT Hassan Page 4


Simple Particle System 2023-24

CHAPTER 2

INTRODUCTION TO OPENCV

OpenCV's functions in Python are the fundamental building blocks of the library, providing low-level
operations for manipulating and processing images and matrices. These functions form the backbone of
OpenCV and are used by many of the higher-level functions and algorithms in the library. OpenCV
provides functions for reading and writing images and videos in various formats. OpenCV also provides
a set of basic image processing functions, such as image arithmetic, pixel manipulation, and colour space
conversion.

2.1 OpenCV Fundamentals


"OpenCV Fundamentals" briefly explains basic OpenCV concepts, such as what a graphic primitive
is and how OpenCV implements an Object Detection and Video Processing.

2.1.1 Primitive and Commands


OpenCV draws primitives—points, line segments, or polygons—subject to several
selectable modes. You can control modes independently of each other; that is, setting one mode
does not affect whether other modes are set (although many modes may interact to determine
what eventually ends up in the frame buffer). Primitives are specified, modes are set, and other
OpenCV operations are described by issuing commands in the form of function calls.

Primitives are defined by a group of one or more vertices. A vertex defines a point, an endpoint
of a line, or a corner of a polygon where two edges meet. Data (consisting of vertex coordinates,
colours, normal, texture coordinates, and edge flags) is associated with a vertex, and each
vertex and its associated data are processed independently, in order, and in the same way. The
only exception to this rule is if the group of vertices must be clipped so that a particular
primitive fits within a specified region; in this case, vertex data may be modified and new
vertices created. The type of clipping depends on which primitive the group of vertices
represents. You can control modes independently of each other; that is, setting one mode does
not affect whether other modes are set.

Dept. of CSE, RIT Hassan Page 5


Simple Particle System 2023-24

Commands are always processed in the order in which they are received, although there may
be an indeterminate delay before a command takes effect.

2.1.2 Procedural versus Descriptive


OpenCV provides you with direct control over the fundamental operations of two- and
three-dimensional graphics. This includes specification of such parameters as transformation
matrices, lighting equation coefficients, antialiasing methods, and pixel update operators.
However, it does not provide you with a means for describing or modelling complex geometric
objects. Thus, the OpenCV commands you issue specify how a certain result should be
produced rather than what exactly that result should look like. That is, OpenCV is
fundamentally procedural rather than descriptive. Because of this procedural nature, it helps to
know how OpenCV works—the order in which it carries out its operations, for example—to
fully understand how to use it.

2.1.3 Execution Model


An application issues commands, which are interpreted and processed by OpenCV. The
server may or may not operate on the same computer as the client. In this sense, OpenCV is
network-transparent. A server can maintain several CV contexts, each of which is an
encapsulated CV state. A client can connect to any one of these contexts. The required network
protocol can be implemented by augmenting an already existing protocol or by using an
independent protocol. No OpenCV commands are provided for obtaining user input.

The effects of OpenCV commands on the frame buffer are ultimately controlled by the window
system that allocates frame buffer resources. The window system determines which portions
of the frame buffer OpenCV may access at any given time and communicates to OpenCV how
those portions are structured. Therefore, there are no OpenCV commands to configure the
frame buffer or initialize OpenCV.

2.1.4 Basic OpenCV Operation


In the diagram, commands enter from the left and proceed through what can be thought
of as a processing pipeline. Some commands specify geometric objects to be drawn, and others
control how the objects are handled during the various processing stages and in various
methods.

Dept. of CSE, RIT Hassan Page 6


Simple Particle System 2023-24

Fig 2.1: OpenCV Block Diagram

As shown by the first block in the diagram, rather than having all commands proceed
immediately through the pipeline, you can choose to accumulate some of them in a display list
for processing later.

The evaluator stage of processing provides an efficient means for approximating curve and
surface geometry by evaluating polynomial commands of input values. During the next stage,
per-vertex operations, and primitive assembly, OpenCV processes geometric primitives—
points, line segments, and polygons, all of which are described by vertices. Vertices are
transformed and lit, and primitives are clipped to the viewport in preparation for the next stage.

Rasterization produces a series of frame buffer addresses and associated values using a two-
dimensional description of a point, line segment, or polygon. Each fragment so produced is fed
into the last stage, per-fragment operations, which performs the final operations on the data
before it is stored as pixels in the frame buffer. These operations include conditional updates to
the frame buffer based on incoming and previously stored z-values (for z-buffering) and
blending of incoming pixel colours with stored colours, as well as masking and other logical
operations on pixel values.

Input data can be in the form of pixels rather than vertices. Such data, which might describe an
image for use in texture mapping, skips the first stage of processing described above and instead
is processed as pixels, in the pixel operations stage. The result of this stage is either stored as
texture memory, for use in the rasterization stage, or rasterized and the resulting fragments
merged into the frame buffer just as if they were generated from geometric data.

All elements of OpenCV state, including the contents of the texture memory and even of the
frame buffer, can be obtained by an OpenCV application.

Dept. of CSE, RIT Hassan Page 7


Simple Particle System 2023-24

2.2 OpenCV API


OpenCV (Open-Source Computer Vision Library) is a versatile open-source library for computer
vision and machine learning applications. Key components of its API include:

1. Core Functionality: Handles image representation (cv: Mat), geometric entities (cv::Point,
cv::Rect, cv::Size), and basic operations.

2. Image Processing: Provides functions for image I/O, color conversion, filtering, and convolution.

3. Feature Detection: Supports methods for detecting keypoints (cv::cornerHarris,


cv::goodFeaturesToTrack) and computing descriptors (cv::ORB, cv::SIFT, cv::SURF).

4. Object Detection and Tracking: Includes tools for cascade classifiers (cv::CascadeClassifier) and
deep learning models (DNN module) for object detection.

5. Video Analysis: Offers functionality for video I/O, background subtraction, and frame processing.

6. High-Level GUI and Utilities: Provides drawing functions (cv::line, cv::rectangle, etc.) for
annotations, GUI utilities (cv::imshow, cv::waitKey), and optimization tools.

OpenCV supports multiple programming languages, including C++, Python, Java, and MATLAB, making
it widely accessible for cross-platform development and integration into various applications.

Dept. of CSE, RIT Hassan Page 8


Simple Particle System 2023-24

CHAPTER 3

SYSTEM DESIGN

3.1 DESIGN OVERVIEW


In the design phase the software requirements are transformed into definitions of software components
and their interfaces, to establish the framework of the software. The system design is about the system’s
behavioral design affecting the design of system components. The essence of software design is making
decisions about the logical organization of the software. Sometimes we represent this logical organization
as a model in a defined modeling language. Sometimes we simply use informal notations and sketches to
represent thedesign. The purpose of this phase is to develop the concept and basic framework for the
design of the project. This is the most existing and creative part of the project. This phase starts with the
requirement document delivered by the requirement phase and maps the requirements into architecture.
The design which represents the working of the nuclear power plant is shown. The complete overview of
the project is shown in the block diagram; it shows how it will perform the actions through user
interaction.

3.2 ARCHITECTURE

Fig 3.1: Architecture Block Diagram

Dept. of CSE, RIT Hassan Page 9


Simple Particle System 2023-24

3.3 FLOWCHART

Fig 3.2: Flowchart of Process

This flowchart represents the control flow and functionality of a particle system program. It begins
with the Start block, followed by the Main(), Init(), and Display() functions. User interactions are handled
through various keyboard functions. Pressing 'f' toggles fog on or off, while 't' changes the spray type to
either waterfall or fountain. The 's' key adds collision spheres, with a maximum of three spheres. The '-'
key decreases the particle flow. Pressing 'p' reduces the size of the particles, whereas 'P' increases their
size. The 'l' key toggles between points and lines rendering modes. The '#' key toggles the frame rate
display on or off, and the '~' key toggles full screen mode. This flowchart ensures an interactive and
versatile particle system simulation.

Dept. of CSE, RIT Hassan Page 10


Simple Particle System 2023-24
3.4 ADVANTAGES

A. Visual Effects Creation: Provides experience in creating dynamic visual effects like fire, smoke,
and water, which are widely used in media and entertainment.
B. Interactive Learning: Enhances understanding of computer graphics concepts through hands-on
interaction with particle systems.
C. User-Controlled Features: Allows users to manipulate various parameters, fostering
experimentation and deeper comprehension of particle behavior.
D. Programming Skills: Strengthens coding skills in graphics programming, particularly in
managing and optimizing particle systems.
E. Versatility in Applications: Offers insights into applications of particle systems in different
fields, including virtual reality, special effects, and scientific visualization.
F. Problem-Solving and Creativity: Encourages creative problem-solving by addressing
challenges in designing and implementing particle interactions and behaviors.
G. Performance Optimization: Teaches optimization techniques to manage and render a large
number of particles efficiently, enhancing performance skills.

3.1 DISADVANTAGES
A. Performance Constraints: High computational requirements can slow down the system,
especially with a large number of particles, affecting real-time performance.
B. Complexity in Implementation: Developing and managing a particle system can be complex
and time-consuming, requiring a strong grasp of graphics programming and physics.
C. Limited Realism: Simple particle systems might not achieve the high level of realism needed for
advanced applications without significant enhancements.
D. Resource Intensive: Intensive use of memory and processing power can limit the application on
lower-end hardware.
E. Debugging Challenges: Troubleshooting and debugging particle systems can be difficult due to
the dynamic and concurrent nature of particle updates and rendering.
F. Scalability Issues: As the number of particles increases, maintaining performance and visual
quality can become problematic.
G. Specialized Knowledge Required: Requires specialized knowledge in computer graphics,
physics, and optimization techniques, which might be a barrier for beginners.

Dept. of CSE, RIT Hassan Page 11


1411
Simple Particle System 2023-24

CHAPTER 4

REQUIREMENTS SPECIFICATION

To perform this project in graphics using OpenGL, certain hardware and software requirements are
required by the system. These hardware and software requirements are listed as below:

4.1 SOFTWARE REQUIREMENTS

A. Operating System: Windows XP, Windows 10


B. Language : Visual C++ with OpenGL API
C. Compiler : GNU GCC Compiler/C++ Compiler
D. Library Files : glut32.h, OpenGL32.h & glu32.h
E. Software : Codeblock 17.2 or Visual studio 2015

4.2 HARDWARE REQUIREMENTS


A. Processor: Pentium 4

B. RAM : 1 GB DDR with 512 MHz

C. Hard Disk Drive : 40 GB

D. Moniter : 16 bit Color Moniter

Dept. of CSE, RIT Hassan Page 13


1412
Simple Particle System 2023-24

CHAPTER 5

PROJECT DESCRIPTION

The simple particle system involves developing an interactive particle system to simulate natural
phenomena like fire, smoke, and water. The system initializes particles with properties such as position,
velocity, lifespan, and color, and updates these properties in real-time based on physics-based rules. Users
can interact with the system through various keyboard controls, allowing them to toggle fog effects,
change spray types, add collision spheres, adjust particle size and flow, and switch between different
rendering modes. The project aims to provide hands-on experience in graphics programming, enhance
understanding of particle dynamics, and explore optimization techniques for real-time simulation. Despite
its complexity and resource-intensive nature, this project offers valuable insights into creating dynamic
visual effects and managing performance in computer graphics applications.

5.1 GRAPHICS FUNCTIONS AND REQUIREMENT

Header Files:
The in-built functions are defined in the OpenGL library. Some of the headers that are
used are as follows:

• #include<stdio.h> :to take input from standard input and write to standard output

• #include<stdlib.h> :to include standard library functions

• #include<GL/glut.h> : to include glut library files

Inbuilt Functions

• glClearColor (GLclampf r, GLclampf g, GLclampf b, GLclamp a)

• Specifies clear values to the color buffers and clears the display before redrawing it.

• glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)

• Clears buffer to preset values.

• Void glutDisplayFunc(void(*func)(void))

Dept. of CSE, RIT Hassan Page 13


1413
Simple Particle System 2023-24

• glFlush()

• Forces any buffered OpenGL commands to execute. Sets keyboard call back to current
window.

• glBegin (glEnum mode)

• Initiates a new primitive of type mode and starts collection of vertices. Values of mode
include GL_POINTS, GL_LINES and GL_POLYGON.

• void glEnd()

• Terminates a list of vertices.

• void glutInit ( )

• All Initializes the GLUT. The arguments from main are passed in and can beused by the application.

• void glutCreateWindow( )

• Creates a window on the display. The string title can be used to label the window.

• void glutInitDisplayMode()

• Requests a display with the properties in mode. color model.

• Void glutInitWindowSize( )

• Specifies the initial height and width of the window in pixels.

• void glutInitwindowPosition(int x, int y)

• Specifies the initial position of the top-left corner of the window in pixels.

• void glutMainLoop()

• Causes the program to enter an event-processing loop. It should be the laststatement main.

• void glMatrixMode( GLenum mode)

• Specify matrix will be affected by subsequent transformation mode GL_PROJECTION.

• void glutBitmapCharacter(void *font, int character)

• void glutKeyboardFunc()

Dept. of CSE, RIT Hassan Page 13


1414
Simple Particle System 2023-24
User defined functions

• timedelta(void);

• This function returns the number of seconds that have elapsed since the previous call to the
function.

• void text( );

• This function draws a string of text with an 18 point Helvetica bitmap space.

• int fequal( );

• Customized equals ("==") operation for floating point value.

• void psTimestep( );

• Updates velocity and position of particles by a small value delta.

• void psNewparticle( );

• Initializes the velocity, position,dampening and related information

• void psBounce( );

• psBounce: the particle has gone past (or exactly hit) the groundplane .

• void psBounce( );

• psBounce the particle has gone past (or exactly hit) the ground
plane, so calculate the time at which the particle actually

5.2 IMPLEMENTATION
#include <windows.h>
#include <GL/glut.h>
#include "bits/stdc++.h"
#include "testlib.h" //Download this header file from
https://raw.githubusercontent.com/MikeMirzayanov/testlib/master/testlib.h
using namespace std;

string Title = "Clash of Cars";

bool collide;
bool game_over;
long long score;

const double EPS = 1e-6;

Dept. of CSE, RIT Hassan Page 13


1415
Simple Particle System 2023-24
const double Ortho_left = -24;
const double Ortho_right = 24;
const double Ortho_top = 32;
const double Ortho_bottom = 0;

const double Road_left = -12;


const double Road_right = 13;
const double Road_top = 32;
const double Road_bottom = 0;

class Point {
public:
double x, y, z;
Point() { x = y = z = 0; }
Point(double _x, double _y) { x = _x, y = _y, z = 0; }
Point(double _x, double _y, double _z) { x = _x, y = _y, z = _z; }
};

class Color {
public:
double r, g, b;
Color() { update(); }
Color(double _r, double _g, double _b) { r = _r, g = _g, b = _b; }
void update() { r = rnd.next(1.0), g = rnd.next(1.0), b = rnd.next(1.0); }
};

vector<int> Lanes({ -11, -7, -3, 1, 5, 9 });


class Car {
public:
Color color, tolor;
double height = 5.5, width = 3, speed, x, y; bool forward;
Car() { renovate(); }
Car(int _x, int _y, double s) {
x = _x, y = _y; speed = s;
color = { 1,0,0 }; tolor = { 0,0,0 }; forward = 1;
}

void go_left() { x = max(x - 4, Road_left + 1); }


void go_right() { x = min(x + 4, Road_right - width - 1); }
void go_down() {
if (y < 0 - height) renovate(), score++;
else y -= speed;
}
void go_down(int f) { { y = max(y - 1, Road_bottom); } }
void go_up() { y = min(y + 1, Road_top - width); }

void renovate() {
x = rnd.any(Lanes), y = Road_top;
speed = rnd.next(0.1, .2);

color.update(), tolor.update();}

Dept. of CSE, RIT Hassan Page 13


1416
Simple Particle System 2023-24
void update() {
glPushMatrix();
glColor3f(tolor.r, tolor.g, tolor.b);
if (!forward) {
glRectd(x + 0, y + 2, x + 3, y + 5);

glColor3f(color.r, color.g, color.b);


glRectd(.75 + x, 2.75 + y, 2.25 + x, 4.25 + y);

glBegin(GL_LINES);
glVertex2d(x + 0, y + 2);
glVertex2d(x + 1, y + 3);
glVertex2d(x + 0, y + 5);
glVertex2d(x + 1, y + 4);
glVertex2d(x + 2, y + 4);
glVertex2d(x + 3, y + 5);
glVertex2d(x + 2, y + 3);
glVertex2d(x + 3, y + 2);
glEnd();

glBegin(GL_QUADS);
glVertex2d(x + 0.25, y + 5.5);
glVertex2d(x + 2.75, y + 5.5);
glVertex2d(x + 3, y + 5);
glVertex2d(x + 0, y + 5);
glVertex2d(x + 0, y + 2);
glVertex2d(x + 3, y + 2);
glVertex2d(x + 2.6, y);
glVertex2d(x + 0.4, y);
glEnd();

glPointSize(10);
glBegin(GL_POINTS);
glVertex2d(2.75 + x, y + 1);
glVertex2d(0.25 + x, y + 1);
glEnd();
glPopMatrix();
return;
}
glRectd(x + 0, y + .5, x + 3, y + 3.5);

glColor3f(color.r, color.g, color.b);


glRectd(.75 + x, 1.25 + y, 2.25 + x, 2.75 + y);

glBegin(GL_LINES);
glVertex2d(x + 0, y + .5);
glVertex2d(x + 1, y + 1.5);
glVertex2d(x + 0, y + 3.5);
glVertex2d(x + 1, y + 2.5);
glVertex2d(x + 2, y + 2.5);
glVertex2d(x + 3, y + 3.5);
glVertex2d(x + 2, y + 1.5);

Dept. of CSE, RIT Hassan Page 13


1417
Simple Particle System 2023-24
glVertex2d(x + 3, y + .5);
glEnd();

glBegin(GL_QUADS);
glVertex2d(x + 0.25, y);
glVertex2d(x + 2.75, y);
glVertex2d(x + 3, y + 0.5);
glVertex2d(x + 0, y + 0.5);
glVertex2d(x + 0, y + 3.5);
glVertex2d(x + 3, y + 3.5);
glVertex2d(x + 2.6, y + 5.5);
glVertex2d(x + 0.4, y + 5.5);
glEnd();

glPointSize(10);
glBegin(GL_POINTS);
glVertex2d(2.75 + x, y + 4.5);
glVertex2d(0.25 + x, y + 4.5);
glEnd();
glPopMatrix();
}
}PlayerCar(1, 0, 0.1);

vector<Car>Cars(5);

void drawstring(double x, double y, double z, string s) {


glRasterPos3f(x, y, z);
for (auto c : s)glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, c);
}

class Road {
public:
vector<double> Dash;
Road() { for (int i = 0; i <= Road_top + 4; i += 4) Dash.push_back(i); }
void update() {
glColor3d(.25, .25, .25);
glRectd(Road_left, Road_bottom, Road_right, Road_top);

glColor3d(1, 1, 0.25);
glRectd(Road_left + 0.5, Road_bottom, Road_left + 1, Road_top);
glRectd(Road_left + 8, Road_bottom, Road_left + 8.5, Road_top);
glRectd(Road_left + 16, Road_bottom, Road_left + 16.5, Road_top);
glRectd(Road_left + 24, Road_bottom, Road_left + 24.5, Road_top);

glColor3d(1, 1, 1);
for (auto& d : Dash) {
d -= PlayerCar.speed; if (d < 0)d = Road_top + 4;
glRectd(Road_left + 4, d, Road_left + 4.5, d - 2);
glRectd(Road_left + 12, d, Road_left + 12.5, d - 2);
glRectd(Road_left + 20, d, Road_left + 20.5, d - 2);
}
}

Dept. of CSE, RIT Hassan Page 13


1418
Simple Particle System 2023-24

}Roads;

class Tree {
public:
double x, y;
Tree() { renovate(); }
void renovate() {
x = (rnd.next(2) ? rnd.next(Ortho_left, Road_left) : rnd.next(Road_right, Ortho_right));
y = rnd.next(Ortho_top, Ortho_top * 2);
}
void update() {
y -= PlayerCar.speed;
if (y <= -6)renovate();

glColor3d(0.44, 0.33, 0.23);


glRectd(-0.5 + x, 0 + y, 0.5 + x, 4 + y);

glColor3d(.13, 1, .13);
glBegin(GL_TRIANGLES);
glVertex2d(0 + x, 5 + y);
glVertex2d(-1 + x, 4 + y);
glVertex2d(1 + x, 4 + y);
glVertex2d(0 + x, 4.4 + y);
glVertex2d(-2 + x, 3 + y);
glVertex2d(2 + x, 3 + y);
glVertex2d(0 + x, 3.8 + y);
glVertex2d(-2.5 + x, 2 + y);
glVertex2d(2.5 + x, 2 + y);
glEnd();
}
}; vector<Tree>Trees(30);

void display() {
glClear(GL_COLOR_BUFFER_BIT);
Roads.update();
PlayerCar.update();
for (auto& car : Cars) { if (!collide)car.go_down(); car.update(); }
sort(Trees.begin(), Trees.end(), [](auto& a, auto& b) {return a.y > b.y;});
for (auto& tree : Trees)tree.update();
if (game_over) {
glColor3d(.7, .7, .7); glRectd(-7.3, 17, 7.5, 22);
glColor3d(0, 0, 1), drawstring(-4, 21, 0, "Game Over");
glColor3d(0, 0, 1), drawstring(-3, 19.5, 0, "Score: " + toString(score));
glColor3d(1, 0, 0), drawstring(-7, 18, 0, "Press R to Restart");
}
else {
glColor3d(.7, .7, .7); glRectd(Ortho_left, Ortho_top - 1, Ortho_left + 10, Ortho_top - 3);
glColor3d(0, 0, 1), drawstring(Ortho_left + 2, Ortho_top - 2, 0, "Score: " + toString(score));
}

Dept. of CSE, RIT Hassan Page 13


1419
Simple Particle System 2023-24
boolean rectRect(double r1x, double r1y, double r2x, double r2y) {
double r1w = 3, r1h = 5.5, r2w = 3, r2h = 5.5;
if (r1x + r1w >= r2x + EPS && r1x + EPS <= r2x + r2w && r1y + r1h >= r2y + EPS && r1y + EPS <=
r2y + r2h)return true;
return false;
}

bool collision() {
for (auto c : Cars)if (rectRect(c.x, c.y, PlayerCar.x, PlayerCar.y))return true;
return false;
}

void timer(int v) {
if (collision()) {
game_over = 1;
collide = 1;
glutPostRedisplay();
glutSpecialFunc(NULL);
return;
}
glutPostRedisplay();
glutTimerFunc(10, timer, v);
}

void specialKeys(int key, int x, int y) {


switch (key) {
case GLUT_KEY_LEFT:
PlayerCar.go_left();
break;
case GLUT_KEY_RIGHT:
PlayerCar.go_right();
break;
case GLUT_KEY_UP:
PlayerCar.go_up();
break;
case GLUT_KEY_DOWN:
PlayerCar.go_down(1);
break;
default:
break;
}
glutPostRedisplay();
}

void Keys(unsigned char key, int x, int y) {


if ('r' == key or 'R' == key) {
for (auto& car : Cars)car.renovate();
score = game_over = collide = 0;
glutSpecialFunc(specialKeys);
glutPostRedisplay();
glutTimerFunc(10, timer, 0);
}

Dept. of CSE, RIT Hassan Page 13


14110
Simple Particle System 2023-24
else if (key == 'e' or key == 'E')exit(0);
}

void reshape(GLsizei width, GLsizei height) {


glClearColor(0.22, .58, .20, 0);

// Reshape Window
glViewport(0, 0, width, height);
glLoadIdentity();

GLdouble aspect = (GLdouble)width / (GLdouble)max(height, 1);


if (width >= height) glOrtho(Ortho_left * aspect, Ortho_right * aspect, Ortho_bottom, Ortho_top, 0,
Ortho_right);
else glOrtho(Ortho_left, Ortho_right, Ortho_bottom / aspect, Ortho_top / aspect, 0, Ortho_right);
}

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


glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE);
glutInitWindowSize(650, 650);
glutInitWindowPosition(400, 20);
glutCreateWindow(Title.c_str());
glutDisplayFunc(display);
glutSpecialFunc(specialKeys);
glutKeyboardFunc(Keys);
glutReshapeFunc(reshape);
glutTimerFunc(10, timer, 0);
glutMainLoop();

return 0;
}

Dept. of CSE, RIT Hassan Page 13


14111
Simple Particle System 2023-24

Dept. of CSE, RIT Hassan Page 13


14112
Simple Particle System 2023-24

Dept. of CSE, RIT Hassan Page 13


14113
Simple Particle System 2023-24 .

Dept. of CSE, RIT Hassan Page 13


14114
Simple Particle System 2023-24

Dept. of CSE, RIT Hassan Page 13


14115
Simple Particle System 2023-24

Dept. of CSE, RIT Hassan Page 13


14116
Recognition of Objects Through Image Processing 2023-24

CHAPTER 7

Dept. of CSE, RIT Hassan Page 20

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy