Code:
/* ||__This is programming assignment 3__||
||__ Robert Harp CPSC 101 Section 1 __||
||__ **Shapes.c** __||
||__********************************__||
||__ **Due 03.14.13** __||
||__ This is a program that creates __||
||__ a PPM image containing an __||
||__ circle and a purple triangle __||
++====================================++ */
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<stdbool.h>
#include "Shapes.h"
void make_header(int, int);
void make_image(int, int);
void make_pixel(unsigned char, unsigned char, unsigned char);
double area(int, int, int, int, int, int);
bool is_inside(int, int, int, int, int, int, int, int);
/*
*
*/
int main(void)
{
int height, width;
height = 480;
width = 640;
make_header(width, height);
make_image(width, height);
fprintf(stderr, "creating an image with a width %d pixels by a height"
" %d pixels\n", width, height);
return (0);
}
/*
* function to make a PPM header for the file
*/
void make_header(int width, int height)
{
fprintf(stdout,"P6\n%d %d %d\n", width, height, 255);
}
/*
* function to make the image and all of its shapes
*/
void make_image(int width, int height)
{
int x, y; //values respective to each axis
for(y = 1; y <= height; y++)
{
for(x = 1; x <= width; x++)
{ //if <circle>, else if <triangle>, else <background>
if ((((x-CCX) * (x-CCX) + (y-CCY) * (y-CCY)) <= 5625))
{
make_pixel(255,125,1); //Orange circle
}
else
{
if (is_inside(TAX, TAY, TBX, TBY, TCX, TCY, x, y))
{
make_pixel(148, 0, 212); // Purple triangle
}
else
{
make_pixel(0, 0, 0); //Black background
}
}
}
}
}
/*
* Function to print each individual pixel
*/
void make_pixel(unsigned char r, unsigned char g, unsigned char b)
{
printf("%c%c%c", r, g, b);
}
/*
* Function to find the area of each
*/
double area(int x1, int y1, int x2, int y2, int x3, int y3)
{
return abs((x1*(y2-y3) + x2*(y3-y1)+ x3*(y1-y2))/2.0);
}
/*
* A function to check whether point P(x, y) lies inside the triangle formed
* by A(x1, y1), B(x2, y2) and C(x3, y3)
*/
bool is_inside(int x1, int y1, int x2, int y2, int x3, int y3, int x, int y)
{
/* Calculate area of triangle ABC */
double long A = area (x1, y1, x2, y2, x3, y3);
/* Calculate area of triangle PBC */
double long A1 = area (x, y, x2, y2, x3, y3);
/* Calculate area of triangle PAC */
double long A2 = area (x1, y1, x, y, x3, y3);
/* Calculate area of triangle PAB */
double long A3 = area (x1, y1, x2, y2, x, y);
/* Check if sum of A1, A2 and A3 is same as A */
return (A >= A1 + A2 + A3);
}
/*
* Coded by Robbo
*/