// LiangBarClipViewer.cpp // NKU CSC 480 - Kirby // -------------------------------------------------------------------------------- // Demonstrate Liang-Barsky clipping (in file LiBarClipLib.h, .cpp). // Draws many random colored lines, then clips to a rectangle. 2D only. // --------------------------------------------------------------------------------- #include #include #include #include #include "LiBarClipLib.h" using namespace std ; const int NLINES= 100 ; // # of random lines to draw inline double urand() { return (double) rand() / RAND_MAX ; } // random real 0..1. struct Line2D // A colored line, visible or not. { Line2D() : visible( true ) , xA( urand() ), yA( urand() ), xB( urand() ), yB( urand() ) , r( urand() ), g( urand() ), b( urand() ) {} bool visible ; float xA,yA, xB,yB ; float r,g,b ; } ; // Global vector of random lines to be displayed and clipped. vector G_vecLines ; void makeLines( vector& vecLines, int n ) // Fill vecLines[] with n random, randomly colored lines. { vecLines.clear() ; for ( int i=0 ; i < n ; ++i ) vecLines.push_back( Line2D() ) ; } void clipLines( vector& vecLines ) // Apply clipper to all lines in vecLines. { Rect rect( 0.2, 0.6, 0.3, 0.9 ) ; for ( int i=0 ; i < (int) vecLines.size() ; ++i ) { Line2D& ln= vecLines[i] ; ln.visible= clip( rect, ln.xA, ln.yA, ln.xB, ln.yB ) ; } } void drawLines( const vector& vecLines ) // Draw all the lines in vecLines. { glBegin( GL_LINES ) ; for ( int i=0 ; i < (int) vecLines.size() ; ++i ) { const Line2D& ln= vecLines[i] ; if ( ln.visible ) { glColor3f( ln.r, ln.g, ln.b ) ; glVertex3f( ln.xA, ln.yA, 0 ) ; glVertex3f( ln.xB, ln.yB, 0 ) ; } } glEnd() ; } void display() // Display the lines. { glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ) ; drawLines( G_vecLines ) ; glutSwapBuffers() ; } void kbDispatch( unsigned char ch, int x, int y ) // Toggle global state variables, or print projection matrix. { switch( ch ) { case 'c': clipLines( G_vecLines ) ; break ; case 'm': makeLines( G_vecLines, NLINES ) ; break ; } glutPostRedisplay() ; } int main( int argc, char** argv ) { // Initialize OpenGL. glutInit( &argc, argv ) ; glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH ) ; // Window attributes. glutInitWindowSize( 700, 700 ) ; glutInitWindowPosition( 100, 100 ) ; glutCreateWindow( "Liang Barsky Clipping Demo. Keys: m c" ) ; // Register callbacks. glutKeyboardFunc( kbDispatch ) ; glutDisplayFunc( display ) ; // Lines srand( time( 0 ) ) ; makeLines( G_vecLines, NLINES ) ; // Simple orthographic projection glMatrixMode( GL_PROJECTION ) ; glOrtho( 0,1, 0,1, -1,1 ) ; glMatrixMode( GL_MODELVIEW ) ; // Go. glutMainLoop() ; return 0 ; }