BlenderのAdd – Mesh – Monkeyで作れるおさるさんをGLKitで表示してみる
(XcodeのiOS6 Simulatorで試しています。)
ポイント
・storyboardでルートのViewをGLKViewにしています。
・Blenderからobjでexport
(設定でtriangulate Faces と include Normalをチェックした)
・objは obj2opengl.pl を使って C headerファイルにコンバート
参照:Heiko Behrens (http://www.HeikoBehrens.net)
サンプルコード
ViewController.h
#import <GLKit/GLKit.h>
@interface ViewController : GLKViewController
@end
ViewController.m
#import “ViewController.h”
#import “monkey.h”
@interface ViewController () {
GLuint v;
GLuint nv;
}
@property (strong, nonatomic) GLKBaseEffect *baseEffect;
@property (strong, nonatomic) GLKView *gv;
@end
@implementation ViewController
@synthesize baseEffect, gv;
– (void)viewDidLoad
{
gv = (GLKView*)self.view;
gv.drawableDepthFormat = GLKViewDrawableDepthFormat16;
gv.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
[EAGLContext setCurrentContext:gv.context];
[super viewDidLoad];
self.baseEffect = [[GLKBaseEffect alloc] init];
self.baseEffect.light0.enabled = GL_TRUE;
self.baseEffect.light0.diffuseColor = GLKVector4Make(0.7f,0.7f,0.7f,1.0f);
self.baseEffect.light0.position = GLKVector4Make(-0.8f,-0.8f,-1.0f,0.0f);
self.baseEffect.light0.ambientColor = GLKVector4Make(0.2f, 0.2f, 0.2f, 1.0f);
glClearColor(.5f, .5f, .5f, 1.0f);
glGenBuffers(1, &v);
glBindBuffer(GL_ARRAY_BUFFER, v);
glBufferData(GL_ARRAY_BUFFER, sizeof(monkeyVerts), monkeyVerts, GL_STATIC_DRAW);
glGenBuffers(1, &nv);
glBindBuffer(GL_ARRAY_BUFFER, nv);
glBufferData(GL_ARRAY_BUFFER, sizeof(monkeyNormals), monkeyNormals, GL_STATIC_DRAW);
glEnable(GL_DEPTH_TEST);
}
– (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *t = [touches anyObject];
CGPoint p = [t locationInView:self.view];
GLKMatrix4 modelViewMatrix = GLKMatrix4MakeRotation(GLKMathDegreesToRadians(p.x), 0.0f, 0.0f, 1.0f);
modelViewMatrix = GLKMatrix4Rotate(modelViewMatrix,GLKMathDegreesToRadians(p.y), 0.0f, 1.0f, 0.0f);
self.baseEffect.transform.modelviewMatrix = modelViewMatrix;
}
– (void)glkView:(GLKView *)view drawInRect:(CGRect)rect
{
[self.baseEffect prepareToDraw];
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glBindBuffer(GL_ARRAY_BUFFER, v);
glEnableVertexAttribArray(GLKVertexAttribPosition);
glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), NULL + 0);
glBindBuffer(GL_ARRAY_BUFFER, nv);
glEnableVertexAttribArray(GLKVertexAttribNormal);
glVertexAttribPointer(GLKVertexAttribNormal, 3, GL_FLOAT, GL_FALSE, 3* sizeof(GLfloat), NULL + 0);
const GLfloat aspectRatio = (GLfloat)view.drawableWidth / (GLfloat)view.drawableHeight;
self.baseEffect.transform.projectionMatrix = GLKMatrix4MakeScale(0.5f, 0.5 * aspectRatio, 0.5f);
glDrawArrays(GL_TRIANGLES, 0, monkeyNumVerts);
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end