Friday, March 13, 2009

Is this an impossible shape in 3-D? I can't work out if it is or isn't. I'm thinking of using this in Chapter 33 (or is it 34)... as an example of how OpenGL can be used in 2-d drawings to achieve effects otherwise not possible.




Here's the code. You'll need OpenGL running though. You might want to fiddle around with k_rectangles to get the thing running reasonably well. Watch out for the Moray patterns though! 

b e n 



import javax.media.opengl.* ;
import processing.opengl.*;

//
// Inf 1.
//
// Draw a twistig ring shape.
//

final int k_rectangles = 300 ;
final int k_width = 50 ;
final int k_height = 50 ;
final color k_background_colour = color( 100, 200, 128, 255 ) ;
final color k_edge_colour = color( 200, 200, 200, 255 ) ;
final color k_fill_colour = color( 255, 255, 255, 255 ) ;

void setup()
{
// size( 640, 480, JAVA2D ) ; // , P3D ) ;
size( 640, 480, OPENGL ) ;

smooth() ;
}

void draw()
{
//
// Clear the background and set up a drawing style for the rectangles.
//
background( k_background_colour ) ;

stroke( k_edge_colour ) ;
fill( k_fill_colour ) ;
rectMode( RADIUS ) ;

//
// Draw a circle using a sequence of rectangles painted on top of each other.
//
for ( int i = 0 ; i < k_rectangles ; ++i )
{

pushMatrix() ;

//
// Fudge the depth of the rectangles so that the last few rectangles are painted
// underneath the starting rectangles.
//
float dz = i > k_rectangles / 4 ? -0.1 : 0.0 ;

PGraphicsOpenGL pgl = (PGraphicsOpenGL) g ;
GL gl = pgl.beginGL() ;

if ( i < k_rectangles / 5 )
gl.glEnable( gl.GL_DEPTH_TEST ) ;
else
if ( i < k_rectangles / 2 )
gl.glDisable( gl.GL_DEPTH_TEST ) ;
else
gl.glEnable( gl.GL_DEPTH_TEST ) ;

pgl.endGL() ;


//
// Draw the rectangle.
// The Processing variable frameCount is used to animate the rotation of the rectangles.
//
translate( width/2 + 150 * sin( PI * 2.0 * i / k_rectangles ), height/2 + 150 * cos( PI * 2.0 * i / k_rectangles ), dz ) ;
rotate( frameCount * 0.01 ) ;

rect( 0, 0, k_width, k_height ) ;

popMatrix() ;

}
}

2 comments:

Anonymous said...

Moray is an eel, I fink you ment Moire.
Cool animation from such little code amazing.

lazydog said...

Thanks for putting me right! All credit to Processing though for making it simple to write and experiment with.

b e n