如何在glDrawArrays()绘制的形状上设置纹理?

时间:2013-08-12 16:24:56

标签: java opengl jogl texture-mapping texture2d

我有一个由顶点数组绘制的3D立方体 -

public void init(GLAutoDrawable drawable) {
...
float[] cubeVertices = {...}; // vertex coordinates (x,y,z) 
FloatBuffer tmpVerticesBuf = BufferUtil
                .newFloatBuffer(cubeVertices.length);
for (int i = 0; i < cubeVertices.length; i++) {
            tmpVerticesBuf.put(cubeVertices[i]);
        }
tmpVerticesBuf.rewind();
gl.glEnableClientState(GL.GL_VERTEX_ARRAY); 
gl.glVertexPointer(3, GL.GL_FLOAT, 0, tmpVerticesBuf);
}

public void display(GLAutoDrawable drawable) {
...
gl.glDrawArrays(GL.GL_QUADS, 0, 24);
...
}

现在我想在这个立方体的面上设置纹理图片,使其与所有立方体面的纹理相同。到目前为止,我在init() -

中做了
public void init(GLAutoDrawable drawable) { 
...
try {
                    // retrieve the image .  
            BufferedImage image = ImageIO.read(getClass().getClassLoader()
                    .getResource("floor.jpg"));
            DataBufferByte dbb = (DataBufferByte) image.getRaster()
                    .getDataBuffer();
            byte[] data = dbb.getData();
            ByteBuffer pixels = BufferUtil.newByteBuffer(data.length);
            pixels.put(data);
            pixels.flip();

        } catch (GLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        m_textutureIntBuf = IntBuffer.allocate(1); // m_textutureIntBuf type  IntBuffer
        gl.glGenTextures(1, m_textutureIntBuf);
        gl.glBindTexture(GL.GL_TEXTURE_2D, m_textutureIntBuf.get(0));
        gl.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGB, 256, 256, 0, GL.GL_RGB,
                GL.GL_UNSIGNED_BYTE, m_pixels);
        gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER,
                GL.GL_LINEAR);
        gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER,
                GL.GL_NEAREST);
        gl.glEnable(GL.GL_TEXTURE_2D);
}

关于gl.glTexCoordPointer() gl.glEnableClientState()我现在必须做些什么来获得我之前提到的关于纹理的内容?

1 个答案:

答案 0 :(得分:3)

你需要为Texture Coordinates创建一个数组。

“... DATA ...”,您需要添加U,V坐标。所有顶点都有U,V坐标。因此tex_coord_size基本上是2 * vertices_count

int tex_coord_size = x; // Whatever size you want according to your `Vertices`

FloatBuffer tex_coord_data = BufferTools.createFloatBuffer(tex_coord_size);
tex_coord_data.put(new float[] { ... DATA ... });
tex_coord_data.flip();


int vbo_tex_coord_handle = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, vbo_tex_coord_handle );
glBufferData(GL_ARRAY_BUFFER, tex_coord_data, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);

然后渲染你需要添加到你当前的渲染中。

glBindBuffer(GL_ARRAY_BUFFER, vbo_tex_coord_handle);
glTexCoordPointer(tex_coord_size, GL_FLOAT, 0, 0l);

glEnableClientState(GL_TEXTURE_COORD_ARRAY);

在你调用glDrawArrays之后,你当然也需要调用glDisableClientState(GL_TEXTURE_COORD_ARRAY);