require 'riko/math'
require 'riko/graphics/opentk/gles2'
def vec4(x, y, z, w); Riko::Vector.new(x, y, z, w); end
def vec3(x, y, z); Riko::Vector.new(x, y, z, 0.0); end
def vec2(x, y); Riko::Vector.new(x, y, 0.0, 0.0); end
window = Riko::Graphics::OpenTK::GLES2::GameWindow.new(256, 256)
context = window.context
vertex_shader = context.compile_shader(:vertex, <<GLSL)
#ifdef GL_ES
precision mediump float;
#endif
attribute vec4 aVertex;
attribute vec3 aNormal;
attribute vec4 aColor;
varying vec4 vColor;
uniform mat4 uModelViewProjectionMatrix;
void main()
{
gl_Position = uModelViewProjectionMatrix * aVertex;
vColor = aColor;
}
GLSL
fragment_shader = context.compile_shader(:fragment, <<GLSL)
#ifdef GL_ES
precision mediump float;
#endif
varying vec4 vColor;
void main()
{
gl_FragColor = vColor;
}
GLSL
program = context.create_program
program.attach(vertex_shader)
program.attach(fragment_shader)
program.bind_attrib_location(0, 'aVertex')
program.bind_attrib_location(1, 'aNormal')
program.bind_attrib_location(2, 'aColor')
program.link
vertex_array = context.create_vertex_array
vertex_buffer = context.create_buffer([
[ #position
#front
[ 1.0, 1.0, 1.0, 1.0],
[-1.0, 1.0, 1.0, 1.0],
[-1.0,-1.0, 1.0, 1.0],
[ 1.0, 1.0, 1.0, 1.0],
[-1.0,-1.0, 1.0, 1.0],
[ 1.0,-1.0, 1.0, 1.0],
#back
[-1.0, 1.0,-1.0, 1.0],
[ 1.0, 1.0,-1.0, 1.0],
[ 1.0,-1.0,-1.0, 1.0],
[-1.0, 1.0,-1.0, 1.0],
[ 1.0,-1.0,-1.0, 1.0],
[-1.0,-1.0,-1.0, 1.0],
#left
[-1.0, 1.0, 1.0, 1.0],
[-1.0, 1.0,-1.0, 1.0],
[-1.0,-1.0,-1.0, 1.0],
[-1.0, 1.0, 1.0, 1.0],
[-1.0,-1.0,-1.0, 1.0],
[-1.0,-1.0, 1.0, 1.0],
#right
[ 1.0, 1.0,-1.0, 1.0],
[ 1.0, 1.0, 1.0, 1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0, 0.0],
[ 1.0, 0.0, 1.0, 0.0],
],
].flatten.pack('f*'), :static_draw)
vertex_array.vertex_attrib(0, 4, :float, false, 16, 0*36*16, vertex_buffer)
vertex_array.vertex_attrib(1, 3, :float, false, 16, 1*36*16, vertex_buffer)
vertex_array.vertex_attrib(2, 4, :float, false, 16, 2*36*16, vertex_buffer)
context.set_front_face(:ccw)
context.set_cull_face(:back)
context.set_depth_func(:less)
context.set_clear_color(0.2, 0.2, 0.2, 0.0)
model_transform = Riko::Matrix.identity
vp_matrix =
Riko::Matrix.perspective(45, 1.0, 0.1, 100.0) *
Riko::Matrix.look_at(
vec3( 0.0, 0.0, 0.0),
vec3( 2.0, 2.0, 2.0),
vec3( 0.0, 1.0, 0.0))
t = Time.now
window.run do |step|
context.clear
Riko::Matrix.mul_rotate(model_transform, step*Math::PI/180.0, 0.0, 1.0, 0.0)
mvp_matrix = vp_matrix * model_transform
program.uniform_matrix4(program.uniform_location('uModelViewProjectionMatrix'), 1, mvp_matrix.transpose.to_a)
context.draw_arrays(program, :triangles, vertex_array, 0, 36)
window.swap_buffers
window.close if Time.now-t>6
end