Подтвердить что ты не робот

Объект буферизации вершинного буфера OpenGL ES

Я смотрел новую фреймворк OpenGL для iOS, точно названный GLKit, и играл с переносом некоторого существующего кода OpenGL 1.0 на OpenGL ES 2.0, чтобы окунуть мой палец в воду и справиться с вещами.

После прочтения API и целого ряда других лучших практик, предоставленных Apple и документации OpenGL, у меня было довольно укоренилось в меня, что я должен использовать Vertex Buffer Objects и использовать "элементы" или, вернее, вершину индексы. Похоже, что есть много упоминаний об оптимизации хранения памяти с помощью дополнения, когда это необходимо, но что разговор на другой день возможно;)

I прочитал о SO некоторое время назад о преимуществах использования NSMutableData над классическим malloc/free и хотел попробовать и принять этот подход при написании моего VBO. Пока мне удалось объединить фрагмент, похожий на то, что я направляюсь по правильному пути, но я не совсем уверен, сколько данных должен содержать VBO. Вот что у меня до сих пор:

//import headers
#import <GLKit/GLKit.h>

#pragma mark -
#pragma mark InterleavingVertexData

//vertex buffer object struct
struct InterleavingVertexData
{
    //vertices
    GLKVector3 vertices;

    //normals
    GLKVector3 normal;

    //color
    GLKVector4 color;

    //texture coordinates
    GLKVector2 texture;
};
typedef struct InterleavingVertexData InterleavingVertexData;

#pragma mark -
#pragma mark VertexIndices

//vertex indices struct
struct VertexIndices
{
    //vertex indices
    GLuint a;
    GLuint b;
    GLuint c;
};
typedef struct VertexIndices VertexIndices;

//create and return a vertex index with specified indices
static inline VertexIndices VertexIndicesMake(GLuint a, GLuint b, GLuint c)
{
    //declare vertex indices
    VertexIndices vertexIndices;

    //set indices
    vertexIndices.a = a;
    vertexIndices.b = b;
    vertexIndices.c = c;

    //return vertex indices
    return vertexIndices;
}

#pragma mark -
#pragma mark VertexBuffer

//vertex buffer struct
struct VertexBuffer
{
    //vertex data
    NSMutableData *vertexData;

    //vertex indices
    NSMutableData *indices;

    //total number of vertices
    NSUInteger totalVertices;

    //total number of indices
    NSUInteger totalIndices;
};
typedef struct VertexBuffer VertexBuffer;

//create and return a vertex buffer with allocated data
static inline VertexBuffer VertexBufferMake(NSUInteger totalVertices, NSUInteger totalIndices)
{
    //declare vertex buffer
    VertexBuffer vertexBuffer;

    //set vertices and indices count
    vertexBuffer.totalVertices = totalVertices;
    vertexBuffer.totalIndices = totalIndices;

    //set vertex data and indices
    vertexBuffer.vertexData = nil;
    vertexBuffer.indices = nil;

    //check vertices count
    if(totalVertices > 0)
    {
        //allocate data
        vertexBuffer.vertexData = [[NSMutableData alloc] initWithLength:(sizeof(InterleavingVertexData) * totalVertices)];
    }

    //check indices count
    if(totalIndices > 0)
    {
        //allocate data
        vertexBuffer.indices = [[NSMutableData alloc] initWithLength:(sizeof(VertexIndices) * totalIndices)];
    }

    //return vertex buffer
    return vertexBuffer;
}

//grow or shrink a vertex buffer
static inline void VertexBufferResize(VertexBuffer *vertexBuffer, NSUInteger totalVertices, NSUInteger totalIndices)
{
    //check adjusted vertices count
    if(vertexBuffer->totalVertices != totalVertices && totalVertices > 0)
    {
        //set vertices count
        vertexBuffer->totalVertices = totalVertices;

        //check data is valid
        if(vertexBuffer->vertexData)
        {
            //allocate data
            [vertexBuffer->vertexData setLength:(sizeof(InterleavingVertexData) * totalVertices)];
        }
        else
        {
            //allocate data
            vertexBuffer->vertexData = [[NSMutableData alloc] initWithLength:(sizeof(InterleavingVertexData) * totalVertices)];
        }
    }

    //check adjusted indices count
    if(vertexBuffer->totalIndices != totalIndices && totalIndices > 0)
    {
        //set indices count
        vertexBuffer->totalIndices = totalIndices;

        //check data is valid
        if(vertexBuffer->indices)
        {
            //allocate data
            [vertexBuffer->indices setLength:(sizeof(VertexIndices) * totalIndices)];
        }
        else
        {
            //allocate data
            vertexBuffer->indices = [[NSMutableData alloc] initWithLength:(sizeof(VertexIndices) * totalIndices)];
        }
    }
}

//release vertex buffer data
static inline void VertexBufferRelease(VertexBuffer *vertexBuffer)
{
    //set vertices and indices count
    vertexBuffer->totalVertices = 0;
    vertexBuffer->totalIndices = 0;

    //check vertices are valid
    if(vertexBuffer->vertexData)
    {
        //clean up
        [vertexBuffer->vertexData release];
        vertexBuffer->vertexData = nil;
    }

    //check indices are valid
    if(vertexBuffer->indices)
    {
        //clean up
        [vertexBuffer->indices release];
        vertexBuffer->indices = nil;
    }
}

В настоящее время данные перемежающихся вершин содержат достаточно для хранения вершин, нормалей, цветов и координат текстуры для каждой вершины. У меня создалось впечатление, что будет равное количество вершин и индексов, но на практике это, очевидно, не так, поэтому по этой причине индексы являются частью VBO, а не InterleavingVertexData.

Вопрос обновлен:

Я обновил код выше, после того, как он разрешил его в рабочее состояние. Надеюсь, это пригодится кому-то в будущем.

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

//generate buffers
glGenBuffers(2, buffers);

//bind vertices buffer
glBindBuffer(GL_ARRAY_BUFFER, buffers[0]);
glBufferData(GL_ARRAY_BUFFER, (sizeof(InterleavingVertexData) * vertexBuffer.totalVertices), self.vertexData, GL_STATIC_DRAW);

//bind indices buffer
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[1]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, (sizeof(VertexIndices) * vertexBuffer.totalIndices), self.vertexIndices, GL_STATIC_DRAW);

//reset buffers
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

И код для рендеринга всего:

//enable required attributes
glEnableVertexAttribArray(GLKVertexAttribPosition);
glEnableVertexAttribArray(GLKVertexAttribNormal);
glEnableVertexAttribArray(GLKVertexAttribColor);
glEnableVertexAttribArray(GLKVertexAttribTexCoord0);

//bind buffers
glBindBuffer(GL_ARRAY_BUFFER, buffers[0]);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[1]);

//set shape attributes
glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, sizeof(InterleavingVertexData), (void *)offsetof(InterleavingVertexData, vertices));
glVertexAttribPointer(GLKVertexAttribNormal, 3, GL_FLOAT, GL_TRUE, sizeof(InterleavingVertexData), (void *)offsetof(InterleavingVertexData, normal));
glVertexAttribPointer(GLKVertexAttribColor, 4, GL_FLOAT, GL_TRUE, sizeof(InterleavingVertexData), (void *)offsetof(InterleavingVertexData, color));
glVertexAttribPointer(GLKVertexAttribTexCoord0, 2, GL_FLOAT, GL_TRUE, sizeof(InterleavingVertexData), (void *)offsetof(InterleavingVertexData, texture));

//draw shape
glDrawElements(GL_TRIANGLES, vertexBuffer.totalIndices, GL_UNSIGNED_INT, (void *)0);

//reset buffers
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

//disable atttributes
glDisableVertexAttribArray(GLKVertexAttribTexCoord0);
glDisableVertexAttribArray(GLKVertexAttribColor);
glDisableVertexAttribArray(GLKVertexAttribNormal);
glDisableVertexAttribArray(GLKVertexAttribPosition);

Пока мой iPhone еще не взорвался потрясающей графикой единорогов, снимающих радуги с их глаз, я не смог сделать простую форму целиком, не отрывая волосы.

Из рендеринга кажется, что нарисовано только 1/3 каждой фигуры, возможно, 1/2 в зависимости от угла обзора. Кажется, что виновником является параметр count, переданный glDrawElements, поскольку это имеет разные результаты, но я прочитал документацию и проверил значение снова и снова, и он действительно ожидает общее количество индексов (это то, что я проходящий в настоящее время).

Как я уже упоминал в своем первоначальном вопросе, я довольно смущен VBO в настоящее время или, скорее, смущен реализацией, а не концепцией, по крайней мере. Если бы кто-нибудь был так добр, чтобы бросить взгляд на мою реализацию, это было бы потрясающе, так как я уверен, что я сделал ошибку новобранец где-то на этом пути, но вы знаете, как это происходит, когда вы что-то часами смотрите на закончите без прогресса.

Спасибо за чтение!

4b9b3361

Ответ 1

Думаю, я вижу твою проблему.

У вас есть структура, VertexIndices, которая содержит три индекса или индексы для одного треугольника. Когда вы связываете свой IBO (объект Buffer Index, объект буфера, содержащий ваши индексы), вы делаете это:

glBufferData(GL_ELEMENT_ARRAY_BUFFER, (sizeof(VertexIndices) * vertexBuffer.totalIndices), self.vertexIndices, GL_STATIC_DRAW);

Это нормально. Параметр size в glBufferData находится в байтах, поэтому вы умножаете sizeof (3 поплавки) на число групп из 3 поплавков, которые у вас есть. Отлично.

Но тогда, когда вы на самом деле вызываете glDrawElements, вы делаете это:

glDrawElements(GL_TRIANGLES, vertexBuffer.totalIndices, GL_UNSIGNED_INT, (void *)0);

Однако vertexBuffer.totalIndices равно количеству структур VertexIndices, которые у вас есть, что равно общему числу индексов /3 (или общее количество треугольников). Поэтому вам нужно выполнить одно из следующих действий:

  • Легкое исправление, но глупое: glDrawElements(..., vertexBuffer.totalIndices * 3, ...);
  • Правильная еще больше работы: vertexBuffer.totalIndices должно содержать фактическое общее количество индексов, которое у вас есть, а не общее количество отображаемых треугольников.

Вам нужно сделать одно из них, потому что сейчас totalIndices содержит общее количество VertexIndices, которое у вас есть, и каждый имеет 3 индекса. Правильная вещь здесь - либо переименовать totalIndices в totalTriangles, либо отслеживать фактическое общее количество индексов где-то.