Sdl2 code abstraction

I'm trying to export my OpenGL game to Rust. I created blueish window based on this example - https://github.com/Rust-SDL2/rust-sdl2#use-opengl-calls-manually, but when I try to separate my code into different strutcs window is white.

main function:

mod program;

extern crate sdl2;
extern crate gl;
extern crate nalgebra_glm as glm;

use program::*;

fn main() {

    let program: Program = Program::new();
    let mut event_pump = program.sdl.event_pump().unwrap();
    
    'main: loop {
        for event in event_pump.poll_iter() {
            match event {
                sdl2::event::Event::Quit {..} => { break 'main },
                _ => {},
            }
        }

        unsafe {
            gl::Clear(gl::COLOR_BUFFER_BIT);
        }
        
       program.window.gl_swap_window();
    }
}

program file:

extern crate sdl2;
extern crate gl;
extern crate nalgebra_glm as glm;

use std::ffi::CStr;

pub struct Program{
    pub sdl: sdl2::Sdl,
    pub video_subsystem: sdl2::VideoSubsystem,
    pub window: sdl2::video::Window,
}

impl Program{

    pub fn new() -> Program{

        let sdl = sdl2::init().unwrap();
        let video_subsystem = sdl.video().unwrap();
        let window = video_subsystem.window("Game", 900, 700).opengl().resizable().build().unwrap();

        let program = Program{
            sdl: sdl,
            video_subsystem: video_subsystem,
            window: window,
        };

        let _gl_attr = program.video_subsystem.gl_attr();
        _gl_attr.set_context_profile(sdl2::video::GLProfile::Core);
        _gl_attr.set_context_version(4, 5);
    
        let _gl_context = program.window.gl_create_context().unwrap();
        let _gl = gl::load_with(|s| program.video_subsystem.gl_get_proc_address(s) as *const std::os::raw::c_void);
    
        unsafe {
            let version = CStr::from_ptr( gl::GetString(gl::VERSION) as *const i8 ).to_string_lossy();
            let renderer = CStr::from_ptr( gl::GetString(gl::RENDERER) as *const i8 ).to_string_lossy();
            println!("Program start!\n GPU: {} \n GL: {} ", renderer , version);
        
            gl::Enable(gl::DEPTH_TEST); 
            gl::Viewport(0, 0, 900, 700); 
            gl::ClearColor(0.3, 0.3, 0.9, 1.0);
        }

        program
    }
}

I have no idea where the problem is.

You aren't storing the GLContext returned by program.window.gl_create_context().unwrap() anywhere, so it gets dropped at the end of
Program::new. You should store this as a field in Program.

Thank you

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.