繪制多個(gè)重復(fù)的模型時(shí),使用Instanced方式繪制可以大大加快顯然速度。
網(wǎng)站建設(shè)哪家好,找創(chuàng)新互聯(lián)!專注于網(wǎng)頁(yè)設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、小程序開發(fā)、集團(tuán)企業(yè)網(wǎng)站建設(shè)等服務(wù)項(xiàng)目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了望城免費(fèi)建站歡迎大家使用!
繪制效果如下圖所示:
1、Vertex Shader中定義如下:
attribute vec3 pos; attribute vec2 coord; attribute vec3 normal; attribute vec3 offset; uniform mat4 M; uniform mat4 V; uniform mat4 P; uniform mat4 NM; varying vec2 M_coord; varying vec3 M_normal; varying vec4 M_WordPos; void main() { M_coord = coord; M_WordPos = M * vec4(pos, 1.0) + vec4(offset, 1.0); M_normal = mat3(NM) * normal; gl_Position = P * V * M_WordPos; }
offset為每次繪制的偏移量。
2、CPU端實(shí)現(xiàn)
float nIndexOffset[] = { -100.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 100.0f, 0.0f, 0.0f };
createBufferObject為封裝創(chuàng)建OpenGL Buffer的函數(shù)
定義如下:
GLuint OpenGLOperate::createBufferObject(GLenum nBufferType, GLsizeiptr size, \ const GLvoid *data, GLenum usage) { GLuint BufferObjIndex = 0; m_OpenGLCore->glGenBuffers(1, &BufferObjIndex); m_OpenGLCore->glBindBuffer(nBufferType, BufferObjIndex); m_OpenGLCore->glBufferData(nBufferType, size, data, usage); m_OpenGLCore->glBindBuffer(nBufferType, 0); return BufferObjIndex; }
創(chuàng)建Offset的FBO
m_OffsetIndex = m_OpenGLOperate->createBufferObject(GL_ARRAY_BUFFER, \ sizeof(float) * 9, \ (void*)nIndexOffset, GL_STATIC_DRAW);
為Offset賦值
OpenGLCore->glBindBuffer(GL_ARRAY_BUFFER, m_OffsetIndex); OpenGLCore->glEnableVertexAttribArray(m_OffsetLocation); OpenGLCore->glVertexAttribPointer(m_OffsetLocation, 3, GL_FLOAT, GL_FALSE, \ sizeof(float) * 3, (void*)0); OpenGLCore->glBindBuffer(GL_ARRAY_BUFFER, 0); OpenGLCore->glVertexAttribDivisor(m_OffsetLocation, 1);
調(diào)用繪制指令:
OpenGLCore->glDrawElementsInstanced(GL_TRIANGLES, m_VertexCount, \ GL_UNSIGNED_INT, 0, 3);