Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

Graphics in C Programming Language

C GRAPHICAS NOTES
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Graphics in C Programming Language

C GRAPHICAS NOTES
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 9

Graphics In C Programming Language

In this tutorial you will learn how to do 2D graphics in C. We'll actually give the basis for
programming up something simple but worthwhile, e.g. a Space Invaders game (taking us back to the
Eighties) and it is a lot less complicated than it sounds. Remember, computers of the very early eighties
(before C was even used on home computers) all had games like Space Invaders, so if they could do it
so easily, then doing a bit of basic graphics should be a piece of cake for us with our modern computers.

We frequently get requests at FriedSpace.com for tutorials on doing graphics in C. It is a very


popular subject, and it fits in with the philosophy of our site quite well, namely that people should have
fun with their computers and not just use them for work.

There's only one problem: natively, C does not provide graphics capabilities!!

In order for C to be completely portable from platform to platform it has focused on providing
platform independent functions, such as file access, text string manipulation, mathematical functions,
etc. So in order to get graphics in C, one needs to do one of four things:

 Write a 16 bit DOS program and use assembly


language for graphics

 Make calls to the Windows API

 Make calls to the OpenGL subsystem

 Use a graphics library

The problem is, not all of these options are practical. One could for example, add some assembly
language in to the mix in order to add graphics capabilities. But there is a problem with this. Once upon
a time, it was easy to do graphics in assembly language. This was when machines were 16 bit. One
would simply call processor interrupts which alllowed for a variety of graphics functions to be sent to
the graphics card in the PC. One can still do this, but the problem is, one needs to write a 16 bit program.
That requires a 16 bit C compiler, capable of compiling 16 bit DOS programs. But pretty soon, 16 bit
programs won't be supported at all by Windows (and possibly even by the CPU's in PC's). Therefore,
this solution is hardly future proof (though for nostalgic reasons it might be fun for some of us).

One could try writing some 32 bit assembly language code for handling graphics. The problem
is, this is almost infinitely complicated, probably not portable from machine to machine and most likely
requires some negotiation with the operating system anyway, which means learning how to write device
drivers, DLL's and/or low level code for speaking directly to a graphics card. This is certainly out of the
question for all but the most advanced computer engineers, and only a few of those visit our site.

One can call the GDI functions provided by Windows itself. One slight problem here is that one
then needs to learn Win32 programming. That is a whole "language" in itself, and far too complicated
for an introductory, or even intermediate tutorial. The so-called Windows API (Application
Programming Interface), the part of Windows that programs communicate with to access features of the
operating system, does in fact provide numerous graphical functions. Although this is possible to learn,
the nature of Win32 programming is completely different to ordinary console programming in C that we
have been learning. Later on we may provide some tutorials on Win32 programming, but they really
make advanced tutorials. It isn't just a matter of running a function for drawing a line on the screen, etc.
One needs to negotiate with Windows for some space to draw the line, a window, etc, etc. The other
problem is, the actual GDI functions can be a bit restrictive and a bit slow for doing really decent, fast
graphics of the type we want.

The third option is to use OpenGL. This is a 3D graphics language which most modern graphics
cards support. The problem with this option is that one needs a bit of a Win32 program before one can
use OpenGL commands (unless one uses SDL). Also, programming 2D graphics effectively in OpenGL
requires some mucking around. It is like using a jackhammer to dig up a weed. OpenGL is simply
fantastic for 3D graphics programming, and we'd like to have tutorials about that too eventually, but for
now it falls into the advanced category. What is more, SDL allows one to hook directly into OpenGL
anyhow, and makes OpenGL programming easier, so why not start with SDL. That is not to say
OpenGL is a bad option - actually, it's great - but it is just more than we need for now.

The fourth option is to use a graphics library. The only problem is, it is very hard to find a simple
graphics library which will work with Pelles C, will be easy to use and which will produce fast graphics
programs. One can literally search for months to find one (as I did). But there is one. It is called SDL.
We recommend it as virtually the ONLY decent solution to our problem. And it is a good solution.

************

C Language Graphics Library Reference (part 1)

Posted on February 3rd, 2008

Graphics programming in C Language is discussed rarely. Today I will discuss some important functions
of graphics.h in C programming Language and in the next coming article I will make a simple program
to demonstrate the use of graphics functions. This is the part one of the article which discuses the
important graphics function to create and destroy the graphics environment. In part two I will show you
different graphics functions to draw shapes. And in last part I will add a sample program to
demonstrate the use of graphics.h library. So let's start with the description of important functions and
their use.

Below are the important functions and their description mostly used in graphics applications in C
Language.

Function initgraph
This function is used to load the graphics drivers and initialize the graphics system. For every function,
that uses graphics mode, graphics mode must be initialized before using that function.

void far initgraph(int far *driver, int far *mode, char far *path)
Path determines that path to the specified graphics driver.
Function detectgraph
Detectgraph function determines the graphics hardware in the system, if the function finds a graphics
adapter then it returns the highest graphics mode that the adapter supports.

void far detectgraph(int far *driver, int far *mode)

Function cleardevice
This function clears the graphics screen contents and return the control to the location (0,0).

void far cleardevice(void)

Function closegraph
This function shutdown the graphics mode and returns to the position it was before the initgraph
function was called. Closegraph function releases all the resources occupied by the graphics system like
memry, fonts, drivers etc…

void far closegraph(void)

********************

First of all we have to call the initgraph function that will intialize the graphics mode on the computer.
initigraph have the following prototype.

void initgraph(int far *graphdriver, int far *graphmode, char far *pathtodriver);
Initgraph initializes the graphics system by loading a graphics driver from disk (or validating a
registered driver) then putting the system into

graphics mode.Initgraph also resets all graphics settings (color, palette, current position, viewport,
etc.) to their defaults, then resets graphresult to 0.

*graphdriver
Integer that specifies the graphics driver to be used. You can give graphdriver a value using a constant
of the graphics_drivers enumeration type.

*graphmode
Integer that specifies the initial graphics mode (unless *graphdriver = DETECT). If *graphdriver =
DETECT, initgraph sets *graphmode to the highest resolution available for the detected driver. You can
give *graphmode a value using a constant of the graphics_modes enumeration type.
*pathtodriver
Specifies the directory path where initgraph looks for graphics drivers (*.BGI) first.

1. If they’re not there, initgraph looks in the current directory.


2. If pathtodriver is null, the driver files must be in the current directory.

*graphdriver and *graphmode must be set to valid graphics_drivers and graphics_mode values or
you’ll get unpredictable results. (The exception is graphdriver = DETECT.)

After a call to initgraph, *graphdriver is set to the current graphics driver, and *graphmode is set to
the current graphics mode. You can tell initgraph to use a particular graphics driver and mode, or to
autodetect the attached video adapter at run time and pick the corresponding driver. If you tell
initgraph to autodetect, it calls detectgraph to select a graphics driver and mode.

Normally, initgraph loads a graphics driver by allocating memory for the driver (through
_graphgetmem), then loading the appropriate .BGI file from disk.As an alternative to this dynamic
loading scheme, you can link a graphics driver file (or several of them) directly into your executable
program file.

Here is a sample program that initializes the graphics mode in C Language.

#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int main(void)
{
/* request auto detection */
int gdriver = DETECT, gmode, errorcode;
/* initialize graphics mode */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) /* an error occurred */
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1); /* return with error code */
}
/* draw a line */
line(0, 0, getmaxx(), getmaxy());
/* clean up */
getch();
closegraph();
return 0;
}
The graphics programming in c language is discussed in brief to provide an over view to the beginner.

/* Sample program to draw a circle*/


#include<graphics.h>
#include<conio.h>
main()
{
int gd=DETECT,gm;
initgraph(&gd,&gm,""); /* initialization of graphic mode */
circle(150,150,100);
getch();
closegraph(); /* Restore orignal screen mode */
}
/* End of program */
Normally the screen which u view in DOS is in the text mode which means it is meant for text. And for
graphics u need to initialize graphics mode. And for this to happen u need to include graphics.h?.

circle(x coordinate ,y coordinate , radius);


The circle command takes a X coordinate which means Vertical axis and Y coordinate which means
Horizontal axis. And the last one is the radius of the circle. closegraph();

With out this function the screen mode will still remain in graphic mode and when u come out, to DOS
u will see a different screen, which is not in the text mode.

/*A program to draw a space with stars*/


#include<graphics.h>
main()
{
int gd=DETECT,gm;
int i,x,y;
initgraph(&gd,&gm,"");
line(0,0,640,0);
line(0,0,0,480);
line(639,0,639,480);
line(639,479,0,479);
for(i=0;i<=1000;i++)
{
x=rand()%639;
y=rand()%480;
putpixel(x,y,15);
}
getch();
closegraph();
}
/* End of program */
/*Here a sample program to illustrate how to use BARS which are used for visual
statistics */
#include<graphics.h>
main() {
int gd=DETECT,gm,maxx,maxy,x,y,button;
initgraph(&gd,&gm,"");
line(80,150,200,150);
line(80,150,80,50);
settextstyle(1,HORIZ_DIR,1);
outtextxy(100,153,"<-X axis");
settextstyle(1,VERT_DIR,1);
outtextxy(60,50,"<-Y axis");
bar(100,100,120,150);
bar(130,120,150,150);
getch();
closegraph();
}
*******************

Graphics Essentials
Before jumping into the details of how graphics work in Windows and how they are applied to games, it's important to
establish some ground rules and gain an understanding of how computer graphics work in general. More specifically, you
need to have a solid grasp on what a graphics coordinate system is, as well as how color is represented in computer
graphics. The next couple of sections provide you with this knowledge, which you'll put to practical use a little later in the
chapter.

Understanding the Graphics Coordinate System


All graphical computing systems use some sort of graphics coordinate system to specify how points are arranged in a
window or on the screen. Graphics coordinate systems typically spell out the origin (0, 0) of the system, as well as the axes
and directions of increasing value for each of the axes. If you're not a big math person, this simply means that a coordinate
system describes how to pinpoint any location on the screen as an XY value. The traditional mathematical coordinate system
familiar to most of us is shown in Figure 3.1.

Figure 3.1 The traditional XY coordinate system is commonly used in math.

Windows graphics relies on a similar coordinate system to specify how and where drawing operations take
place. Because all drawing in Windows takes place within the confines of a window, the Windows
coordinate system is applied relative to a particular window. The Windows coordinate system has an
origin that is located in the upper-left corner of the window, with positive X values increasing to the right and positive Y values
increasing down. All values in the Windows coordinate system are positive integers. Figure 3.2 shows how this coordinate
system looks.

Figure 3.2 The Windows XY coordinate system is similar to the traditional coordinate system
except that it applies to the client area of windows.

NOTE

When I talk about drawing graphics in a window, I'm actually referring to the client area of a window, which doesn't include
the title bar, menus, scrollbars, and so on. In the case of games, you can think of the client area of the main game window as
the game screen. You learn more about the client area of a window later in this chapter in the section titled, "Painting
Windows."

If the Windows graphics coordinate system sounds a little complicated, just think of it in terms of a classic game of Battleship.
In Battleship, you try to sink enemy ships by firing torpedoes at specific locations on a grid. Battleship uses its own
coordinate system to allow you to specify locations on the grid where ships might be located. Similarly, when you draw
graphics in Windows, you specify locations in the client area of a window, which is really just a grid of little squares called
pixels.
Learning the Basics of Color
A topic that impacts almost every area of game graphics is color. Fortunately, most computer systems take a similar
approach to representing color. The main function of color in a computer system is to accurately reflect the physical nature of
color within the confines of a computer. This physical nature isn't hard to figure out; anyone who has experienced the joy of
Play-Doh can tell you that colors react in different ways when they are combined with each other. Like Play-Doh, a computer
color system needs to be capable of mixing colors with accurate, predictable results.

Color computer monitors provide possibly the most useful insight into how software systems implement color. A color monitor
has three electron guns: red, green, and blue. The output from these three guns converges on each pixel on the screen,
stimulating phosphors to produce the appropriate color. The combined intensities of each gun determine the resulting pixel
color. This convergence of different colors from the monitor guns is very similar to the convergence of different colored Play-
Doh.

NOTE

Technically speaking, the result of combining colors on a monitor is different from that of combining similarly colored Play-
Doh. The reason for this is that color combinations on a monitor are additive, meaning that mixed colors are added together
to become white; Play-Doh color combinations are subtractive, meaning that mixed colors are subtracted from each other to
become black. Whether the color combination is additive or subtractive depends on the physical properties of the particular
medium involved.

The Windows color system is very similar to the physical system used by color monitors; it forms unique colors by using
varying intensities of the colors red, green, and blue. Therefore, Windows colors are represented by the combination of the
numeric intensities of the primary colors (red, green, and blue). This color system is known as RGB (Red Green Blue) and is
standard across most graphical computer systems.

NOTE

RGB isn't the only color system used by computers. Another color system used heavily in desktop publishing applications is
CMYK, which stands for Cyan-Magenta-Yellow-Black. Colors in the CMYK color system are expressed in terms of the color
components cyan, magenta, yellow, and black, as opposed to red, green, and blue in RGB. The CMYK color system is used
heavily in printing because CMYK printing inks are subtractive in nature, making it easier to print using a four-color ink
combination (cyan, magenta, yellow, and black); hence the term four-color printing.

Table 3.1 shows the numeric values for the red, green, and blue components of some basic colors. Notice that the intensities
of each color component range from 0 to 255 in value.

Table 3.1 Numeric RGB Color Component Values for Commonly Used Colors
Color Red Green Blue

White 255 255 255


Black 0 0 0

Light Gray 192 192 192

Medium Gray 128 128 128

Dark Gray 64 64 64

Red 255 0 0

Green 0 255 0

Blue 0 0 255

Yellow 255 255 0

Purple 255 0 255

The Win32 API defines a structure named COLORREF that combines the red, green, and blue components of an RGB color
into a single value. The COLORREF structure is important because it is used throughout the Win32 API to represent RGB
colors. To create a color as a COLORREF structure, you use the RGB() macro, which accepts red, green, and blue color
components as arguments. Here is an example of creating a solid green color using RGB():

COLORREF green = RGB(0, 255, 0);


The color created in this line of code is green because the green component (the middle argument) is specified as 255,
whereas the red and blue components are specified as 0. Changing the values of these three arguments alters the mix of the
color—with lower numbers resulting in darker colors and higher numbers resulting in brighter colors.

You can experiment with RGB color combinations in the standard Paint program that comes with Windows. Double-click one
of the colors in the color palette in the lower left corner of the Paint window. Then, click the Define Custom Colors button in
the Edit Colors dialog box. You can then either type numbers into the Red, Green, and Blue edit fields or click to select a
color and intensity (see Figure 3.3).

Figure 3.3 The standard Windows Paint program allows you to specify colors via RGB values.
************

You might also like