Rust言語のgliumライブラリ(OpenGLライブラリ)を用いて、coloured triangleを
描画しています。
( 実行結果)
・triangleは、上矢印キー(左回転)と下矢印キー(右回転)を使って回転させて
います。
プログラム
### triangle.rs
#[macro_use]
extern crate glium;
use glium::{DisplayBuild, Surface};
use glium::glutin;
fn main() {
let display = glutin::WindowBuilder::new()
.with_dimensions(600, 600)
.with_title(format!("Glium Triangle Test"))
.build_glium().unwrap();
#[derive(Copy, Clone)]
struct Vertex {
position: [f32; 2],
color: [f32; 3],
}
implement_vertex!(Vertex, position, color);
let vertex1 = Vertex { position: [-0.5, -0.5], color: [0.0, 0.0, 1.0] };
let vertex2 = Vertex { position: [ 0.0, 0.5], color: [0.0, 1.0, 0.0] };
let vertex3 = Vertex { position: [ 0.5, -0.5], color: [1.0, 0.0, 0.0] };
let shape = vec![vertex1, vertex2, vertex3];
let vertex_buffer = glium::VertexBuffer::new(&display, &shape).unwrap();
let indices = glium::index::NoIndices(glium::index::PrimitiveType::TrianglesList);
let vertex_shader_src = r#"
#version 140
in vec2 position;
in vec3 color;
out vec3 vColor;
uniform mat4 matrix;
void main() {
gl_Position = matrix * vec4(position, 0.0, 1.0);
vColor = color;
}
"#;
let fragment_shader_src = r#"
#version 140
in vec3 vColor;
out vec4 f_color;
void main() {
f_color = vec4(vColor, 1.0);
}
"#;
let program = glium::Program::from_source(&display, vertex_shader_src,
fragment_shader_src, None).unwrap();
let mut t: f32 = 0.0;
loop {
let mut target = display.draw();
target.clear_color(0.0, 0.0, 0.0, 1.0);
let uniforms = uniform! {
matrix: [
[ t.cos(), t.sin(), 0.0, 0.0],
[-t.sin(), t.cos(), 0.0, 0.0],
[ 0.0, 0.0, 1.0, 0.0],
[ 0.0, 0.0, 0.0, 1.0f32],
]
};
target.draw(&vertex_buffer, &indices, &program, &uniforms,
&Default::default()).unwrap();
target.finish().unwrap();
for ev in display.poll_events() {
match ev {
glium::glutin::Event::Closed => return,
glutin::Event::KeyboardInput(glutin::ElementState::Pressed, _, Some(glutin::VirtualKeyCode::Up)) => {
t += 0.01;
println!("KeyUP Pressed {}", t);
},
glutin::Event::KeyboardInput(glutin::ElementState::Pressed, _,
Some(glutin::VirtualKeyCode::Down)) => {
t -= 0.01;
println!("KeyDown Pressed {}", t);
},
_ => ()
}
}
}
}
・gliumライブラリのexamplesの例を組み合わせています。
### Cargo.toml
[package]
name = "triangle"
version = "0.1.0"
authors = ["xxxxx"]
[dependencies]
glium = "*"