aboutsummaryrefslogtreecommitdiffstats
path: root/examples/support/mod.rs
blob: eb27d236a888661493d75f91878a3f2fabe5d064 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#![cfg(feature = "window")]

#[phase(plugin)]
extern crate gl_generator;

use glutin;

#[cfg(not(target_os = "android"))]
mod gl {
    generate_gl_bindings! {
        api: "gl",
        profile: "core",
        version: "1.1",
        generator: "struct"
    }
}

#[cfg(target_os = "android")]
mod gl {
    pub use self::Gles1 as Gl;
    generate_gl_bindings! {
        api: "gles1",
        profile: "core",
        version: "1.1",
        generator: "struct"
    }
}

pub struct Context {
    gl: gl::Gl
}

pub fn load(window: &glutin::Window) -> Context {
    let gl = gl::Gl::load(window);

    let version = {
        use std::c_str::CString;
        unsafe { CString::new(gl.GetString(gl::VERSION) as *const i8, false) }
    };

    println!("OpenGL version {}", version.as_str().unwrap());

    Context { gl: gl }
}

impl Context {
    #[cfg(not(target_os = "android"))]
    pub fn draw_frame(&self, color: (f32, f32, f32, f32)) {
        unsafe {
            self.gl.ClearColor(color.0, color.1, color.2, color.3);
            self.gl.Clear(gl::COLOR_BUFFER_BIT);

            self.gl.Begin(gl::TRIANGLES);
            self.gl.Color3f(1.0, 0.0, 0.0);
            self.gl.Vertex2f(-0.5, -0.5);
            self.gl.Color3f(0.0, 1.0, 0.0);
            self.gl.Vertex2f(0.0, 0.5);
            self.gl.Color3f(0.0, 0.0, 1.0);
            self.gl.Vertex2f(0.5, -0.5);
            self.gl.End();

            self.gl.Flush();
        }
    }

    #[cfg(target_os = "android")]
    pub fn draw_frame(&self, color: (f32, f32, f32, f32)) {
        unsafe {
            self.gl.ClearColor(color.0, color.1, color.2, color.3);
            self.gl.Clear(gl::COLOR_BUFFER_BIT);

            self.gl.EnableClientState(gl::VERTEX_ARRAY);
            self.gl.EnableClientState(gl::COLOR_ARRAY);

            unsafe {
                use std::mem;
                self.gl.VertexPointer(2, gl::FLOAT, (mem::size_of::<f32>() * 5) as i32,
                    mem::transmute(VERTEX_DATA.as_slice().as_ptr()));
                self.gl.ColorPointer(3, gl::FLOAT, (mem::size_of::<f32>() * 5) as i32,
                    mem::transmute(VERTEX_DATA.as_slice().as_ptr().offset(2)));
            }

            self.gl.DrawArrays(gl::TRIANGLES, 0, 3);
            self.gl.DisableClientState(gl::VERTEX_ARRAY);
            self.gl.DisableClientState(gl::COLOR_ARRAY);
            
            self.gl.Flush();
        }
    }
}

#[cfg(target_os = "android")]
static VERTEX_DATA: [f32, ..15] = [
    -0.5, -0.5, 1.0, 0.0, 0.0,
    0.0, 0.5, 0.0, 1.0, 0.0,
    0.5, -0.5, 0.0, 0.0, 1.0
];