[英]OpenGL draws weird lines on top of polygons
讓我向您介紹Fishtank:
這是我在OpenGL上做的一個水族館模擬器,在進入Vulkan之前需要學習。
我畫了很多像這樣的魚:
現在,我添加了網格功能,如下所示:
但是,當我讓它轉動一段時間時,將出現以下幾行:
我已經看到某個地方清除了“深度緩沖區”,但是這樣做並不能解決問題。
這是該函數的代碼:
void Game::drawGrid()
{
std::vector<glm::vec2> gridVertices;
for (unsigned int x = 1; x < mGameMap.mColCount; x += 1) //Include the last one as the drawed line is the left of the column
{
gridVertices.push_back(glm::vec2(transformToNDC(mWindow, x*mGameMap.mCellSize, mGameMap.mCellSize)));
gridVertices.push_back(glm::vec2(transformToNDC(mWindow, x*mGameMap.mCellSize, (mGameMap.mRowCount-1)*mGameMap.mCellSize)));
}
for (unsigned int y = 1; y < mGameMap.mRowCount; y += 1) //Same here but special info needed:
// Normally, the origin is at the top-left corner and the y-axis points to the bottom. However, OpenGL's y-axis is reversed.
// That's why taking into account the mRowCount-1 actually draws the very first line.
{
gridVertices.push_back(glm::vec2(transformToNDC(mWindow, mGameMap.mCellSize, y*mGameMap.mCellSize)));
gridVertices.push_back(glm::vec2(transformToNDC(mWindow, (mGameMap.mColCount - 1)*mGameMap.mCellSize, y*mGameMap.mCellSize)));
}
mShader.setVec3("color", glm::vec3(1.0f));
glBufferData(GL_ARRAY_BUFFER, gridVertices.size()*sizeof(glm::vec2), gridVertices.data(), GL_STATIC_DRAW);
glVertexAttribPointer(0, 2, GL_FLOAT_VEC2, GL_FALSE, sizeof(glm::vec2), (void*)0);
glEnableVertexAttribArray(0);
glDrawArrays(GL_LINES, 0, gridVertices.size()*sizeof(glm::vec2));
glClear(GL_DEPTH_BUFFER_BIT);
}
我想刪除這些行,並理解OpenGL為什么這樣做(或者也許是我,但我不知道在哪里)。
這是有問題的行:
glDrawArrays(GL_LINES, 0, gridVertices.size()*sizeof(glm::vec2));
void glDrawArrays(GLenum模式,GLint首先,GLsizei計數);
count :指定要呈現的索引數
但是,您正在傳遞字節大小。 因此,您要求OpenGL繪制比頂點緩沖區中更多的頂點。 您正在使用的特定OpenGL實現可能正在讀取網格頂點緩沖區的末尾,並從魚頂點緩沖區中找到要繪制的頂點(但是此行為是不確定的)。
因此,只需將其更改為
glDrawArrays(GL_LINES, 0, gridVertices.size());
一個一般性的評論:不要在每次想繪制同一事物時都創建頂點緩沖區。 在應用程序的開頭創建它們,然后重新使用它們。 您也可以根據需要更改其內容,但要謹慎行事,因為它具有性能價格。 創建頂點緩沖區的成本更高。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.