Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #import "HelloGLKitViewController.h"
- #import "Objects.h"
- GLKMatrix4 modelViewMatrix;
- GLKMatrix4 projectionMatrix;
- Drawable cube;
- GLKTextureInfo * info;
- GLKTextureInfo * info2;
- // THIS IS THE STRUCTURE FOR THE CUBE IN THE TUTORIAL.
- // THIS IS NOT BEING RENDERED.
- typedef struct {
- float Position[3];
- float Color[4];
- float TexCoord[2];
- } Vertex;
- const Vertex Vertices[] = {
- // Front
- {{1, -1, 1}, {1, 0, 0, 1}, {1, 0}},
- {{1, 1, 1}, {0, 1, 0, 1}, {1, 1}},
- {{-1, 1, 1}, {0, 0, 1, 1}, {0, 1}},
- {{-1, -1, 1}, {0, 0, 0, 1}, {0, 0}},
- // Back
- {{1, 1, -1}, {1, 0, 0, 1}, {0, 1}},
- {{-1, -1, -1}, {0, 1, 0, 1}, {1, 0}},
- {{1, -1, -1}, {0, 0, 1, 1}, {0, 0}},
- {{-1, 1, -1}, {0, 0, 0, 1}, {1, 1}},
- // Left
- {{-1, -1, 1}, {1, 0, 0, 1}, {1, 0}},
- {{-1, 1, 1}, {0, 1, 0, 1}, {1, 1}},
- {{-1, 1, -1}, {0, 0, 1, 1}, {0, 1}},
- {{-1, -1, -1}, {0, 0, 0, 1}, {0, 0}},
- // Right
- {{1, -1, -1}, {1, 0, 0, 1}, {1, 0}},
- {{1, 1, -1}, {0, 1, 0, 1}, {1, 1}},
- {{1, 1, 1}, {0, 0, 1, 1}, {0, 1}},
- {{1, -1, 1}, {0, 0, 0, 1}, {0, 0}},
- // Top
- {{1, 1, 1}, {1, 0, 0, 1}, {1, 0}},
- {{1, 1, -1}, {0, 1, 0, 1}, {1, 1}},
- {{-1, 1, -1}, {0, 0, 1, 1}, {0, 1}},
- {{-1, 1, 1}, {0, 0, 0, 1}, {0, 0}},
- // Bottom
- {{1, -1, -1}, {1, 0, 0, 1}, {1, 0}},
- {{1, -1, 1}, {0, 1, 0, 1}, {1, 1}},
- {{-1, -1, 1}, {0, 0, 1, 1}, {0, 1}},
- {{-1, -1, -1}, {0, 0, 0, 1}, {0, 0}}
- };
- const GLubyte Indices[] = {
- // Front
- 0, 1, 2,
- 2, 3, 0,
- // Back
- 4, 6, 5,
- 4, 5, 7,
- // Left
- 8, 9, 10,
- 10, 11, 8,
- // Right
- 12, 13, 14,
- 14, 15, 12,
- // Top
- 16, 17, 18,
- 18, 19, 16,
- // Bottom
- 20, 21, 22,
- 22, 23, 20
- };
- #endif
- @interface HelloGLKitViewController () {
- GLuint _vertexBuffer;
- GLuint _indexBuffer;
- float _rotation;
- }
- @end
- @implementation HelloGLKitViewController
- @synthesize context = _context;
- @synthesize effect = _effect;
- #pragma mark - View lifecycle
- - (void)setupGL {
- [EAGLContext setCurrentContext:self.context];
- glEnable(GL_CULL_FACE);
- self.effect = [[GLKBaseEffect alloc] init];
- NSDictionary * options = [NSDictionary dictionaryWithObjectsAndKeys:
- [NSNumber numberWithBool:YES],
- GLKTextureLoaderOriginBottomLeft,
- nil];
- NSError * error;
- NSString *path = [[NSBundle mainBundle] pathForResource:@"tile_floor" ofType:@"png"];
- info = [GLKTextureLoader textureWithContentsOfFile:path options:options error:&error];
- if (info == nil) {
- NSLog(@"Error loading file: %@", [error localizedDescription]);
- }
- NSString *path2 = [[NSBundle mainBundle] pathForResource:@"stopButton" ofType:@"png"];
- info2 = [GLKTextureLoader textureWithContentsOfFile:path2 options:options error:&error];
- if (info2 == nil) {
- NSLog(@"Error loading file: %@", [error localizedDescription]);
- }
- cube = [self createDrawable:@"Cube.obj"];
- // Old stuff
- glGenBuffers(1, &_vertexBuffer);
- glBindBuffer(GL_ARRAY_BUFFER, _vertexBuffer);
- glBufferData(GL_ARRAY_BUFFER, sizeof(Vertices), Vertices, GL_STATIC_DRAW);
- glGenBuffers(1, &_indexBuffer);
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indexBuffer);
- glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(Indices), Indices, GL_STATIC_DRAW);
- }
- - (void) tearDownGL {
- [EAGLContext setCurrentContext:self.context];
- glDeleteBuffers(1, &_vertexBuffer);
- glDeleteBuffers(1, &_indexBuffer);
- self.effect = nil;
- }
- #pragma mark - GLKViewDelegateiew loading and unloading
- - (void)viewDidLoad {
- [super viewDidLoad];
- self.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
- if (!self.context) {
- NSLog(@"Failed to create ES context");
- }
- GLKView *view = (GLKView *)self.view;
- view.context = self.context;
- view.drawableMultisample = GLKViewDrawableMultisample4X;
- [self setupGL];
- }
- - (void)viewDidUnload {
- [super viewDidUnload];
- [self tearDownGL];
- if ([EAGLContext currentContext] == self.context) {
- [EAGLContext setCurrentContext:nil];
- }
- self.context = nil;
- }
- - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
- {
- // Return YES for supported orientations
- return (interfaceOrientation == UIInterfaceOrientationPortrait);
- }
- #pragma mark - GLKViewDelegate
- - (void)glkView:(GLKView *)view drawInRect:(CGRect)rect {
- glClearColor(1.0f, 1.0, 1.0, 1.0);
- glClear(GL_COLOR_BUFFER_BIT);
- [self.effect prepareToDraw];
- self.effect.texture2d0.name = info.name;
- self.effect.texture2d0.enabled = true;
- glBindBuffer(GL_ARRAY_BUFFER, _vertexBuffer);
- glEnableVertexAttribArray(GLKVertexAttribPosition);
- glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid *) offsetof(Vertex, Position));
- glEnableVertexAttribArray(GLKVertexAttribColor);
- glVertexAttribPointer(GLKVertexAttribColor, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid *) offsetof(Vertex, Color));
- glEnableVertexAttribArray(GLKVertexAttribTexCoord0);
- glVertexAttribPointer(GLKVertexAttribTexCoord0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid *) offsetof(Vertex, TexCoord));
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indexBuffer);
- // NOT RENDERING THE DEFAULT CUBE.
- //glDrawElements(GL_TRIANGLES, sizeof(Indices)/sizeof(Indices[0]), GL_UNSIGNED_BYTE, 0);
- self.effect.texture2d0.name = info2.name;
- self.effect.texture2d0.enabled = true;
- [self renderDrawable:cube];
- glFlush();
- }
- #pragma mark - GLKViewControllerDelegate
- - (void)update {
- float aspect = fabsf(self.view.bounds.size.width / self.view.bounds.size.height);
- projectionMatrix = GLKMatrix4MakePerspective(GLKMathDegreesToRadians(65.0f), aspect, 2.0f, 20.0f);
- self.effect.transform.projectionMatrix = projectionMatrix;
- modelViewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, -10.0f);
- _rotation += 45 * self.timeSinceLastUpdate;
- modelViewMatrix = GLKMatrix4Rotate(modelViewMatrix, GLKMathDegreesToRadians(25), 1, 0, 0);
- modelViewMatrix = GLKMatrix4Rotate(modelViewMatrix, GLKMathDegreesToRadians(_rotation), 0, 1, 0);
- self.effect.transform.modelviewMatrix = modelViewMatrix;
- }
- # pragma mark - Create and render Drawable functions
- - (Drawable)createDrawable: (NSString *)objFileName {
- NSError * error;
- // Get obj contents.
- NSArray *objFile = [objFileName componentsSeparatedByString:@"."];
- NSString *name = [objFile objectAtIndex:0];
- NSString *extension = [objFile objectAtIndex:1];
- NSString *objFilePath = [[NSBundle mainBundle] pathForResource:name ofType:extension];
- NSString *objFileContents = [[NSString alloc] init];
- objFileContents = [NSString stringWithContentsOfFile:objFilePath encoding: NSASCIIStringEncoding error: &error];
- if (objFileContents == nil) {
- NSLog(@"Error loading file %@.obj: %@", name, [error localizedDescription]);
- }
- NSArray *individualLinesInObj = [objFileContents componentsSeparatedByString:@"\n"];
- // Specifications/arrays of individual things for this object. The array for
- // faces can (and will) be directly used for the indexbuffer. For the
- // vertexbuffer we'll need another array that will hold all three vertices,
- // texture uvs and normals togather.
- int numVerts = 0;
- int numTex = 0;
- int numNormals = 0;
- int numFaces = 0;
- float *vertices;
- float *tex;
- float *normals;
- uint *indices;
- // We will be returning this Drawable.
- Drawable _drawable;
- // Get specifications (i.e. # of everything).
- for(NSString *line in individualLinesInObj) {
- if([line hasPrefix:@"v "])
- numVerts++;
- else if([line hasPrefix:@"vt "])
- numTex++;
- else if([line hasPrefix:@"vn "])
- numNormals++;
- else if([line hasPrefix:@"f "])
- numFaces++;
- }
- // Initialize object arrays with values from the obj file.
- vertices = malloc(sizeof(GL_FLOAT) * numVerts * 3); // x, y, z: 3 values per vertex.
- tex = malloc(sizeof(GL_FLOAT) * numTex * 2); // u, v: 2 values per texture point.
- normals = malloc(sizeof(GL_FLOAT) * numNormals * 3); // nx, ny, nz: 3 values per normal.
- indices = malloc(sizeof(GL_UNSIGNED_INT) * numFaces * 3);// 3 vertices per (triangle) face.
- // Copy obj file data to arrays. v, n, t, f: counters.
- int v = 0;
- int t = 0;
- int n = 0;
- int f = 0;
- for(NSString *line in individualLinesInObj) {
- if([line hasPrefix:@"v "]) {
- NSArray *tempV = [line componentsSeparatedByString:@" "];
- // The first string is the prefix 'v', which we are to ignore.
- BOOL prefixPassed = NO;
- for(NSString *tempString in tempV) {
- if(prefixPassed) {
- vertices[v] = [tempString floatValue];
- v++;
- }
- else {
- prefixPassed = YES;
- }
- }
- }
- else if([line hasPrefix:@"vt "]) {
- NSArray *tempT = [line componentsSeparatedByString:@" "];
- // The first string is the prefix 'vt', which we are to ignore.
- BOOL prefixPassed = NO;
- for(NSString *tempString in tempT) {
- if(prefixPassed) {
- tex[t] = [tempString floatValue];
- t++;
- }
- else {
- prefixPassed = YES;
- }
- }
- }
- else if([line hasPrefix:@"vn "]) {
- NSArray *tempN = [line componentsSeparatedByString:@" "];
- // The first string is the prefix 'vn', which we are to ignore.
- BOOL prefixPassed = NO;
- for(NSString *tempString in tempN) {
- if(prefixPassed) {
- normals[n] = [tempString floatValue];
- n++;
- }
- else {
- prefixPassed = YES;
- }
- }
- }
- else if([line hasPrefix:@"f "]) {
- NSArray *tempF = [line componentsSeparatedByString:@" "];
- // The first string is the prefix 'f', which we are to ignore.
- BOOL prefixPassed = NO;
- for(NSString *tempString in tempF) {
- int iTemp[3] = {0, 0, 0};
- NSArray *singleFaceData = [tempString componentsSeparatedByString:@" "];
- for(NSString *singleVertexData in singleFaceData) {
- if(prefixPassed) {
- // Break this vertex's data into V#, T# and N#. For now,
- // we need only vertex number.
- NSArray *brokenVertex = [singleVertexData componentsSeparatedByString:@"/"];
- int i = 0;
- for(NSString *vertexNumber in brokenVertex) {
- iTemp[i] = [vertexNumber intValue] - 1;
- i++;
- }
- indices[f] = iTemp[0];
- f++;
- }
- else {
- prefixPassed = YES;
- }
- }
- }
- }
- }
- // Create an array for vertex data. This array will contain 3 vertex data
- // sets, each having 8 float values for each vertex. Something like:
- // (Vx, Vy, Vz, u, v, Nx, Ny, Nz).
- // This ordering will come from the indexbuffer (*faces array). An indexbuffer
- // triplet a/b/c means a-th vertex, b-th uv and in the .obj file.
- GLfloat *vertexData = malloc(sizeof(GL_FLOAT) * (3 + 2 + 3) * numFaces * 3);
- int vdCount = 0;
- for(NSString *line in individualLinesInObj) {
- if([line hasPrefix:@"f "]) {
- NSArray *tempF = [line componentsSeparatedByString:@" "];
- // The first string is the prefix 'f', which we are to ignore.
- BOOL prefixPassed = NO;
- for(NSString *tempString in tempF) {
- NSArray *singleFaceData = [tempString componentsSeparatedByString:@" "];
- for(NSString *singleVertexData in singleFaceData) {
- if(prefixPassed) {
- // Break this vertex's data into V#, T# and N#.
- NSArray *brokenVertex = [singleVertexData componentsSeparatedByString:@"/"];
- int i = 0;
- int iTemp[3] = {0, 0, 0};
- for(NSString *string in brokenVertex) {
- iTemp[i] = [string intValue];
- iTemp[i] -= 1;
- i++;
- }
- // Copy data into vertex-array (not vertexarray) from
- // vertices, texture (uvs) and normals.
- // vertices
- vertexData[vdCount + 0] = vertices[iTemp[0] * 3 + 0];
- vertexData[vdCount + 1] = vertices[iTemp[0] * 3 + 1];
- vertexData[vdCount + 2] = vertices[iTemp[0] * 3 + 2];
- // texture
- vertexData[vdCount + 3] = tex[iTemp[1] * 3 + 0];
- vertexData[vdCount + 4] = tex[iTemp[1] * 3 + 1];
- // normals
- vertexData[vdCount + 5] = normals[iTemp[2] * 3 + 0];
- vertexData[vdCount + 6] = normals[iTemp[2] * 3 + 1];
- vertexData[vdCount + 7] = normals[iTemp[2] * 3 + 2];
- // increment vertex count
- vdCount += 8;
- }
- else {
- prefixPassed = YES;
- }
- }
- }
- }
- }
- _drawable.numFaces = numFaces;
- glGenBuffers(1, &_drawable.vertexBuffer);
- glBindBuffer(GL_ARRAY_BUFFER, _drawable.vertexBuffer);
- glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData) * numFaces * 8, vertexData, GL_STATIC_DRAW);
- glGenBuffers(1, &_drawable.indexBuffer);
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _drawable.indexBuffer);
- glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices) * numFaces * 3, indices, GL_STATIC_DRAW);
- _drawable.matrix = GLKMatrix4Identity;
- //_drawable.matrix = GLKMatrix4Scale(_drawable.matrix, 5.0f, 5.0f, 5.0f);
- _drawable.matrix = GLKMatrix4Translate(_drawable.matrix, 0.0f, 0.0f, 10.0f);
- return _drawable;
- }
- - (void) renderDrawable: (Drawable)object {
- glBindBuffer(GL_ARRAY_BUFFER, object.vertexBuffer);
- glEnableVertexAttribArray(GLKVertexAttribPosition);
- glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, 0, (const GLvoid *) 0);
- glEnableVertexAttribArray(GLKVertexAttribTexCoord1);
- glVertexAttribPointer(GLKVertexAttribTexCoord1, 2, GL_FLOAT, GL_FALSE, 0, (const GLvoid *) 3);
- glEnableVertexAttribArray(GLKVertexAttribNormal);
- glVertexAttribPointer(GLKVertexAttribNormal, 3, GL_FLOAT, GL_FALSE, 0, (const GLvoid *) 5);
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, object.indexBuffer);
- glDrawElements(GL_LINES, sizeof(object.indexBuffer) * 3 * object.numFaces, GL_UNSIGNED_BYTE, (const GLvoid *) object.indexBuffer);
- }
- # pragma mark - Touch events
- - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
- self.paused = !self.paused;
- NSLog(@"timeSinceLastUpdate: %f", self.timeSinceLastUpdate);
- NSLog(@"timeSinceLastDraw: %f", self.timeSinceLastDraw);
- NSLog(@"timeSinceFirstResume: %f", self.timeSinceFirstResume);
- NSLog(@"timeSinceLastResume: %f", self.timeSinceLastResume);
- }
- - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
- }
- - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
- }
- - (void) touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
- }
- @end
Advertisement
Add Comment
Please, Sign In to add comment