Pure opengl app on winit + gl crashes on startup

I am trying to implement opengl application. For this purpose I want to use winit (to draw windows) and gl to render things within generated window. I do not want to use gluten and similar crates because want to keep application low-level and avoid a lot of abstract levels.

So, for now my application generates window, which hangs few seconds and exits. I see no errors in console except this:

process didn't exit successfully: (exit code: 0xc0000005, STATUS_ACCESS_VIOLATION)

I use cargo run to start my app.

This is my code:

extern crate gl;

use std::os::raw::c_void;
use winit::event::{Event, WindowEvent};
use winit::event_loop::{ControlFlow, EventLoop};
use winit::window::WindowBuilder;

fn main() {
    let event_loop = EventLoop::new();
    let mut window = WindowBuilder::new().build(&event_loop).unwrap();
    
    // https://stackoverflow.com/a/24191977/5397119
    let pointer: *mut c_void = &mut window as *mut _ as *mut c_void;

    gl::load_with(|s| pointer);

    event_loop.run(move |event, _, control_flow| {
        *control_flow = ControlFlow::Wait;

        match event {
            Event::WindowEvent {
                event: WindowEvent::CloseRequested,
                window_id,
            } if window_id == window.id() => *control_flow = ControlFlow::Exit,
            _ => unsafe {
                let program: gl::types::GLuint = 1;
                let mut buffer: gl::types::GLuint = 0;

                gl::ClearColor(0.0, 0.0, 0.0, 0.0);
                gl::Clear(gl::COLOR_BUFFER_BIT);

                gl::UseProgram(program);

                gl::GenBuffers(1, &mut buffer);

                gl::BindBuffer(gl::ARRAY_BUFFER, buffer);
                gl::EnableVertexAttribArray(0);
                gl::VertexAttribPointer(0, 4, gl::FLOAT, gl::FALSE, 0, 0 as *const c_void);

                gl::DrawArrays(gl::TRIANGLES, 0, 3);

                gl::DisableVertexAttribArray(0);
                gl::UseProgram(0);
            },
        }
    });
}

Could somebody help me to get what I did wrong ?

You need a library to bridge the gap between OpenGL and the window system you're using. winit on it's own doesn't provide that, and it's rare that you will want to write it yourself unless you have very specific needs.

glutin provides a bridge, as does glfw though you'll have to install the GLFW library yourself if you go for that option since the crate is just a wrapper around the C library.

The specific problem you're hitting is that load_with is supposed to map OpenGL function names to implementations, but you're just returning a pointer to the winit window on the stack. So you're getting a segmentation fault when the OpenGL implementation tries to use that pointer how it expects to be able to.

2 Likes

as @semicoleon mentioned, winit is not equipped for use directly with OpenGL. The same team behind it also created glutin for that purpose.

You can use the gl_loader crate to load gl functions with gl::load_with:

gl_loader::init_gl();
gl::load_with(|symbol| gl_loader::get_proc_address(symbol) as *const _);

however you'll still hit a wall since winit doesn't create a Gl context nor makes it current. You could manually create a context by calling platform specific functions (like glxCreateContext and wglCreateContext) on the raw window handle of the winit window, but why do that when glutin already does all the necessary work for you.

2 Likes

Documentation for glutin seems a bit messy for me. And example for window init from their repo is pretty verbose. Could you advice glutin less-verbose alternative for creating window which I can use next with gl::load_with function ? Or probably there another less-verbose approach exists provided by glutin itself ?

P.S. the most difficult I faced is breaking changes in latest glutin version. I checked a lot of other libraries/crates built on glutin and there pretty different API (for example, glutin there provides glutin::WindowBuilder). And for latest glutin I found only one example. In their repo.

Generally speaking, no. If you want to write all the platform-dependent code to create a GL context yourself, that code is likely going to be even more complicated than just using glutin.

1 Like

Could you explain what can I do within |configs| {...} closure ? It's not clear according to the example and docs of latest version

There may be multiple rendering devices, or sets of incompatible options for a single rendering device. Configs let you pick the configuration that best suits your needs. One of the primary options that a config lets you pick is the format of the pixels that the context will use.

Here's the list of configs I get when I run the example, printing out all of the options exposed by the config
[
    ConfigInfo {
        color_buffer_type: Some(
            Rgb {
                r_size: 8,
                g_size: 8,
                b_size: 8,
            },
        ),
        float_pixels: false,
        alpha_size: 8,
        depth_size: 24,
        stencil_size: 8,
        num_samples: 0,
        srgb_capable: true,
        supports_transparency: Some(
            false,
        ),
        hardware_accelerated: true,
        config_surface_types: WINDOW,
        api: OPENGL | GLES1 | GLES2,
    },
    ConfigInfo {
        color_buffer_type: Some(
            Rgb {
                r_size: 8,
                g_size: 8,
                b_size: 8,
            },
        ),
        float_pixels: false,
        alpha_size: 8,
        depth_size: 24,
        stencil_size: 8,
        num_samples: 0,
        srgb_capable: true,
        supports_transparency: Some(
            false,
        ),
        hardware_accelerated: true,
        config_surface_types: WINDOW,
        api: OPENGL | GLES1 | GLES2,
    },
    ConfigInfo {
        color_buffer_type: Some(
            Rgb {
                r_size: 8,
                g_size: 8,
                b_size: 8,
            },
        ),
        float_pixels: false,
        alpha_size: 8,
        depth_size: 24,
        stencil_size: 8,
        num_samples: 0,
        srgb_capable: true,
        supports_transparency: Some(
            false,
        ),
        hardware_accelerated: true,
        config_surface_types: WINDOW,
        api: OPENGL | GLES1 | GLES2,
    },
    ConfigInfo {
        color_buffer_type: Some(
            Rgb {
                r_size: 8,
                g_size: 8,
                b_size: 8,
            },
        ),
        float_pixels: false,
        alpha_size: 8,
        depth_size: 24,
        stencil_size: 8,
        num_samples: 2,
        srgb_capable: true,
        supports_transparency: Some(
            false,
        ),
        hardware_accelerated: true,
        config_surface_types: WINDOW,
        api: OPENGL | GLES1 | GLES2,
    },
    ConfigInfo {
        color_buffer_type: Some(
            Rgb {
                r_size: 8,
                g_size: 8,
                b_size: 8,
            },
        ),
        float_pixels: false,
        alpha_size: 8,
        depth_size: 24,
        stencil_size: 8,
        num_samples: 2,
        srgb_capable: false,
        supports_transparency: Some(
            false,
        ),
        hardware_accelerated: true,
        config_surface_types: WINDOW,
        api: OPENGL | GLES1 | GLES2,
    },
    ConfigInfo {
        color_buffer_type: Some(
            Rgb {
                r_size: 8,
                g_size: 8,
                b_size: 8,
            },
        ),
        float_pixels: false,
        alpha_size: 8,
        depth_size: 32,
        stencil_size: 8,
        num_samples: 0,
        srgb_capable: false,
        supports_transparency: Some(
            false,
        ),
        hardware_accelerated: false,
        config_surface_types: WINDOW,
        api: OPENGL | GLES1 | GLES2,
    },
    ConfigInfo {
        color_buffer_type: Some(
            Rgb {
                r_size: 8,
                g_size: 8,
                b_size: 8,
            },
        ),
        float_pixels: false,
        alpha_size: 8,
        depth_size: 24,
        stencil_size: 8,
        num_samples: 4,
        srgb_capable: true,
        supports_transparency: Some(
            false,
        ),
        hardware_accelerated: true,
        config_surface_types: WINDOW,
        api: OPENGL | GLES1 | GLES2,
    },
    ConfigInfo {
        color_buffer_type: Some(
            Rgb {
                r_size: 8,
                g_size: 8,
                b_size: 8,
            },
        ),
        float_pixels: false,
        alpha_size: 8,
        depth_size: 24,
        stencil_size: 8,
        num_samples: 4,
        srgb_capable: false,
        supports_transparency: Some(
            false,
        ),
        hardware_accelerated: true,
        config_surface_types: WINDOW,
        api: OPENGL | GLES1 | GLES2,
    },
    ConfigInfo {
        color_buffer_type: Some(
            Rgb {
                r_size: 8,
                g_size: 8,
                b_size: 8,
            },
        ),
        float_pixels: false,
        alpha_size: 8,
        depth_size: 24,
        stencil_size: 8,
        num_samples: 4,
        srgb_capable: true,
        supports_transparency: Some(
            false,
        ),
        hardware_accelerated: true,
        config_surface_types: WINDOW,
        api: OPENGL | GLES1 | GLES2,
    },
    ConfigInfo {
        color_buffer_type: Some(
            Rgb {
                r_size: 8,
                g_size: 8,
                b_size: 8,
            },
        ),
        float_pixels: false,
        alpha_size: 8,
        depth_size: 24,
        stencil_size: 8,
        num_samples: 8,
        srgb_capable: true,
        supports_transparency: Some(
            false,
        ),
        hardware_accelerated: true,
        config_surface_types: WINDOW,
        api: OPENGL | GLES1 | GLES2,
    },
    ConfigInfo {
        color_buffer_type: Some(
            Rgb {
                r_size: 8,
                g_size: 8,
                b_size: 8,
            },
        ),
        float_pixels: false,
        alpha_size: 8,
        depth_size: 24,
        stencil_size: 8,
        num_samples: 8,
        srgb_capable: false,
        supports_transparency: Some(
            false,
        ),
        hardware_accelerated: true,
        config_surface_types: WINDOW,
        api: OPENGL | GLES1 | GLES2,
    },
    ConfigInfo {
        color_buffer_type: Some(
            Rgb {
                r_size: 8,
                g_size: 8,
                b_size: 8,
            },
        ),
        float_pixels: false,
        alpha_size: 8,
        depth_size: 24,
        stencil_size: 8,
        num_samples: 8,
        srgb_capable: true,
        supports_transparency: Some(
            false,
        ),
        hardware_accelerated: true,
        config_surface_types: WINDOW,
        api: OPENGL | GLES1 | GLES2,
    },
    ConfigInfo {
        color_buffer_type: Some(
            Rgb {
                r_size: 8,
                g_size: 8,
                b_size: 8,
            },
        ),
        float_pixels: false,
        alpha_size: 8,
        depth_size: 24,
        stencil_size: 8,
        num_samples: 16,
        srgb_capable: false,
        supports_transparency: Some(
            false,
        ),
        hardware_accelerated: true,
        config_surface_types: WINDOW,
        api: OPENGL | GLES1 | GLES2,
    },
    ConfigInfo {
        color_buffer_type: Some(
            Rgb {
                r_size: 8,
                g_size: 8,
                b_size: 8,
            },
        ),
        float_pixels: false,
        alpha_size: 8,
        depth_size: 24,
        stencil_size: 8,
        num_samples: 16,
        srgb_capable: true,
        supports_transparency: Some(
            false,
        ),
        hardware_accelerated: true,
        config_surface_types: WINDOW,
        api: OPENGL | GLES1 | GLES2,
    },
]

I reorganized the example a bit, to hopefully make it easier to see how to adapt it to your needs. I moved all of the window and context initialization into a Graphics struct, which is used in the main function. I also tweaked some of the cfgs so you don't need the build script, and used the gl crate rather then the binding generator that the example was using. You should be able to get a working context without tweaking the config selection for simple things, but it should be relatively straightforward to choose a different config if you end up needing to.

Cargo.toml

...
[dependencies]
glutin = "0.30.6"
raw-window-handle = "0.5.0"
glutin-winit = "0.3.0"
gl = "0.14.0"
winit = "0.28.1"
main.rs
use std::ffi::{CStr, CString};
use std::num::NonZeroU32;

use winit::event::{Event, WindowEvent};
use winit::event_loop::{EventLoop, EventLoopBuilder};
use winit::window::{Window, WindowBuilder};

use raw_window_handle::HasRawWindowHandle;

use glutin::config::{Api, ColorBufferType, Config, ConfigSurfaceTypes, ConfigTemplateBuilder};
use glutin::context::{ContextApi, ContextAttributesBuilder, NotCurrentContext, Version};
use glutin::display::GetGlDisplay;
use glutin::prelude::*;
use glutin::surface::SwapInterval;

use glutin_winit::{self, DisplayBuilder, GlWindow};

pub fn main() {
    let event_loop = EventLoopBuilder::new().build();

    let mut graphics = Graphics::new(&event_loop);
    let gl_display = graphics.gl_config.display();

    let mut state = None;
    let mut renderer = None;
    event_loop.run(move |event, window_target, control_flow| {
        control_flow.set_wait();
        match event {
            Event::Resumed => {
                #[cfg(target_os = "android")]
                println!("Android window available");

                let window = graphics.window.take().unwrap_or_else(|| {
                    let window_builder = WindowBuilder::new().with_transparent(true);
                    glutin_winit::finalize_window(
                        window_target,
                        window_builder,
                        &graphics.gl_config,
                    )
                    .unwrap()
                });

                let attrs = window.build_surface_attributes(<_>::default());
                let gl_surface = unsafe {
                    graphics
                        .gl_config
                        .display()
                        .create_window_surface(&graphics.gl_config, &attrs)
                        .unwrap()
                };

                // Make it current.
                let gl_context = graphics
                    .not_current_gl_context
                    .take()
                    .unwrap()
                    .make_current(&gl_surface)
                    .unwrap();

                // The context needs to be current for the Renderer to set up shaders and
                // buffers. It also performs function loading, which needs a current context on
                // Wgl::
                renderer.get_or_insert_with(|| Renderer::new(&gl_display));

                // Try setting vsync.
                if let Err(res) = gl_surface
                    .set_swap_interval(&gl_context, SwapInterval::Wait(NonZeroU32::new(1).unwrap()))
                {
                    eprintln!("Error setting vsync: {res:?}");
                }

                assert!(state.replace((gl_context, gl_surface, window)).is_none());
            }
            Event::Suspended => {
                // This event is only raised on Android, where the backing NativeWindow for a GL
                // Surface can appear and disappear at any moment.
                println!("Android window removed");

                // Destroy the GL Surface and un-current the GL Context before ndk-glue releases
                // the window back to the system.
                let (gl_context, ..) = state.take().unwrap();
                assert!(graphics
                    .not_current_gl_context
                    .replace(gl_context.make_not_current().unwrap())
                    .is_none());
            }
            Event::WindowEvent { event, .. } => match event {
                WindowEvent::Resized(size) => {
                    if size.width != 0 && size.height != 0 {
                        // Some platforms like EGL require resizing GL surface to update the size
                        // Notable platforms here are Wayland and macOS, other don't require it
                        // and the function is no-op, but it's wise to resize it for portability
                        // reasons.
                        if let Some((gl_context, gl_surface, _)) = &state {
                            gl_surface.resize(
                                gl_context,
                                NonZeroU32::new(size.width).unwrap(),
                                NonZeroU32::new(size.height).unwrap(),
                            );
                            let renderer = renderer.as_ref().unwrap();
                            renderer.resize(size.width as i32, size.height as i32);
                        }
                    }
                }
                WindowEvent::CloseRequested => {
                    control_flow.set_exit();
                }
                _ => (),
            },
            Event::RedrawEventsCleared => {
                if let Some((gl_context, gl_surface, window)) = &state {
                    let renderer = renderer.as_ref().unwrap();
                    renderer.draw();
                    window.request_redraw();

                    gl_surface.swap_buffers(gl_context).unwrap();
                }
            }
            _ => (),
        }
    })
}

struct Graphics {
    window: Option<Window>,
    gl_config: Config,
    not_current_gl_context: Option<NotCurrentContext>,
}

impl Graphics {
    pub fn new(event_loop: &EventLoop<()>) -> Self {
        // Only windows requires the window to be present before creating the display.
        // Other platforms don't really need one.
        //
        // XXX if you don't care about running on android or so you can safely remove
        // this condition and always pass the window builder.
        let window_builder = if cfg!(windows) {
            Some(WindowBuilder::new().with_transparent(true))
        } else {
            None
        };

        // The template will match only the configurations supporting rendering
        // to windows.
        //
        // XXX We force transparency only on macOS, given that EGL on X11 doesn't
        // have it, but we still want to show window. The macOS situation is like
        // that, because we can query only one config at a time on it, but all
        // normal platforms will return multiple configs, so we can find the config
        // with transparency ourselves inside the `reduce`.
        let template = ConfigTemplateBuilder::new()
            .with_alpha_size(8)
            .with_transparency(cfg!(target_os = "macos"));

        let display_builder = DisplayBuilder::new().with_window_builder(window_builder);

        let (window, gl_config) = display_builder
            .build(event_loop, template, |configs| {
                let configs: Vec<_> = configs.collect();

                #[derive(Debug)]
                #[allow(unused)]
                struct ConfigInfo {
                    color_buffer_type: Option<ColorBufferType>,
                    float_pixels: bool,
                    alpha_size: u8,
                    depth_size: u8,
                    stencil_size: u8,
                    num_samples: u8,
                    srgb_capable: bool,
                    supports_transparency: Option<bool>,
                    hardware_accelerated: bool,
                    config_surface_types: ConfigSurfaceTypes,
                    api: Api,
                }
                println!(
                    "{:#?}",
                    configs
                        .iter()
                        .map(|c| ConfigInfo {
                            color_buffer_type: c.color_buffer_type(),
                            float_pixels: c.float_pixels(),
                            alpha_size: c.alpha_size(),
                            depth_size: c.depth_size(),
                            stencil_size: c.stencil_size(),
                            num_samples: c.num_samples(),
                            srgb_capable: c.srgb_capable(),
                            supports_transparency: c.supports_transparency(),
                            hardware_accelerated: c.hardware_accelerated(),
                            config_surface_types: c.config_surface_types(),
                            api: c.api()
                        })
                        .collect::<Vec<_>>()
                );
                // Find the config with the maximum number of samples, so our triangle will
                // be smooth.
                configs
                    .into_iter()
                    .reduce(|accum, config| {
                        let transparency_check = config.supports_transparency().unwrap_or(false)
                            & !accum.supports_transparency().unwrap_or(false);

                        if transparency_check || config.num_samples() > accum.num_samples() {
                            config
                        } else {
                            accum
                        }
                    })
                    .unwrap()
            })
            .unwrap();

        println!("Picked a config with {} samples", gl_config.num_samples());

        let raw_window_handle = window.as_ref().map(|window| window.raw_window_handle());

        // XXX The display could be obtained from the any object created by it, so we
        // can query it from the config.
        let gl_display = gl_config.display();

        // The context creation part. It can be created before surface and that's how
        // it's expected in multithreaded + multiwindow operation mode, since you
        // can send NotCurrentContext, but not Surface.
        let context_attributes = ContextAttributesBuilder::new().build(raw_window_handle);

        // Since glutin by default tries to create OpenGL core context, which may not be
        // present we should try gles.
        let fallback_context_attributes = ContextAttributesBuilder::new()
            .with_context_api(ContextApi::Gles(None))
            .build(raw_window_handle);

        // There are also some old devices that support neither modern OpenGL nor GLES.
        // To support these we can try and create a 2.1 context.
        let legacy_context_attributes = ContextAttributesBuilder::new()
            .with_context_api(ContextApi::OpenGl(Some(Version::new(2, 1))))
            .build(raw_window_handle);

        let not_current_gl_context = Some(unsafe {
            gl_display
                .create_context(&gl_config, &context_attributes)
                .unwrap_or_else(|_| {
                    gl_display
                        .create_context(&gl_config, &fallback_context_attributes)
                        .unwrap_or_else(|_| {
                            gl_display
                                .create_context(&gl_config, &legacy_context_attributes)
                                .expect("failed to create context")
                        })
                })
        });

        Self {
            window,
            gl_config,
            not_current_gl_context,
        }
    }
}

pub struct Renderer {
    program: gl::types::GLuint,
    vao: gl::types::GLuint,
    vbo: gl::types::GLuint,
}

impl Renderer {
    pub fn new<D: GlDisplay>(gl_display: &D) -> Self {
        unsafe {
            gl::load_with(|symbol| {
                let symbol = CString::new(symbol).unwrap();
                gl_display.get_proc_address(symbol.as_c_str()).cast()
            });

            if let Some(renderer) = get_gl_string(gl::RENDERER) {
                println!("Running on {}", renderer.to_string_lossy());
            }
            if let Some(version) = get_gl_string(gl::VERSION) {
                println!("OpenGL Version {}", version.to_string_lossy());
            }

            if let Some(shaders_version) = get_gl_string(gl::SHADING_LANGUAGE_VERSION) {
                println!("Shaders version on {}", shaders_version.to_string_lossy());
            }

            let vertex_shader = create_shader(gl::VERTEX_SHADER, VERTEX_SHADER_SOURCE);
            let fragment_shader = create_shader(gl::FRAGMENT_SHADER, FRAGMENT_SHADER_SOURCE);

            let program = gl::CreateProgram();

            gl::AttachShader(program, vertex_shader);
            gl::AttachShader(program, fragment_shader);

            gl::LinkProgram(program);

            gl::UseProgram(program);

            gl::DeleteShader(vertex_shader);
            gl::DeleteShader(fragment_shader);

            let mut vao = std::mem::zeroed();
            gl::GenVertexArrays(1, &mut vao);
            gl::BindVertexArray(vao);

            let mut vbo = std::mem::zeroed();
            gl::GenBuffers(1, &mut vbo);
            gl::BindBuffer(gl::ARRAY_BUFFER, vbo);
            gl::BufferData(
                gl::ARRAY_BUFFER,
                (VERTEX_DATA.len() * std::mem::size_of::<f32>()) as gl::types::GLsizeiptr,
                VERTEX_DATA.as_ptr() as *const _,
                gl::STATIC_DRAW,
            );

            let pos_attrib = gl::GetAttribLocation(program, b"position\0".as_ptr() as *const _);
            let color_attrib = gl::GetAttribLocation(program, b"color\0".as_ptr() as *const _);
            gl::VertexAttribPointer(
                pos_attrib as gl::types::GLuint,
                2,
                gl::FLOAT,
                0,
                5 * std::mem::size_of::<f32>() as gl::types::GLsizei,
                std::ptr::null(),
            );
            gl::VertexAttribPointer(
                color_attrib as gl::types::GLuint,
                3,
                gl::FLOAT,
                0,
                5 * std::mem::size_of::<f32>() as gl::types::GLsizei,
                (2 * std::mem::size_of::<f32>()) as *const () as *const _,
            );
            gl::EnableVertexAttribArray(pos_attrib as gl::types::GLuint);
            gl::EnableVertexAttribArray(color_attrib as gl::types::GLuint);

            Self { program, vao, vbo }
        }
    }

    pub fn draw(&self) {
        unsafe {
            gl::UseProgram(self.program);

            gl::BindVertexArray(self.vao);
            gl::BindBuffer(gl::ARRAY_BUFFER, self.vbo);

            gl::ClearColor(0.1, 0.1, 0.1, 0.9);
            gl::Clear(gl::COLOR_BUFFER_BIT);
            gl::DrawArrays(gl::TRIANGLES, 0, 3);
        }
    }

    pub fn resize(&self, width: i32, height: i32) {
        unsafe {
            gl::Viewport(0, 0, width, height);
        }
    }
}

impl Drop for Renderer {
    fn drop(&mut self) {
        unsafe {
            gl::DeleteProgram(self.program);
            gl::DeleteBuffers(1, &self.vbo);
            gl::DeleteVertexArrays(1, &self.vao);
        }
    }
}

unsafe fn create_shader(shader: gl::types::GLenum, source: &[u8]) -> gl::types::GLuint {
    let shader = gl::CreateShader(shader);
    gl::ShaderSource(
        shader,
        1,
        [source.as_ptr().cast()].as_ptr(),
        std::ptr::null(),
    );
    gl::CompileShader(shader);
    shader
}

fn get_gl_string(variant: gl::types::GLenum) -> Option<&'static CStr> {
    unsafe {
        let s = gl::GetString(variant);
        (!s.is_null()).then(|| CStr::from_ptr(s.cast()))
    }
}

#[rustfmt::skip]
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,
];

const VERTEX_SHADER_SOURCE: &[u8] = b"
#version 100
precision mediump float;

attribute vec2 position;
attribute vec3 color;

varying vec3 v_color;

void main() {
    gl_Position = vec4(position, 0.0, 1.0);
    v_color = color;
}
\0";

const FRAGMENT_SHADER_SOURCE: &[u8] = b"
#version 100
precision mediump float;

varying vec3 v_color;

void main() {
    gl_FragColor = vec4(v_color, 1.0);
}
\0";
1 Like

thank you for example ! I trying to make same code but with using glow crate (it seems for me more Rusty since it provides snake_cased methods). So I replaced next lines:

gl::load_with(|symbol| {
    let symbol = CString::new(symbol).unwrap();
    gl_display.get_proc_address(symbol.as_c_str()).cast()
});

with:

let gl = Context::from_loader_function(|symbol| {
    let symbol = CString::new(symbol).unwrap();
    gl_display.get_proc_address(symbol.as_c_str()).cast()
});

the error I got is next:

thread 'main' panicked at 'Reading GL_VERSION failed. Make sure there is a valid GL context currently active.'  ...\glow-0.12.1\src\native.rs:33:13

Could you advice what can I do for fix this ?

I ported that example to glow quickly and didn't have any issues. I used

let gl = Context::from_loader_function_cstr(|symbol| gl_display.get_proc_address(symbol))

but replacing that with your code worked fine as well. Something else must be not quite right.

I don't think you can use gl and glow at the same time, so if you were trying to mix the two that might be the problem

glow-ified version of the previous example
use std::ffi::CString;
use std::num::NonZeroU32;

use glow::{Context, HasContext, NativeBuffer, NativeProgram, NativeShader, NativeVertexArray};
use winit::event::{Event, WindowEvent};
use winit::event_loop::{EventLoop, EventLoopBuilder};
use winit::window::{Window, WindowBuilder};

use raw_window_handle::HasRawWindowHandle;

use glutin::config::{Api, ColorBufferType, Config, ConfigSurfaceTypes, ConfigTemplateBuilder};
use glutin::context::{ContextApi, ContextAttributesBuilder, NotCurrentContext, Version};
use glutin::display::GetGlDisplay;
use glutin::prelude::*;
use glutin::surface::SwapInterval;

use glutin_winit::{self, DisplayBuilder, GlWindow};

pub fn main() {
    let event_loop = EventLoopBuilder::new().build();

    let mut graphics = Graphics::new(&event_loop);
    let gl_display = graphics.gl_config.display();

    let mut state = None;
    let mut renderer = None;
    event_loop.run(move |event, window_target, control_flow| {
        control_flow.set_wait();
        match event {
            Event::Resumed => {
                #[cfg(target_os = "android")]
                println!("Android window available");

                let window = graphics.window.take().unwrap_or_else(|| {
                    let window_builder = WindowBuilder::new().with_transparent(true);
                    glutin_winit::finalize_window(
                        window_target,
                        window_builder,
                        &graphics.gl_config,
                    )
                    .unwrap()
                });

                let attrs = window.build_surface_attributes(<_>::default());
                let gl_surface = unsafe {
                    graphics
                        .gl_config
                        .display()
                        .create_window_surface(&graphics.gl_config, &attrs)
                        .unwrap()
                };

                // Make it current.
                let gl_context = graphics
                    .not_current_gl_context
                    .take()
                    .unwrap()
                    .make_current(&gl_surface)
                    .unwrap();

                // The context needs to be current for the Renderer to set up shaders and
                // buffers. It also performs function loading, which needs a current context on
                // Wgl::
                renderer.get_or_insert_with(|| Renderer::new(&gl_display));

                // Try setting vsync.
                if let Err(res) = gl_surface
                    .set_swap_interval(&gl_context, SwapInterval::Wait(NonZeroU32::new(1).unwrap()))
                {
                    eprintln!("Error setting vsync: {res:?}");
                }

                assert!(state.replace((gl_context, gl_surface, window)).is_none());
            }
            Event::Suspended => {
                // This event is only raised on Android, where the backing NativeWindow for a GL
                // Surface can appear and disappear at any moment.
                println!("Android window removed");

                // Destroy the GL Surface and un-current the GL Context before ndk-glue releases
                // the window back to the system.
                let (gl_context, ..) = state.take().unwrap();
                assert!(graphics
                    .not_current_gl_context
                    .replace(gl_context.make_not_current().unwrap())
                    .is_none());
            }
            Event::WindowEvent { event, .. } => match event {
                WindowEvent::Resized(size) => {
                    if size.width != 0 && size.height != 0 {
                        // Some platforms like EGL require resizing GL surface to update the size
                        // Notable platforms here are Wayland and macOS, other don't require it
                        // and the function is no-op, but it's wise to resize it for portability
                        // reasons.
                        if let Some((gl_context, gl_surface, _)) = &state {
                            gl_surface.resize(
                                gl_context,
                                NonZeroU32::new(size.width).unwrap(),
                                NonZeroU32::new(size.height).unwrap(),
                            );
                            let renderer = renderer.as_ref().unwrap();
                            renderer.resize(size.width as i32, size.height as i32);
                        }
                    }
                }
                WindowEvent::CloseRequested => {
                    control_flow.set_exit();
                }
                _ => (),
            },
            Event::RedrawEventsCleared => {
                if let Some((gl_context, gl_surface, window)) = &state {
                    let renderer = renderer.as_ref().unwrap();
                    renderer.draw();
                    window.request_redraw();

                    gl_surface.swap_buffers(gl_context).unwrap();
                }
            }
            _ => (),
        }
    })
}

struct Graphics {
    window: Option<Window>,
    gl_config: Config,
    not_current_gl_context: Option<NotCurrentContext>,
}

impl Graphics {
    pub fn new(event_loop: &EventLoop<()>) -> Self {
        // Only windows requires the window to be present before creating the display.
        // Other platforms don't really need one.
        //
        // XXX if you don't care about running on android or so you can safely remove
        // this condition and always pass the window builder.
        let window_builder = if cfg!(windows) {
            Some(WindowBuilder::new().with_transparent(true))
        } else {
            None
        };

        // The template will match only the configurations supporting rendering
        // to windows.
        //
        // XXX We force transparency only on macOS, given that EGL on X11 doesn't
        // have it, but we still want to show window. The macOS situation is like
        // that, because we can query only one config at a time on it, but all
        // normal platforms will return multiple configs, so we can find the config
        // with transparency ourselves inside the `reduce`.
        let template = ConfigTemplateBuilder::new()
            .with_alpha_size(8)
            .with_transparency(cfg!(target_os = "macos"));

        let display_builder = DisplayBuilder::new().with_window_builder(window_builder);

        let (window, gl_config) = display_builder
            .build(event_loop, template, |configs| {
                let configs: Vec<_> = configs.collect();

                #[derive(Debug)]
                #[allow(unused)]
                struct ConfigInfo {
                    color_buffer_type: Option<ColorBufferType>,
                    float_pixels: bool,
                    alpha_size: u8,
                    depth_size: u8,
                    stencil_size: u8,
                    num_samples: u8,
                    srgb_capable: bool,
                    supports_transparency: Option<bool>,
                    hardware_accelerated: bool,
                    config_surface_types: ConfigSurfaceTypes,
                    api: Api,
                }
                println!(
                    "{:#?}",
                    configs
                        .iter()
                        .map(|c| ConfigInfo {
                            color_buffer_type: c.color_buffer_type(),
                            float_pixels: c.float_pixels(),
                            alpha_size: c.alpha_size(),
                            depth_size: c.depth_size(),
                            stencil_size: c.stencil_size(),
                            num_samples: c.num_samples(),
                            srgb_capable: c.srgb_capable(),
                            supports_transparency: c.supports_transparency(),
                            hardware_accelerated: c.hardware_accelerated(),
                            config_surface_types: c.config_surface_types(),
                            api: c.api()
                        })
                        .collect::<Vec<_>>()
                );
                // Find the config with the maximum number of samples, so our triangle will
                // be smooth.
                configs
                    .into_iter()
                    .reduce(|accum, config| {
                        let transparency_check = config.supports_transparency().unwrap_or(false)
                            & !accum.supports_transparency().unwrap_or(false);

                        if transparency_check || config.num_samples() > accum.num_samples() {
                            config
                        } else {
                            accum
                        }
                    })
                    .unwrap()
            })
            .unwrap();

        println!("Picked a config with {} samples", gl_config.num_samples());

        let raw_window_handle = window.as_ref().map(|window| window.raw_window_handle());

        // XXX The display could be obtained from the any object created by it, so we
        // can query it from the config.
        let gl_display = gl_config.display();

        // The context creation part. It can be created before surface and that's how
        // it's expected in multithreaded + multiwindow operation mode, since you
        // can send NotCurrentContext, but not Surface.
        let context_attributes = ContextAttributesBuilder::new().build(raw_window_handle);

        // Since glutin by default tries to create OpenGL core context, which may not be
        // present we should try gles.
        let fallback_context_attributes = ContextAttributesBuilder::new()
            .with_context_api(ContextApi::Gles(None))
            .build(raw_window_handle);

        // There are also some old devices that support neither modern OpenGL nor GLES.
        // To support these we can try and create a 2.1 context.
        let legacy_context_attributes = ContextAttributesBuilder::new()
            .with_context_api(ContextApi::OpenGl(Some(Version::new(2, 1))))
            .build(raw_window_handle);

        let not_current_gl_context = Some(unsafe {
            gl_display
                .create_context(&gl_config, &context_attributes)
                .unwrap_or_else(|_| {
                    gl_display
                        .create_context(&gl_config, &fallback_context_attributes)
                        .unwrap_or_else(|_| {
                            gl_display
                                .create_context(&gl_config, &legacy_context_attributes)
                                .expect("failed to create context")
                        })
                })
        });

        Self {
            window,
            gl_config,
            not_current_gl_context,
        }
    }
}

pub struct Renderer {
    gl: Context,
    program: NativeProgram,
    vao: NativeVertexArray,
    vbo: NativeBuffer,
}

impl Renderer {
    pub fn new<D: GlDisplay>(gl_display: &D) -> Self {
        unsafe {
            let gl = Context::from_loader_function(|symbol| {
                let symbol = CString::new(symbol).unwrap();
                gl_display.get_proc_address(symbol.as_c_str()).cast()
            });

            println!("Running on {}", get_gl_string(&gl, glow::RENDERER));

            println!("OpenGL Version {}", get_gl_string(&gl, glow::VERSION));

            println!(
                "Shaders version on {}",
                get_gl_string(&gl, glow::SHADING_LANGUAGE_VERSION)
            );

            let vertex_shader = create_shader(&gl, glow::VERTEX_SHADER, VERTEX_SHADER_SOURCE);
            let fragment_shader = create_shader(&gl, glow::FRAGMENT_SHADER, FRAGMENT_SHADER_SOURCE);

            let program = gl.create_program().unwrap();

            gl.attach_shader(program, vertex_shader);
            gl.attach_shader(program, fragment_shader);

            gl.link_program(program);

            gl.use_program(Some(program));

            gl.delete_shader(vertex_shader);
            gl.delete_shader(fragment_shader);

            let vao = gl.create_vertex_array().unwrap();
            gl.bind_vertex_array(Some(vao));

            let vbo = gl.create_buffer().unwrap();
            gl.bind_buffer(glow::ARRAY_BUFFER, Some(vbo));
            gl.buffer_data_u8_slice(
                glow::ARRAY_BUFFER,
                std::slice::from_raw_parts(
                    VERTEX_DATA.as_ptr() as *const _,
                    VERTEX_DATA.len() * core::mem::size_of::<f32>(),
                ),
                glow::STATIC_DRAW,
            );

            let pos_attrib = gl.get_attrib_location(program, "position").unwrap();
            let color_attrib = gl.get_attrib_location(program, "color").unwrap();
            gl.vertex_attrib_pointer_f32(
                pos_attrib,
                2,
                glow::FLOAT,
                false,
                5 * std::mem::size_of::<f32>() as i32,
                0,
            );
            gl.vertex_attrib_pointer_f32(
                color_attrib,
                3,
                glow::FLOAT,
                false,
                5 * std::mem::size_of::<f32>() as i32,
                (2 * std::mem::size_of::<f32>()) as i32,
            );

            gl.enable_vertex_attrib_array(pos_attrib);
            gl.enable_vertex_attrib_array(color_attrib);

            Self {
                gl,
                program,
                vao,
                vbo,
            }
        }
    }

    pub fn draw(&self) {
        unsafe {
            self.gl.use_program(self.program.into());

            self.gl.bind_vertex_array(self.vao.into());
            self.gl.bind_buffer(glow::ARRAY_BUFFER, self.vbo.into());

            self.gl.clear_color(0.1, 0.1, 0.1, 0.9);
            self.gl.clear(glow::COLOR_BUFFER_BIT);
            self.gl.draw_arrays(glow::TRIANGLES, 0, 3);
        }
    }

    pub fn resize(&self, width: i32, height: i32) {
        unsafe {
            self.gl.viewport(0, 0, width, height);
        }
    }
}

impl Drop for Renderer {
    fn drop(&mut self) {
        unsafe {
            self.gl.delete_program(self.program);
            self.gl.delete_buffer(self.vbo);
            self.gl.delete_vertex_array(self.vao)
        }
    }
}

unsafe fn create_shader(gl: &Context, shader: u32, source: &str) -> NativeShader {
    let shader = gl.create_shader(shader).unwrap();
    gl.shader_source(shader, source);
    gl.compile_shader(shader);
    shader
}

fn get_gl_string(gl: &Context, variant: u32) -> String {
    unsafe { gl.get_parameter_string(variant) }
}

#[rustfmt::skip]
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,
];

const VERTEX_SHADER_SOURCE: &str = "
#version 100
precision mediump float;

attribute vec2 position;
attribute vec3 color;

varying vec3 v_color;

void main() {
    gl_Position = vec4(position, 0.0, 1.0);
    v_color = color;
}";

const FRAGMENT_SHADER_SOURCE: &str = "
#version 100
precision mediump float;

varying vec3 v_color;

void main() {
    gl_FragColor = vec4(v_color, 1.0);
}";
1 Like

Thank you very much for detailed explanation !