
//Set screen size
final int screenwid = 720;
final int screenhei = 480;
int bxmin, bxmax, bymin, bymax;
void setup()
{
size(screenwid, screenhei);
noLoop();
}
void draw()
{
//Declare clipping bounds and create rectangle
bxmin = screenwid/4;
bymin = screenhei/4;
bxmax = screenwid/4 + screenwid/2;
bymax = screenhei/4 + screenhei/2;
//rect(bxmin, bymin, screenwid/2, screenhei/2);
rect(bxmin, bymin, (bxmax - bxmin), (bymax - bymin));
//Produce 5 triangles with random points
int x0, x1, x2, y0, y1, y2;
for(int i = 0; i < 5; i++)
{
//Initiate points of triangle
x0 = int(random(screenwid));
x1 = int(random(screenwid));
x2 = int(random(screenwid));
y0 = int(random(screenhei));
y1 = int(random(screenhei));
y2 = int(random(screenhei));
//Draw edges
drawline(x0, y0, x1, y1);
drawline(x1, y1, x2, y2);
drawline(x2, y2, x0, y0);
}
}
//Calculate Sutherland-Cohen clipping code
int bP(int x, int y) {
int b = 0;
//X too low
if(x < bxmin)
b += 8;
//X too high
if(x > bxmax)
b += 4;
//Y too low
if(y > bymax)
b += 2;
//Y too high
if(y < bymin)
b += 1;
return b;
}
boolean rejectCheck(int b0, int b1) {
if((b0 & b1) != 0)
return true;
return false;
}
boolean acceptCheck(int b0, int b1) {
if((b0 == 0) && (b1 == 0))
return true;
return false;
}
boolean drawline(int x0, int y0, int x1, int y1) {
int b0, b1;
while(true) {
b0 = bP(x0, y0);
b1 = bP(x1, y1);
if(rejectCheck(b0, b1))
return false;
if(acceptCheck(b0, b1)) {
line(x0, y0, x1, y1);
return true;
}
if(b0 == 0) {
int tempCoord, tempCode;
tempCoord = x0; x0 = x1; x1 = tempCoord;
tempCoord = y0; y0 = y1; y1 = tempCoord;
tempCode = b0; b0 = b1; b1 = tempCode;
}
if((b0 & 1)!=0) {
x0 += (x1 - x0)*(bymax-y0)/(y1-y0);
y0 = bymax;
}
else if((b0 & 2)!=0) {
x0 += (x1 - x0)*(bymin-y0)/(y1-y0);
y0 = bymin;
}
else if((b0 & 4)!=0) {
y0 += (y1-y0)*(bxmax-x0)/(x1-x0);
x0 = bxmax;
}
else if((b0 & 8)!=0) {
y0 += (y1-y0)*(bymin-x0)/(x1-x0);
x0 = bxmin;
}
}
}
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment