我正在学习有关使用OpenGL在Java中创建游戏引擎的教程。
我正在尝试在屏幕上渲染一个三角形。一切运行正常,我可以更改背景颜色,但三角形不会显示。我也尝试过运行作为教程系列的一部分提供的代码,但仍然无法正常工作。
链接至教程:http : //bit.ly/1EUnvz4
链接到视频中使用的代码:http : //bit.ly/1z7XUlE
建立
Mesh.java
import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.opengl.GL15.*; import static org.lwjgl.opengl.GL20.*; public class Mesh { private int vbo; //pointer to the buffer private int size; //size of the data to buffer public Mesh () { vbo = glGenBuffers(); size = 0; } public void addVertices (Vertex[] vertices) { size = vertices.length; //add the data by first binding the buffer glBindBuffer (GL_ARRAY_BUFFER, vbo); //vbo is now the buffer //and then buffering the data glBufferData (GL_ARRAY_BUFFER, Util.createFlippedBuffer(vertices), GL_STATIC_DRAW); } public void draw () { glEnableVertexAttribArray (0); //divide up the data into a segment glBindBuffer (GL_ARRAY_BUFFER, vbo); //vbo is now the buffer //tell OpenGL more about the segment: //segment = 0, elements = 3, type = float, normalize? = false, vertex size, where to start = 0) glVertexAttribPointer(0, 3, GL_FLOAT, false, Vertex.SIZE * 4, 0); //draw GL_TRIANGLES starting from '0' with a given 'size' glDrawArrays (GL_TRIANGLES, 0, size); glDisableVertexAttribArray (0); } }
RenderUtil.java
import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.opengl.GL30.*; public class RenderUtil { public static void clearScreen () { //TODO: Stencil Buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } //set everything to engine defaults public static void initGraphics () { glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // default color glFrontFace(GL_CW); // direction for visible faces glCullFace(GL_BACK); // direction for back faces glEnable (GL_CULL_FACE); // don't draw back faces glEnable (GL_DEPTH_TEST); // determines draw order by pixel depth testing //TODO: Depth clamp for later glEnable (GL_FRAMEBUFFER_SRGB); // do exponential correction on gamma so we don't have to } }
实用程序
import java.nio.FloatBuffer; import org.lwjgl.BufferUtils; public class Util { //create a float buffer (we need this because java is weird) public static FloatBuffer createFloatBuffer (int size) { return BufferUtils.createFloatBuffer(size); } //flip the buffer to fit what OpenGL expects public static FloatBuffer createFlippedBuffer (Vertex[] vertices) { FloatBuffer buffer = createFloatBuffer(vertices.length * Vertex.SIZE); for (int i = 0; i < vertices.length; i++) { buffer.put(vertices[i].getPos().getX()); buffer.put(vertices[i].getPos().getY()); buffer.put(vertices[i].getPos().getZ()); } buffer.flip(); return buffer; } }
您正在使用旧版和现代OpenGL的无效组合。
您要调用的glVertexAttribPointer()和glEnableVertexAttribArray()函数用于设置 通用 顶点属性。这是在当前版本的OpenGL(桌面OpenGL或OpenGL ES 2.0及更高版本)中设置顶点属性的唯一方法。它们也可以在旧版OpenGL中使用,但只能与在GLSL中实现的提供自己的着色器结合使用。
glVertexAttribPointer()
glEnableVertexAttribArray()
如果您只是入门,那么最好的选择可能是继续使用已有的东西,并研究如何开始实现自己的着色器。如果要使代码与旧式固定管道一起使用(仅在OpenGL兼容性配置文件中受支持),则需要使用glVertexPointer()和glEnableClientState()函数。
glVertexPointer()
glEnableClientState()