emecoding
emecoding

Reputation: 21

How to program textures in Rust OpenGL?

I can't get this code working. It only shows me a black triangle, and it doesn't even show me any errors. I have tried to apply textures for this, but it won't work!

#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
#![allow(clippy::single_match)]
#![allow(unused_imports)]
#![allow(clippy::zero_ptr)]

const WINDOW_TITLE: &str = "Triangle: Draw Arrays";

use beryllium::*;
use core::{
    convert::{TryFrom, TryInto},
    mem::{size_of, size_of_val},
};
use libc::c_void;
use ogl33::*;
use stb_image::stb_image::bindgen::{stbi_image_free, stbi_load};
use std::ffi::CString;

mod VertexArray;
mod Buffer;
mod Shader;
mod ShaderProgram;
mod polygon_mode;

use crate::Buffer::*;

type Vertex = [f32; 5]; //x, y, z, tx, ty
type TriIndexes = [u32; 3];

const VERTICES: [Vertex; 3] = [
    [0.5, 0.5, 0.0, 0.5, 0.5],
    [0.5, -0.5, 0.0, 0.5, -0.5],
    [-0.5, -0.5, 0.0, -0.5, -0.5],
];

const INDICES: [TriIndexes; 2] = [[0, 1, 3], [1, 2, 3]];

const VERT_SHADER: &str = r#"#version 330 core
 layout (location = 0) in vec3 pos;
 layout (location = 1) in vec2 texPos;
 out vec2 TexCoord;
 void main() {
  gl_Position = vec4(pos.x, pos.y, pos.z, 1.0);
  TexCoord = texPos;
}
"#;

const FRAG_SHADER: &str = r#"#version 330 core
out vec4 final_color;
in vec2 TexCoord;
uniform sampler2D tex;
void main() {
  final_color = texture(tex, TexCoord);
}
"#;

fn main() {
    let mut tex: u32 = 0;
    let mut vao: VertexArray::VertexArray;
    let mut shader_program: ShaderProgram::ShaderProgram;
    let sdl = SDL::init(InitFlags::Everything).expect("couldn't start SDL");
    sdl.gl_set_attribute(SdlGlAttr::MajorVersion, 3).unwrap();
    sdl.gl_set_attribute(SdlGlAttr::MinorVersion, 3).unwrap();
    sdl.gl_set_attribute(SdlGlAttr::Profile, GlProfile::Core)
        .unwrap();
    #[cfg(target_os = "macos")]
    {
        sdl.gl_set_attribute(SdlGlAttr::Flags, ContextFlag::ForwardCompatible)
            .unwrap();
    }

    let win = sdl
        .create_gl_window(
            WINDOW_TITLE,
            WindowPosition::Centered,
            800,
            600,
            WindowFlags::Shown,
        )
        .expect("couldn't make a window and context");
    win.set_swap_interval(SwapInterval::Vsync);

    unsafe {
        load_gl_with(|f_name| win.get_proc_address(f_name));

        glClearColor(0.2, 0.3, 0.3, 1.0);

        vao = VertexArray::VertexArray::new().expect("couldn't make a vao");
        vao.bind();

        let vbo = Buffer::Buffer::new().expect("couldn't make a vbo");
        vbo.bind(BufferType::Array);
        Buffer::buffer_data(
            BufferType::Array,
            bytemuck::cast_slice(&VERTICES),
            GL_STATIC_DRAW,
        );

        let ebo = Buffer::Buffer::new().expect("couldn't make a ebo");
        ebo.bind(BufferType::ElementArray);
        Buffer::buffer_data(
            BufferType::ElementArray,
            bytemuck::cast_slice(&INDICES),
            GL_STATIC_DRAW,
        );

        glVertexAttribPointer(
            0,
            3,
            GL_FLOAT,
            GL_FALSE,
            size_of::<Vertex>().try_into().unwrap(),
            0 as *const _,
        );
        glEnableVertexAttribArray(0);

        glVertexAttribPointer(
            1,
            2,
            GL_FLOAT,
            GL_FALSE,
            size_of::<Vertex>().try_into().unwrap(),
            12 as *const _,
        );
        glEnableVertexAttribArray(1);

        shader_program =
            ShaderProgram::ShaderProgram::from_vert_frag(VERT_SHADER, FRAG_SHADER).unwrap();
        shader_program.use_program();
        //LOAD TEXTURE
        unsafe {
            let mut width: i32 = 0;
            let mut height: i32 = 0;
            let mut nrChannels: i32 = 0;
            let p = CString::new("../res/tree.png").unwrap();
            let path: *const c_char = p.as_ptr() as *const c_char;

            let _data: *mut u8 = stbi_load(path, &mut width, &mut height, &mut nrChannels, 0);

            glGenTextures(1, &mut tex);
            glBindTexture(GL_TEXTURE_2D, tex);

            glTexParameteri(
                GL_TEXTURE_2D,
                GL_TEXTURE_WRAP_S,
                GL_MIRRORED_REPEAT.try_into().unwrap(),
            );
            glTexParameteri(
                GL_TEXTURE_2D,
                GL_TEXTURE_WRAP_T,
                GL_MIRRORED_REPEAT.try_into().unwrap(),
            );
            glTexParameteri(
                GL_TEXTURE_2D,
                GL_TEXTURE_MIN_FILTER,
                GL_LINEAR_MIPMAP_LINEAR.try_into().unwrap(),
            );
            glTexParameteri(
                GL_TEXTURE_2D,
                GL_TEXTURE_MAG_FILTER,
                GL_LINEAR.try_into().unwrap(),
            );

            glTexImage2D(
                GL_TEXTURE_2D,
                0,
                GL_RGB8 as i32,
                width as i32,
                height as i32,
                0,
                GL_RGB,
                GL_UNSIGNED_BYTE,
                _data as *const u8 as *const libc::c_void,
            );
            glGenerateMipmap(GL_TEXTURE_2D);
            glBindTexture(GL_TEXTURE_2D, 0);

            stbi_image_free(_data as *const u8 as *mut libc::c_void);
        }
    }

    polygon_mode::polygon_mode(polygon_mode::PolygonMode::Fill);

    'main_loop: loop {
        // handle events this frame
        while let Some(event) = sdl.poll_events().and_then(Result::ok) {
            match event {
                Event::Quit(_) => break 'main_loop,
                _ => (),
            }
        }

        unsafe {
            glClearColor(0.2, 0.3, 0.3, 1.0);
            glClear(GL_COLOR_BUFFER_BIT);
            shader_program.use_program();
            vao.bind();
            glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0 as *const _);
        }
        win.swap_window();
    }

    vao.clear_binding();
}

Upvotes: 1

Views: 390

Answers (1)

Rabbid76
Rabbid76

Reputation: 210890

They only have 3 vertices but indices from 0 to 3. You must also specify the 4th vertex coordinate:

const VERTICES: [Vertex; 4] = [
    [0.5, 0.5, 0.0, 0.5, 0.5],
    [0.5, -0.5, 0.0, 0.5, -0.5],
    [-0.5, -0.5, 0.0, -0.5, -0.5],
    [-0.5, 0.5, 0.0, -0.5, 0.5],
];

const INDICES: [TriIndexes; 2] = [[0, 1, 2], [0, 2, 3]];

Upvotes: 1

Related Questions