Wednesday, October 14, 2009

groovyとJOGLで複数の直方体を凸凹に配置する

groovyとJOGLで複数の直方体を凸凹に配置するには、以下のコードを実行します。


import static javax.media.opengl.GL.*;
import java.io.*;
import javax.media.opengl.*;
import com.sun.opengl.util.*;

// 出力画像サイズ
width = 300
height = 300

GLDrawableFactory gldf =
GLDrawableFactory.getFactory()
GLCapabilities glc = new GLCapabilities()
glc.setDoubleBuffered(false)
GLPbuffer buf = gldf.createGLPbuffer(
glc, null, width, height, null)
GL gl = buf.getGL()

buf.addGLEventListener(
[ init: {
// 背景色
gl.glClearColor(
0x58/0xff as Float,
0x50/0xff as Float,
0x50/0xff as Float,
1f)
},

display: {
GLUT glut = new GLUT()
gl.glViewport(0, 0, width, height)

// 透視投影
gl.glMatrixMode(GL_PROJECTION)
gl.glLoadIdentity()
float ratio = height/width as Float
gl.glFrustum(-1.0f, 1.0f, -ratio, ratio,
5.0f, 40.0f)

gl.glMatrixMode(GL_MODELVIEW)
gl.glLoadIdentity()
gl.glTranslatef(-3.0f, -1.5f, -7.0f)

gl.glEnable(GL_LIGHTING)
gl.glEnable(GL_LIGHT0)
gl.glEnable(GL_COLOR_MATERIAL)
gl.glEnable(GL_NORMALIZE)
gl.glEnable(GL_DEPTH_TEST)
gl.glEnable(GL_CULL_FACE)

// フォグの設定
fog=[0.1f,0.1f,0.2f,1.0f]
gl.glFogfv(GL_FOG_COLOR,fog as float[], 0)
gl.glFogi(GL_FOG_MODE,GL.GL_EXP)
gl.glFogf(GL_FOG_DENSITY, 0.08f)
gl.glFogf(GL_FOG_START, 0.0f)
gl.glFogf(GL_FOG_END,20.0f)
gl.glEnable(GL_FOG)

// 光源の位置
l1pos = [-5.0f, 5.0f, 0.0f, 1.0f]
gl.glLightfv(GL_LIGHT0, GL_POSITION, l1pos as float[], 0)
// 環境光
l1amb = [0.2f, 0.2f, 0.1f, 1.0f]
gl.glLightfv(GL_LIGHT0, GL_AMBIENT, l1amb as float[], 0)
// 拡散光
l1dif = [0.9f, 0.9f, 0.9f, 1.0f]
gl.glLightfv(GL_LIGHT0, GL_DIFFUSE, l1dif as float[], 0)
// 鏡面光
l1spe = [0.9f, 0.9f, 0.9f, 1.0f]
gl.glLightfv(GL_LIGHT0, GL_SPECULAR, l1spe as float[], 0)

gl.glClear(GL_COLOR_BUFFER_BIT
| GL_DEPTH_BUFFER_BIT )

gl.glPushMatrix()

// 面の色を設定
gl.glColor3f(
0xff/0xff as float,
0xff/0xff as float,
0xff/0xff as float
)

// X軸回転
gl.glRotatef(15.0f, 1.0f, 0.0f, 0.0f)
// Y軸回転
gl.glRotatef(30.0f, 0.0f, 1.0f, 0.0f)

cs = 0.5f
gs = 0.6f
xs = 50
zs = 50
for(lz in -3..zs-1){
for(lx in -3..xs-1){
gl.glPushMatrix()
ch = cs * (float)(Math.random()*1.0) as float
gl.glScalef(1f,ch, 1f)
gl.glTranslatef(lx*gs as float,
-(cs-ch)/2 as float, -1*lz*gs as float)
glut.glutSolidCube(cs)
gl.glPopMatrix()
}
}

gl.glPopMatrix()
},

reshape: {},
displayChanged: {}
] as GLEventListener
)
GLContext context =
buf.createContext(null)
context.makeCurrent()
buf.display()
Screenshot.writeToFile(
new File("sample1308a.png"),
width, height, true)
context.release()
context.destroy()


出力画像(sample1308a.png)
groovyとJOGLで複数の直方体を凸凹に配置した画像

動作環境
JDK1.6 Update14, Groovy 1.6.3, JOGL 1.1.1a

関連情報
groovyとJOGLのまとめ

No comments:

Post a Comment