Skip to content

Instantly share code, notes, and snippets.

@xian
Created August 9, 2019 20:44
Show Gist options
  • Save xian/d517b0aff455111d4da8611300d507d8 to your computer and use it in GitHub Desktop.
Save xian/d517b0aff455111d4da8611300d507d8 to your computer and use it in GitHub Desktop.
vertex shader:
#version 300 es
#ifdef GL_ES
precision mediump float;
#endif
in vec4 Vertex;
uniform mat4 viewProjMatrix;
void main(void) {
gl_Position = viewProjMatrix * Vertex;
}
matrix:
internal var viewProjMatrix = Matrix4()
.makeOrthographic(-0.5, 0.5, -.5, .5, 1.0, 10.0)
.lookAt(
Vector3(0.0f, 0.0f, 1.0f),
Vector3(0.0f, 0.0f, 0.0f),
Vector3(0.0f, 1.0f, 0.0f)
)
quad:
inner class Quad {
private val vertices = arrayOf(
// Left bottom triangle
-0.5f, 0.5f, 0f,
-0.5f, -0.5f, 0f,
0.5f, -0.5f, 0f,
// Right top triangle
0.5f, -0.5f, 0f,
0.5f, 0.5f, 0f,
-0.5f, 0.5f, 0f
)
private val indices = arrayOf(0, 1, 2, 3, 4, 5).map { it.toShort() }.toTypedArray()
private var quadVertexBuffer: WebGLBuffer? = null
private var indexBuffer: WebGLBuffer? = null
init {
quadVertexBuffer = gl.createBuffer()
gl { gl.bindBuffer(GL.ARRAY_BUFFER, quadVertexBuffer) }
gl { gl.bufferData(GL.ARRAY_BUFFER, Float32Array(vertices), GL.STATIC_DRAW); }
indexBuffer = gl.createBuffer()
gl { gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, indexBuffer); }
gl { gl.bufferData(GL.ELEMENT_ARRAY_BUFFER, Uint16Array(indices), GL.STATIC_DRAW); }
val vertexAttr = gl { gl.getAttribLocation(program, "Vertex") }
gl { gl.vertexAttribPointer(vertexAttr, 3, GL.FLOAT, false, 0, 0) }
gl { gl.enableVertexAttribArray(vertexAttr) }
gl { gl.bindBuffer(GL.ARRAY_BUFFER, null) }
gl { gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, null); }
}
internal fun render() {
gl { gl.bindBuffer(GL.ARRAY_BUFFER, quadVertexBuffer) }
gl { gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, indexBuffer); }
// Draw the vertices
gl { gl.drawElements(GL.TRIANGLES, indices.size, GL.UNSIGNED_SHORT,0) }
gl { gl.bindBuffer(GL.ARRAY_BUFFER, null) }
gl { gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, null); }
}
private fun release() {
gl { gl.bindBuffer(GL.ARRAY_BUFFER, null) }
gl { gl.deleteBuffer(quadVertexBuffer) }
gl { gl.deleteBuffer(indexBuffer) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment