Skip to content

Instantly share code, notes, and snippets.

@edom18
Created March 24, 2014 13:58
Show Gist options
  • Select an option

  • Save edom18/9740598 to your computer and use it in GitHub Desktop.

Select an option

Save edom18/9740598 to your computer and use it in GitHub Desktop.
Objective-CでOpenGL事始め ref: http://qiita.com/edo_m18/items/6a911da63990d96be7fc
// ViewController.h
@interface SampleViewController : UIViewController <GLKViewDelegate>
{
// 頂点バッファのインデックス保持用インスタンス変数。
// インデックス番号なので`GL uint`型
GLuint vertexBufferID;
}
// ViewController.m
typeof struct {
GLKVector3 position;
} Vertex;
static const Vertex vertices[] = {
{{ 0.0, -0.5, 0.0}},
{{ 0.5, -0.5, 0.0}},
{{-0.5, 0.5, 0.0}},
};
- (void)viewDidLoad
{
self.glview = [[GLKView alloc] initWithFrame:self.view.bounds];
// OpenGL ES 2を使う
self.glview.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
[self.view addSubview:self.glview];
self.glview.delegate = self;
// 生成したコンテキストをカレントコンテキストに設定
[EAGLContext setCurrentContext:self.glview.context];
// BaseEffectを生成
self.baseEffect = [[GLKBaseEffect alloc] init];
self.baseEffect.useConstantColor = GL_TRUE;
self.baseEffect.constantColor = GLKVector4Make(1.0, 1.0, 1.0, 1.0); // 白
// self.baseEffect.transform.modelviewMatrix = GLKMatrix4MakeZRotation(M_PI);
self.baseEffect.transform.projectionMatrix = GLKMatrix4MakeScale(1.0, self.glview.bounds.size.width / self.glview.bounds.size.height, 1.0); // アスペクト比を維持
// クリアカラーを黒に
// glClear関数に`GL_COLOR_BUFFER_BIT`が立てられている場合に、この設定の色で塗りつぶされる
glClearColor(0.0, 0.0, 0.0, 1.0);
// GPUに情報を渡すためのバッファを生成する
// GenはGenerateの「Gen」
glGenBuffers(1, &vertexBufferID);
// 生成したバッファをバインド
glBindBuffer(GL_ARRAY_BUFFER, vertexBufferID);
// バインドしたバッファにデータを転送
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// バッファのバインドを解除しておく
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect
{
// レンダリング前の準備
[self.baseEffect prepareToDraw];
// 画面をクリア
glClear(GL_COLOR_BUFFER_BIT);
// 頂点位置情報を有効化
glEnableVertexAttribArray(GLKVertexAttribPosition);
// バッファをバインド
glBindBuffer(GL_ARRAY_BUFFER, vertexBufferID);
// 頂点位置情報としてバッファの位置を指定 ※1
glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0);
// 図形を描く
glDrawArrays(GL_TRIANGLES, 0, 3);
}
void glVertexAttribPointer(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *ptr);
baseEffect.transform = GLKMatrix4MakeZRotation(M_PI); // Z軸に対して180度回転
// 縦の比率を`self.view.bounds`を元に計算する
baseEffect.transform.projectionMatrix = GLKMatrix4MakeScale(1.0, self.view.bounds.size.width / self.view.bounds.size.height, 1.0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment