limikael / appy

Declarative UI framework in Rust
MIT License
66 stars 2 forks source link

Glium API for SDL2 #23

Closed mrazorvin closed 9 months ago

mrazorvin commented 10 months ago

Hi, thanks for your hard work on appy/glapp/apk-sdl, those crates saves me a lot of time, with "how to run sdl on android and stay sane" problem

Do you have any thoughts on "How to implements Glium API with SDL2?"

I checked Glium source, and it's look like I need to implement custom backed and create my own context with it

mrazorvin commented 9 months ago

I managed to do it by myself,

I forked https://github.com/nukep/glium-sdl2 and rewritten your code with something like this

use sdl2::Sdl;

use crate::glium_sdl2::{DisplayBuild, SDL2Facade};

#[derive(Debug, Clone)]
pub enum AppUnits {
    DeviceIndependent,
    HardwarePixels,
}

impl AppUnits {
    #[allow(unused_parens)]
    pub fn hw_to_units(&self, pixel_ratio: f32, value: f32) -> f32 {
        match self {
            AppUnits::DeviceIndependent => (value / pixel_ratio),
            AppUnits::HardwarePixels => value,
        }
    }

    #[allow(unused_parens)]
    pub fn units_to_hw(&self, pixel_ratio: f32, value: f32) -> f32 {
        match self {
            AppUnits::DeviceIndependent => (value * pixel_ratio),
            AppUnits::HardwarePixels => value,
        }
    }
}

pub struct AppWindow {
    pub display: SDL2Facade,
    pub sdl: Sdl,
}

impl AppWindow {
    pub fn new(title: &str, width: f32, height: f32) -> Self {
        let sdl = sdl2::init().unwrap();
        let video_subsystem = sdl.video().unwrap();

        let mut pixel_ratio = 1.0;
        let dpi = video_subsystem.display_dpi(0).unwrap().0;
        if dpi > 160.0 {
            pixel_ratio = dpi / 160.0;
        }

        let units = AppUnits::HardwarePixels;
        let hw_size = (
            units.units_to_hw(pixel_ratio, width),
            units.units_to_hw(pixel_ratio, height),
        );

        //pixel_ratio=2.0; // debug
        println!("pixel ratio: {:?}", pixel_ratio);

        let display = video_subsystem
            .window(title, hw_size.0 as u32, hw_size.1 as u32)
            .opengl()
            .resizable()
            .build_glium()
            .unwrap();

        Self { display, sdl }
    }
}