gfxmath-vec3 0.1.3

A simple 3D math library
Documentation
use super::shaderprogram::ShaderProgram;
use super::shader::{Shader, ShaderType};

use sdl2::video::GLProfile;

pub const V_SHADER: &str = r"
#version 450 core
layout (location = 0) in vec2 pos;

uniform vec3 position;
uniform vec3 scale;

void main() {
    mat4 model = mat4(
        vec4(scale.x,     0.0,     0.0, position.x),
        vec4(    0.0, scale.y,     0.0, position.y),
        vec4(    0.0,     0.0, scale.z, position.z),
        vec4(    0.0,     0.0,     0.0,        1.0)
    );  

    gl_Position = transpose(model) * vec4(pos, 0.0, 1.0);
}
";

pub const F_SHADER: &str = r"
#version 450 core

out vec4 o_col;

uniform vec3 color;

void main() {
    o_col = vec4(color.x, color.y, color.z, 1.0);
}
";

pub fn init<S: AsRef<str>>(window_name: S) -> (sdl2::Sdl, sdl2::video::GLContext, sdl2::video::Window) {
    sdl2::hint::set("SDL_NO_SIGNAL_HANDLERS", "1");
    let sdl_context = sdl2::init().unwrap();
    let video_subsystem = sdl_context.video().unwrap();

    let gl_attr = video_subsystem.gl_attr();
    gl_attr.set_context_profile(GLProfile::Core);
    gl_attr.set_context_version(4, 5);

    let window = video_subsystem.window(window_name.as_ref(), 800, 800)
        .opengl()
        .build()
        .unwrap();

    // Unlike the other example above, nobody created a context for your window, so you need to create one.
    let ctx = window.gl_create_context().unwrap();
    gl::load_with(|name| video_subsystem.gl_get_proc_address(name) as *const _);

    debug_assert_eq!(gl_attr.context_profile(), GLProfile::Core);
    debug_assert_eq!(gl_attr.context_version(), (4, 5));

    (sdl_context, ctx, window)
}

pub fn init_buffers() -> (u32, u32) {
    let mut vao: gl::types::GLuint = 0;
    let mut vbo: gl::types::GLuint = 0;

    unsafe {
        gl::GenVertexArrays(1, &mut vao as *const _ as *mut gl::types::GLuint);
        gl::GenBuffers(1, &mut vbo as *const _ as *mut gl::types::GLuint);
        
        if vao == 0 || vbo == 0 { panic!("failed to generate buffer or vertex arrays "); }

        gl::BindVertexArray(vao);

        gl::BindBuffer(gl::ARRAY_BUFFER, vbo);
        gl::BufferData(gl::ARRAY_BUFFER, 0, std::ptr::null(), gl::DYNAMIC_DRAW);

        gl::VertexAttribPointer(0, 3, gl::FLOAT, gl::FALSE, 0 as i32, std::ptr::null());
        gl::EnableVertexAttribArray(0);

        gl::BindVertexArray(0);
    }

    (vao, vbo)
}

pub fn get_shader() -> ShaderProgram {
    let v_shader = Shader::load(V_SHADER, ShaderType::Vertex).unwrap();
    dbg!("Loaded v_shader!");
    let f_shader = Shader::load(F_SHADER, ShaderType::Fragment).unwrap();
    dbg!("Loaded f_shaders!");
    
    let shader = ShaderProgram::new().unwrap();
    shader.activate();
    shader.attach(&v_shader);
    shader.attach(&f_shader);
    shader.link();
    shader
}