Monday, October 12, 2009

groovyとJOGLで画像を放射状に配置する

groovyとJOGLで画像を放射状に配置するには、以下のコードを実行します。


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

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

fn = [
"sample1182a.png",
"sample1189a.png",
"sample1191a.png",
"sample1194a.png",
"sample1195a.png",
"sample1196a.png",
"sample1197a.png",
"sample1198a.png",
"sample1199a.png",
"sample1201a.png",
"sample1202a.png",
"sample1206a.png"
]
textures = new Texture[fn.size]

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(
0x68/0xff as Float,
0x60/0xff as Float,
0x60/0xff as Float,
1f)
for(fi in 0..fn.size-1){
textures[fi] =
TextureIO.newTexture(
new File(fn[fi]), true)
textures[fi].enable();
}
},

display: {
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(0.0f, -0.5f, -12.0f)

gl.glEnable(GL_LIGHTING)
gl.glEnable(GL_LIGHT0)
gl.glEnable(GL_COLOR_MATERIAL)
gl.glEnable(GL_AUTO_NORMAL);
gl.glEnable(GL_NORMALIZE)
gl.glEnable(GL_DEPTH_TEST)
// gl.glEnable(GL_CULL_FACE)
gl.glLightModeli(GL_LIGHT_MODEL_TWO_SIDE,
GL_TRUE)

gl.glEnable(GL_TEXTURE_2D)

gl.glClear(GL_COLOR_BUFFER_BIT
| GL_DEPTH_BUFFER_BIT )

gl.glPushMatrix()

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

da = 360f / fn.size
ps = 2f
for(qi in 0..fn.size-1){
// テクスチャが張られたポリゴンを描画
textures[qi].bind();
px = ps * (float)Math.cos(
Math.PI * da * qi / 180) as float
pz = ps * (float)Math.sin(
Math.PI * da * qi / 180) as float
nx = ps * (float)Math.cos(
Math.PI * (da * qi+90) / 180) as float
nz = ps * (float)Math.sin(
Math.PI * (da * qi+90) / 180) as float

gl.glBegin(GL_QUADS)
gl.glNormal3f(nx, 0.0f, nz)

gl.glTexCoord2f(0.0f, 0.0f)
gl.glVertex3f(0f, ps/2f as float, 0f)
gl.glTexCoord2f(0.0f, 1.0f)
gl.glVertex3f(0f, -ps/2f as float, 0f)
gl.glTexCoord2f(1.0f, 1.0f)
gl.glVertex3f(px, -ps/2f as float, pz)
gl.glTexCoord2f(1.0f, 0.0f)
gl.glVertex3f(px, ps/2f as float, pz)
gl.glEnd()
}

gl.glPopMatrix()
},

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


出力画像(sample1306a.png)
groovyとJOGLで放射状に複数の画像を配置した画像

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

関連情報
groovyとJOGLのまとめ

No comments: