/*********************************************************************************************/
/*
*/
/* Java 3D Engine Basics Tutorials - Tut Solid
Triangle */
/* Auth: bkenwright@xbdev.net
*/
/* URL: www.xbdev.net
*/
/*
*/
/* Drawing our own solid triangle using linear
interpolation */
/*
*/
/*********************************************************************************************/
import
java.awt.image.*;
import
java.awt.*;
import
java.applet.*;
public
class
solidtriangle
extends
Applet
{
public
void
paint(Graphics g)
{ SolidTriangle(g, mouse_x_right, mouse_y_right,
mouse_x_left, mouse_y_left,
90, 230, Color.green);
}// End of paint(..)
public
void
setPixel(Graphics g,
int
x,
int
y, Color color )
{ g.setColor( color );
g.fillRect( x, y, 1, 1 );
}// End of setPixel(..)
int
mouse_x_right= 10;
int
mouse_y_right= 10;
int
mouse_x_left= 100;
int
mouse_y_left= 100;
public
boolean
mouseDown(Event evt,
int
x,
int
y)
{
if(evt.id ==
Event.MOUSE_DOWN)
{
// Right mouse button
if(
evt.metaDown() ==
true
)
{
System.out.println(
"Right MouseDown"
);
mouse_x_right = x;
mouse_y_right = y;
}
else
// right mouse button
{
System.out.println(
"Left MouseDown"
);
mouse_x_left = x;
mouse_y_left = y;
}
}// End if
repaint();
return
true;
}// End of mouseDown(..)
void
SolidTriangle( Graphics
g,
float
x0,
float
y0,
float
x1,
float
y1,
float
x2,
float
y2,
Color colour )
{
//Sort into order y0 -> y1 -> y2
float
temp;
if(
y1 < y0 )
{
temp=y1; y1=y0; y0=temp;
temp=x1; x1=x0; x0=temp;
}
if(
y2 < y0 )
{
temp=y2; y2=y0; y0=temp;
temp=x2; x2=x0; x0=temp;
}
if(
y2 < y1 )
{
temp=y2; y2=y1; y1=temp;
temp=x2; x2=x1; x1=temp;
}
// Draw Top Half Triangle
float
x_left = x0;
float
x_right = x0;
float
dx_left = x1 - x0;
// to the middle then we change it
float
dx_right = x2 - x0;
// all the way to the bottom :)
dx_left = (x1 - x0) / (y1 -
y0);
dx_right = (x2 - x0) / (y2 - y0);
int
s = 0;
float
t;
// temp variable
if(
dx_left > dx_right )
{
t = dx_left;
dx_left = dx_right;
dx_right = t;
s=1;
}//End if
for(float
y=y0; y<y1; y++)
{
for(float
x=x_left; x<x_right; x++)
{
setPixel(g, (int)x,
(int)y,
colour );
}// End inner for loop
x_left += dx_left;
x_right += dx_right;
}// End outer for loop
// Now for the bottom of the
triangle
// Whats the s==0 for? Well we made the assumption that dx_left
// goes all the way to p2 (the bottom) if now we set s to 1, and then
// dx_right goes all the way to the bottom.
if(
s == 0 )
{
dx_left = (x2 - x1) / (y2 - y1);
}
else
{
dx_right = (x2 - x1) / (y2 - y1);
}
for(float
y=y1; y<y2; y++)
{
for(float
x=x_left; x<x_right; x++)
{
setPixel(g, (int)x,
(int)y,
colour);
}
x_left += dx_left;
x_right += dx_right;
}// End outer for loop
}//
End SolidTriangle(..)
}//
End of our Applet
|