Форум программистов, компьютерный форум, киберфорум
OpenGL
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.60/5: Рейтинг темы: голосов - 5, средняя оценка - 4.60
0 / 0 / 0
Регистрация: 20.03.2013
Сообщений: 208
1

Создание объектов

20.03.2013, 16:42. Показов 970. Ответов 4
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Доброго времени суток! Я создал куб в пространстве, хочу рядом создать такой же куб рядом с ним. Как я понимаю, для этого нужно создать ещё один вершинный и один индексный массив + создать 2 буфера для них. Но когда я это делаю, на экране появляется второй куб, а первый исчезает. Видимо, что-то ещё нужно добавить? Вот код:

C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
#define VERTEX_SHADER @"vertex"
#define FRAGMENT_SHADER @"fragment"
 
typedef struct
{
    char* Name;
    GLint Location;
}Uniform;
 
GLfloat Cube2VertexData[72] =
{
    // right
    0.5f, -0.5f, 0.5f,
    0.5f,  0.5f, 0.5f,
    0.5f,  0.5f,  1.5f,
    0.5f, -0.5f,  1.5f,
    
    // top
    0.5f,  0.5f, 0.5f,
    -0.5f,  0.5f, 0.5f,
    -0.5f,  0.5f,  1.5f,
    0.5f,  0.5f,  1.5f,
    
    // left
    -0.5f,  0.5f, 0.5f,
    -0.5f, -0.5f, 0.5f,
    -0.5f, -0.5f,  1.5f,
    -0.5f,  0.5f,  1.5f,
    
    // bottom
    -0.5f, -0.5f, 0.5f,
    0.5f, -0.5f, 0.5f,
    0.5f, -0.5f,  1.5f,
    -0.5f, -0.5f,  1.5f,
    
    // front
    0.5f,  0.5f,  1.5f,
    -0.5f,  0.5f,  1.5f,
    -0.5f, -0.5f,  1.5f,
    0.5f, -0.5f,  1.5f,
    
    // back
    0.5f,  0.5f, 0.5f,
    0.5f, -0.5f, 0.5f,
    -0.5f, -0.5f, 0.5f,
    -0.5f,  0.5f, 0.5f,
};
 
GLuint Cube2IndicesData[36] =
{
    // right
    0, 1, 2,        2, 3, 0,
    // top
    4, 5, 6,        6, 7, 4,
    // left
    8, 9, 10,       10, 11, 8,
    // bottom
    12, 13, 14,     14, 15, 12,
    
    // front
    16, 17, 18,     18, 19, 16,
    // back
    20, 21, 22,     22, 23, 20
};
 
 
GLfloat CubeVertexData[72] =
{
    // right
    0.5f, -0.5f, -0.5f,
    0.5f,  0.5f, -0.5f,
    0.5f,  0.5f,  0.5f,
    0.5f, -0.5f,  0.5f,
    
    // top
    0.5f,  0.5f, -0.5f,
    -0.5f,  0.5f, -0.5f,
    -0.5f,  0.5f,  0.5f,
    0.5f,  0.5f,  0.5f,
    
    // left
    -0.5f,  0.5f, -0.5f,
    -0.5f, -0.5f, -0.5f,
    -0.5f, -0.5f,  0.5f,
    -0.5f,  0.5f,  0.5f,
    
    // bottom
    -0.5f, -0.5f, -0.5f,
    0.5f, -0.5f, -0.5f,
    0.5f, -0.5f,  0.5f,
    -0.5f, -0.5f,  0.5f,
    
    // front
    0.5f,  0.5f,  0.5f,
    -0.5f,  0.5f,  0.5f,
    -0.5f, -0.5f,  0.5f,
    0.5f, -0.5f,  0.5f,
    
    // back
    0.5f,  0.5f, -0.5f,
    0.5f, -0.5f, -0.5f,
    -0.5f, -0.5f, -0.5f,
    -0.5f,  0.5f, -0.5f,
};
 
GLuint CubeIndicesData[36] =
{
    // right
    0, 1, 2,        2, 3, 0,
    // top
    4, 5, 6,        6, 7, 4,
    // left
    8, 9, 10,       10, 11, 8,
    // bottom
    12, 13, 14,     14, 15, 12,
    
    // front
    16, 17, 18,     18, 19, 16,
    // back
    20, 21, 22,     22, 23, 20
};
 
@interface ViewController () {
 
    GLuint _program;    
    GLint _uniformArraySize;
    
    Uniform *_uniformArray;
    
    GLuint _verticesVBO;
    GLuint _indicesVBO;
    GLuint _VAO;
    
    GLuint _verticesVBO2;
    GLuint _indicesVBO2;
 
    GLKMatrix4 _projectionMatrix;
    GLKMatrix4 _modelViewMatrix;
 
}
@end
 
 
@implementation ViewController
 
- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect
{
    // Clear the screen
    glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
    glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
    
    // Bind the VAO and the program
    glBindVertexArrayOES( _VAO );
    glUseProgram( _program );
    
    for (int i = 0; i < _uniformArraySize; i++) {
        if (!strcmp(_uniformArray[i].Name, "ModelViewProjectionMatrix"))
        {
            // Multiply the transformation matrices together
            GLKMatrix4 modelViewProjectionMatrix = GLKMatrix4Multiply(_projectionMatrix, _modelViewMatrix);
            glUniformMatrix4fv(_uniformArray[i].Location, 1, GL_FALSE, modelViewProjectionMatrix.m);
        }
    }
    
    // Draw!
    glDrawElements( GL_TRIANGLES, sizeof(CubeIndicesData)/sizeof(GLuint), GL_UNSIGNED_INT, NULL );
    glDrawElements( GL_TRIANGLES, sizeof(Cube2IndicesData)/sizeof(GLuint), GL_UNSIGNED_INT, NULL );
 
}
 
- (void)update
{
    _modelViewMatrix = GLKMatrix4RotateY(_modelViewMatrix, 0.2); 
}
 
- (GLuint)compileShader:(NSString*)shaderName withType:(GLenum)shaderType
{
    // Load the shader in memory
    NSString *shaderPath = [[NSBundle mainBundle] pathForResource:shaderName ofType:@"glsl"];
    NSError *error;
    NSString *shaderString = [NSString stringWithContentsOfFile:shaderPath encoding:NSUTF8StringEncoding error:&error];
    if(!shaderString)
    {
        NSLog(@"Error loading shader: %@", error.localizedDescription);
        exit(1);
    }
    
    // Create the shader inside openGL
    GLuint shaderHandle = glCreateShader(shaderType);
    
    // Give that shader the source code loaded in memory
    const char *shaderStringUTF8 = [shaderString UTF8String];
    int shaderStringLength = [shaderString length];
    glShaderSource(shaderHandle, 1, &shaderStringUTF8, &shaderStringLength);
    
    // Compile the source code
    glCompileShader(shaderHandle);
    
    // Get the error messages in case the compiling has failed
    GLint compileSuccess;
    glGetShaderiv(shaderHandle, GL_COMPILE_STATUS, &compileSuccess);
    if (compileSuccess == GL_FALSE) {
        GLint logLength;
        glGetShaderiv(shaderHandle, GL_INFO_LOG_LENGTH, &logLength);
        if(logLength > 0)
        {
            GLchar *log = (GLchar *)malloc(logLength);
            glGetShaderInfoLog(shaderHandle, logLength, &logLength, log);
            NSLog(@"Shader compile log:\n%s", log);
            free(log);
        }
        exit(1);
    }
    
    return shaderHandle;
}
 
-(void)createProgram
{
    // Compile both shaders
    GLuint vertexShader = [self compileShader:VERTEX_SHADER withType:GL_VERTEX_SHADER];
    GLuint fragmentShader = [self compileShader:FRAGMENT_SHADER withType:GL_FRAGMENT_SHADER];
    
    // Create the program in openGL, attach the shaders and link them
    GLuint programHandle = glCreateProgram();
    glAttachShader(programHandle, vertexShader);
    glAttachShader(programHandle, fragmentShader);
    glLinkProgram(programHandle);
    
    // Get the error message in case the linking has failed
    GLint linkSuccess;
    glGetProgramiv(programHandle, GL_LINK_STATUS, &linkSuccess);
    if (linkSuccess == GL_FALSE)
    {
        GLint logLength;
        glGetProgramiv(programHandle, GL_INFO_LOG_LENGTH, &logLength);
        if(logLength > 0)
        {
            GLchar *log = (GLchar *)malloc(logLength);
            glGetProgramInfoLog(programHandle, logLength, &logLength, log);
            NSLog(@"Program link log:\n%s", log);
            free(log);
        }
        exit(1);
    }
    
    _program = programHandle;
}
 
-(void)getUniforms
{
    GLint maxUniformLength;
    GLint numberOfUniforms;
    char *uniformName;
    
    // Get the number of uniforms and the max length of their names
    glGetProgramiv(_program, GL_ACTIVE_UNIFORMS, &numberOfUniforms);
    glGetProgramiv(_program, GL_ACTIVE_UNIFORM_MAX_LENGTH, &maxUniformLength);
 
    _uniformArray = malloc(numberOfUniforms * sizeof(Uniform));
    _uniformArraySize = numberOfUniforms;
 
    for(int i = 0; i < numberOfUniforms; i++)
    {
        GLint size;
        GLenum type;
        GLint location;
        // Get the Uniform Info
        uniformName = malloc(sizeof(char) * maxUniformLength);
        glGetActiveUniform(_program, i, maxUniformLength, NULL, &size, &type, uniformName);
        _uniformArray[i].Name = uniformName;
        // Get the uniform location
        location = glGetUniformLocation(_program, uniformName);
        _uniformArray[i].Location = location;
    }
}
 
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Create context
    self.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
    if (!self.context) {
        NSLog(@"Failed to create ES context");
        exit(1);
    }
    
    if (![EAGLContext setCurrentContext:self.context])
    {
        NSLog(@"Failed to set current OpenGL context");
        exit(1);
    }
    
    // Initialize view
    GLKView *view = (GLKView *)self.view;
  view.context = self.context;
    
    // Change the format of the depth renderbuffer
    // This value is None by default
    view.drawableDepthFormat = GLKViewDrawableDepthFormat16;
    
    // Enable face culling and depth test
    glEnable( GL_DEPTH_TEST );
    glEnable( GL_CULL_FACE  );
    
    // Set up the viewport
    int width = view.bounds.size.width;
    int height = view.bounds.size.height;
    glViewport(0, 0, width, height);
    
    [self createProgram];
    [self getUniforms];
        
 
    
    // Make the vertex buffer
    glGenBuffers( 1, &_verticesVBO );
    glBindBuffer( GL_ARRAY_BUFFER, _verticesVBO );
    glBufferData( GL_ARRAY_BUFFER, sizeof(CubeVertexData), CubeVertexData, GL_STATIC_DRAW );
    glBindBuffer( GL_ARRAY_BUFFER, 0 );
    
    // Make the indices buffer
    glGenBuffers( 1, &_indicesVBO );
    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, _indicesVBO );
    glBufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof(CubeIndicesData), CubeIndicesData, GL_STATIC_DRAW );
  glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
    
    
    // Make the indices buffer2
    glGenBuffers( 1, &_indicesVBO2 );
    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, _indicesVBO2 );
    glBufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof(Cube2IndicesData), Cube2IndicesData, GL_STATIC_DRAW );
    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
    
    
    // Make the vertex buffer2
    glGenBuffers( 1, &_verticesVBO2 );
    glBindBuffer( GL_ARRAY_BUFFER, _verticesVBO2 );
    glBufferData( GL_ARRAY_BUFFER, sizeof(Cube2VertexData), Cube2VertexData, GL_STATIC_DRAW );
    glBindBuffer( GL_ARRAY_BUFFER, 0 );
    
    
    // Bind the attribute pointers to the VAO
    GLint attribute;
    GLsizei stride = sizeof(GLfloat) * 3;
    glGenVertexArraysOES( 1, &_VAO );
    glBindVertexArrayOES( _VAO );
    
    glBindBuffer( GL_ARRAY_BUFFER, _verticesVBO );
    glBindBuffer( GL_ARRAY_BUFFER, _verticesVBO2 );
 
    attribute = glGetAttribLocation(_program, "Position");
    glEnableVertexAttribArray( attribute );
    glVertexAttribPointer( attribute, 3, GL_FLOAT, GL_FALSE, stride, NULL );
    
    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, _indicesVBO );
    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, _indicesVBO2 );
 
    glBindVertexArrayOES( 0 );
    
    _modelViewMatrix = GLKMatrix4MakeLookAt(2.0f, 2.0f, 4.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);
    _projectionMatrix = GLKMatrix4MakePerspective(45.0f, (float)width/(float)height, 0.01f, 100.0f);
    
}
 
- (void)viewDidUnload
{
    [super viewDidUnload];
    
    [EAGLContext setCurrentContext:self.context];
    
    glDeleteBuffers(1, &_verticesVBO);
    glDeleteBuffers(1, &_indicesVBO);
    glDeleteVertexArraysOES(1, &_VAO);
    
    if (_program) {
        glDeleteProgram(_program);
        _program = 0;
    }
    
    for (int i = 0; i < _uniformArraySize; i++) {
        free(_uniformArray[i].Name);
    }
    free(_uniformArray);
}
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
20.03.2013, 16:42
Ответы с готовыми решениями:

Создание теней для объектов в OpenGL
Прошу помочь или хотя бы подсказать. Во вложении программа, которая рисует комнату с зеркалом...

Выбор объектов возвращает слишком много объектов
Делаю выбор объекта. Рисую объекты: ... GL.InitNames() ... Dim temp As Integer temp = 1...

Создание списка объектов класса с заранее неизвестным именем (именем самих объектов)
Уважаемые программисты, не получается решить такую задачу: требуется создать приложение (в консоли)...

Создание кода из строк или создание произвольного количества объектов
Привет сообществу. Возник такой вопрос: Мне в мидлете необходимо создать некоторое количество...

4
2 / 2 / 0
Регистрация: 24.02.2013
Сообщений: 62
20.03.2013, 20:25 2
Если это "куб", то у него все стороны равны. Тогда зачем тратить память и создавать 2 массив? Просто рендери куб в разных местах сцены.

P.S. Очень много кода. Лень разбираться. Там его можно на половину как минимум сократить.
1
0 / 0 / 0
Регистрация: 20.03.2013
Сообщений: 208
21.03.2013, 09:25  [ТС] 3
Цитата Сообщение от Nikkilla Посмотреть сообщение
Просто рендери куб в разных местах сцены.
А как это сделать, можете подсказать? Когда я убираю второй массив, то куб исчезает.
0
Модератор
3388 / 2160 / 352
Регистрация: 13.01.2012
Сообщений: 8,378
21.03.2013, 11:07 4
может вы куб и строите по второму массиву? уберите первый как рендерить в разных местах? сделать функцию "рендерить куб". вызвать раз. сделать транслейт. вызвать два.
1
0 / 0 / 0
Регистрация: 20.03.2013
Сообщений: 208
21.03.2013, 11:13  [ТС] 5
Упростил код (убрал массив индексов) и добавил второй куб. У меня такой вопрос , я правильно понимаю, что для каждого куба нужен отдельный VBO и отдельный VAO? Вот код того, что получилось :
C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
#import "ViewController.h"
 
#define VERTEX_SHADER @"vertex"
#define FRAGMENT_SHADER @"fragment"
 
typedef struct
{
    char* Name;
    GLint Location;
}Uniform;
 
GLfloat CubeVertexData[72] =
{
    // right
    0.5f, -0.5f, -0.5f,
    0.5f,  0.5f, -0.5f,
    0.5f,  0.5f,  0.5f,
    0.5f, -0.5f,  0.5f,
    
    // top
    0.5f,  0.5f, -0.5f,
    -0.5f,  0.5f, -0.5f,
    -0.5f,  0.5f,  0.5f,
    0.5f,  0.5f,  0.5f,
    
    // left
    -0.5f,  0.5f, -0.5f,
    -0.5f, -0.5f, -0.5f,
    -0.5f, -0.5f,  0.5f,
    -0.5f,  0.5f,  0.5f,
    
    // bottom
    -0.5f, -0.5f, -0.5f,
    0.5f, -0.5f, -0.5f,
    0.5f, -0.5f,  0.5f,
    -0.5f, -0.5f,  0.5f,
    
    // front
    0.5f,  0.5f,  0.5f,
    -0.5f,  0.5f,  0.5f,
    -0.5f, -0.5f,  0.5f,
    0.5f, -0.5f,  0.5f,
    
    // back
    0.5f,  0.5f, -0.5f,
    0.5f, -0.5f, -0.5f,
    -0.5f, -0.5f, -0.5f,
    -0.5f,  0.5f, -0.5f,
};
 
GLfloat Cube2VertexData[72] =
{
    // right
    0.5f, -0.5f, 0.5f,
    0.5f,  0.5f, 0.5f,
    0.5f,  0.5f,  1.5f,
    0.5f, -0.5f,  1.5f,
    
    // top
    0.5f,  0.5f, 0.5f,
    -0.5f,  0.5f, 0.5f,
    -0.5f,  0.5f,  1.5f,
    0.5f,  0.5f,  1.5f,
    
    // left
    -0.5f,  0.5f, 0.5f,
    -0.5f, -0.5f, 0.5f,
    -0.5f, -0.5f,  1.5f,
    -0.5f,  0.5f,  1.5f,
    
    // bottom
    -0.5f, -0.5f, 0.5f,
    0.5f, -0.5f, 0.5f,
    0.5f, -0.5f,  1.5f,
    -0.5f, -0.5f,  1.5f,
    
    // front
    0.5f,  0.5f,  1.5f,
    -0.5f,  0.5f,  1.5f,
    -0.5f, -0.5f,  1.5f,
    0.5f, -0.5f,  1.5f,
    
    // back
    0.5f,  0.5f, 0.5f,
    0.5f, -0.5f, 0.5f,
    -0.5f, -0.5f, 0.5f,
    -0.5f,  0.5f, 0.5f,
};
 
 
 
@interface ViewController () {
 
    GLuint _program;    
    GLint _uniformArraySize;
    
    Uniform *_uniformArray;
    
    GLuint _verticesVBO;
    GLuint _verticesVBO2;
 
    GLuint _VAO;
    GLuint _VAO2;
 
    GLKMatrix4 _projectionMatrix;
    GLKMatrix4 _modelViewMatrix;
 
}
 
 
 
 
@end
 
@implementation ViewController
 
- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect
{
    // Clear the screen
    glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
    glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
    
    for (int i = 0; i < _uniformArraySize; i++) {
        if (!strcmp(_uniformArray[i].Name, "ModelViewProjectionMatrix")) {
            // Multiply the transformation matrices together
            GLKMatrix4 modelViewProjectionMatrix = GLKMatrix4Multiply(_projectionMatrix, _modelViewMatrix);
            glUniformMatrix4fv(_uniformArray[i].Location, 1, GL_FALSE, modelViewProjectionMatrix.m);
        }
    }
    
    glUseProgram( _program );
 
    
    // Bind the VAO and the program
    glBindVertexArrayOES( _verticesVBO );
    
    // Draw!
    glDrawArrays(GL_LINE_LOOP, 0, 36);
 
    
    // Bind the VAO2 and the program
    glBindVertexArrayOES( _verticesVBO2 );
 
        // Draw!
    glDrawArrays(GL_LINE_LOOP, 0, 36);
        
}
 
- (void)update
{
    _modelViewMatrix = GLKMatrix4RotateY(_modelViewMatrix, 0.02);
}
 
- (GLuint)compileShader:(NSString*)shaderName withType:(GLenum)shaderType
{
    // Load the shader in memory
    NSString *shaderPath = [[NSBundle mainBundle] pathForResource:shaderName ofType:@"glsl"];
    NSError *error;
    NSString *shaderString = [NSString stringWithContentsOfFile:shaderPath encoding:NSUTF8StringEncoding error:&error];
    if(!shaderString)
    {
        NSLog(@"Error loading shader: %@", error.localizedDescription);
        exit(1);
    }
    
    // Create the shader inside openGL
    GLuint shaderHandle = glCreateShader(shaderType);
    
    // Give that shader the source code loaded in memory
    const char *shaderStringUTF8 = [shaderString UTF8String];
    int shaderStringLength = [shaderString length];
    glShaderSource(shaderHandle, 1, &shaderStringUTF8, &shaderStringLength);
    
    // Compile the source code
    glCompileShader(shaderHandle);
    
    // Get the error messages in case the compiling has failed
    GLint compileSuccess;
    glGetShaderiv(shaderHandle, GL_COMPILE_STATUS, &compileSuccess);
    if (compileSuccess == GL_FALSE) {
        GLint logLength;
        glGetShaderiv(shaderHandle, GL_INFO_LOG_LENGTH, &logLength);
        if(logLength > 0)
        {
            GLchar *log = (GLchar *)malloc(logLength);
            glGetShaderInfoLog(shaderHandle, logLength, &logLength, log);
            NSLog(@"Shader compile log:\n%s", log);
            free(log);
        }
        exit(1);
    }
    
    return shaderHandle;
}
 
-(void)createProgram
{
    // Compile both shaders
    GLuint vertexShader = [self compileShader:VERTEX_SHADER withType:GL_VERTEX_SHADER];
    GLuint fragmentShader = [self compileShader:FRAGMENT_SHADER withType:GL_FRAGMENT_SHADER];
    
    // Create the program in openGL, attach the shaders and link them
    GLuint programHandle = glCreateProgram();
    glAttachShader(programHandle, vertexShader);
    glAttachShader(programHandle, fragmentShader);
    glLinkProgram(programHandle);
    
    // Get the error message in case the linking has failed
    GLint linkSuccess;
    glGetProgramiv(programHandle, GL_LINK_STATUS, &linkSuccess);
    if (linkSuccess == GL_FALSE)
    {
        GLint logLength;
        glGetProgramiv(programHandle, GL_INFO_LOG_LENGTH, &logLength);
        if(logLength > 0)
        {
            GLchar *log = (GLchar *)malloc(logLength);
            glGetProgramInfoLog(programHandle, logLength, &logLength, log);
            NSLog(@"Program link log:\n%s", log);
            free(log);
        }
        exit(1);
    }
    
    _program = programHandle;
}
 
-(void)getUniforms
{
    GLint maxUniformLength;
    GLint numberOfUniforms;
    char *uniformName;
    
    // Get the number of uniforms and the max length of their names
    glGetProgramiv(_program, GL_ACTIVE_UNIFORMS, &numberOfUniforms);
    glGetProgramiv(_program, GL_ACTIVE_UNIFORM_MAX_LENGTH, &maxUniformLength);
 
    _uniformArray = malloc(numberOfUniforms * sizeof(Uniform));
    _uniformArraySize = numberOfUniforms;
 
    for(int i = 0; i < numberOfUniforms; i++)
    {
        GLint size;
        GLenum type;
        GLint location;
        // Get the Uniform Info
        uniformName = malloc(sizeof(char) * maxUniformLength);
        glGetActiveUniform(_program, i, maxUniformLength, NULL, &size, &type, uniformName);
        _uniformArray[i].Name = uniformName;
        // Get the uniform location
        location = glGetUniformLocation(_program, uniformName);
        _uniformArray[i].Location = location;
    }
}
 
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Create context
    self.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
    if (!self.context) {
        NSLog(@"Failed to create ES context");
        exit(1);
    }
    
    if (![EAGLContext setCurrentContext:self.context])
    {
        NSLog(@"Failed to set current OpenGL context");
        exit(1);
    }
    
    // Initialize view
    GLKView *view = (GLKView *)self.view;
  view.context = self.context;
    
    // Change the format of the depth renderbuffer
    // This value is None by default
    view.drawableDepthFormat = GLKViewDrawableDepthFormat16;
    
    // Enable face culling and depth test
    glEnable( GL_DEPTH_TEST );
    glEnable( GL_CULL_FACE  );
    
    // Set up the viewport
    int width = view.bounds.size.width;
    int height = view.bounds.size.height;
    glViewport(0, 0, width, height);
    
    [self createProgram];
    [self getUniforms];
    
    
    // Make the vertex buffer
    glGenBuffers( 1, &_verticesVBO );
    glBindBuffer( GL_ARRAY_BUFFER, _verticesVBO );
    glBufferData( GL_ARRAY_BUFFER, sizeof(CubeVertexData), CubeVertexData, GL_STATIC_DRAW );
    glBindBuffer( GL_ARRAY_BUFFER, 0 );
    
    // Make the vertex buffer2
    glGenBuffers( 1, &_verticesVBO2 );
    glBindBuffer( GL_ARRAY_BUFFER, _verticesVBO2 );
    glBufferData( GL_ARRAY_BUFFER, sizeof(Cube2VertexData), Cube2VertexData, GL_STATIC_DRAW );
    glBindBuffer( GL_ARRAY_BUFFER, 0 );
    
    
    // Bind the attribute pointers to the VAO
    GLint attribute;
    GLsizei stride = sizeof(GLfloat) * 3;
    glGenVertexArraysOES( 1, &_VAO );
    glBindVertexArrayOES( _VAO );
    
    glBindBuffer( GL_ARRAY_BUFFER, _verticesVBO );
 
    attribute = glGetAttribLocation(_program, "Position");
    glEnableVertexAttribArray( attribute );
    glVertexAttribPointer( attribute, 3, GL_FLOAT, GL_FALSE, stride, NULL );
    glBindVertexArrayOES( 0 );
    
    
    
    // Bind the attribute pointers to the VAO2
    GLint attribute2;
    GLsizei stride2 = sizeof(GLfloat) * 3;
    glGenVertexArraysOES( 1, &_VAO2 );
    glBindVertexArrayOES( _VAO2 );
    
    glBindBuffer( GL_ARRAY_BUFFER, _verticesVBO2 );
    
    attribute2 = glGetAttribLocation(_program, "Position");
    glEnableVertexAttribArray( attribute2 );
    glVertexAttribPointer( attribute2, 3, GL_FLOAT, GL_FALSE, stride2, NULL );
    glBindVertexArrayOES( 0 );
 
    
    
    _modelViewMatrix = GLKMatrix4MakeLookAt(2.0f, 2.0f, 4.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);
    _projectionMatrix = GLKMatrix4MakePerspective(45.0f, (float)width/(float)height, 0.01f, 100.0f);
 
}
 
- (void)viewDidUnload
{
    [super viewDidUnload];
    
    [EAGLContext setCurrentContext:self.context];
    
    glDeleteBuffers(1, &_verticesVBO);
    glDeleteVertexArraysOES(1, &_VAO);
    
    glDeleteBuffers(1, &_verticesVBO2);
    glDeleteVertexArraysOES(1, &_VAO2);
    
    
    if (_program) {
        glDeleteProgram(_program);
        _program = 0;
    }
    
    for (int i = 0; i < _uniformArraySize; i++) {
        free(_uniformArray[i].Name);
    }
    free(_uniformArray);
}
0
21.03.2013, 11:13
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
21.03.2013, 11:13
Помогаю со студенческими работами здесь

Создание объектов
Допустим есть код: interface IShape { color: string; } interface IPenStroke { ...

Создание объектов
Здравствуйте.Случайно в интернете наткнулся на такую вот штуку(пример): public class...

Создание объектов JS
Наткнулся на создание объекта с помощью конструктора (function): var new_obj = new function(){ ...

Создание объектов
Здравствуйте. Каким образом можно это реализовать? Возьмем простую форму пустого проекта. Положим...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
5
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru