1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
// Copyright 2016 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#[macro_use]
extern crate log;
extern crate sdl2;
extern crate gfx_core as core;
extern crate gfx_device_gl;

use core::handle;
use core::format::{ChannelType, DepthFormat, Format, RenderFormat};
pub use gfx_device_gl::{Device, Factory, Resources};
use sdl2::video::{DisplayMode, GLContext, Window, WindowBuilder, WindowBuildError};
use sdl2::pixels::PixelFormatEnum;

#[derive(Debug)]
pub enum InitError {
    PixelFormatUnsupportedError,
    WindowBuildError(WindowBuildError),
    SdlError(String),
}

impl From<String> for InitError {
    fn from(e: String) -> Self {
        InitError::SdlError(e)
    }
}

impl From<WindowBuildError> for InitError {
    fn from(e: WindowBuildError) -> Self {
        InitError::WindowBuildError(e)
    }
}

fn sdl2_pixel_format_from_gfx(format: Format) -> Option<PixelFormatEnum> {
    use core::format::SurfaceType::*;
    use sdl2::pixels::PixelFormatEnum as SdlFmt;

    let Format(surface, _) = format;

    match surface {
        R4_G4_B4_A4 => Some(SdlFmt::RGBA4444),
        R5_G5_B5_A1 => Some(SdlFmt::RGBA5551),
        R5_G6_B5 => Some(SdlFmt::RGB565),
        R8_G8_B8_A8 => Some(SdlFmt::RGBA8888),
        B8_G8_R8_A8 => Some(SdlFmt::BGRA8888),
        R10_G10_B10_A2 => {
            warn!("The transfer operations with this format may produce different results on SDL \
                   compared to Glutin/GLFW, beware!");
            Some(SdlFmt::ARGB2101010)
        }
        R4_G4 | R8 | R8_G8 | R11_G11_B10 | R16 | R16_G16 | R16_G16_B16 |
        R16_G16_B16_A16 | R32 | R32_G32 | R32_G32_B32 | R32_G32_B32_A32 | D16 | D24 |
        D24_S8 | D32 => None,
    }
}

pub type InitRawOk = (Window, GLContext, Device, Factory,
    handle::RawRenderTargetView<Resources>, handle::RawDepthStencilView<Resources>);

pub type InitOk<Cf, Df> =
    (Window, GLContext, Device, Factory,
     handle::RenderTargetView<Resources, Cf>,
     handle::DepthStencilView<Resources, Df>);

/// Builds an SDL2 window from a WindowBuilder struct.
///
/// # Example
///
/// ```no_run
/// extern crate gfx_window_sdl;
/// extern crate sdl2;
///
/// fn main() {
///     let sdl = sdl2::init().unwrap();
///
///     let builder = sdl.video().unwrap().window("Example", 800, 600);
///     let (window, glcontext, device, factory, color_view, depth_view) =
///         gfx_window_sdl::init(builder).expect("gfx_window_sdl::init failed!");
///
///     // some code...
/// }
/// ```
pub fn init<Cf, Df>(builder: WindowBuilder) -> Result<InitOk<Cf, Df>, InitError>
where
    Cf: RenderFormat,
    Df: DepthFormat,
{
    use core::memory::Typed;
    init_raw(builder, Cf::get_format(), Df::get_format())
        .map(|(w, gl, d, f, color_view, ds_view)|
            (w, gl, d, f, Typed::new(color_view), Typed::new(ds_view)))
}

pub fn init_raw(mut builder: WindowBuilder, cf: Format, df: Format)
                -> Result<InitRawOk, InitError> {
    use core::texture::{AaMode, Size};

    let mut window = builder.opengl().build()?;

    let display_mode = DisplayMode {
        format: sdl2_pixel_format_from_gfx(cf)
                    .ok_or(InitError::PixelFormatUnsupportedError)?,
        ..window.display_mode()?
    };
    window.set_display_mode((Some(display_mode)))?;
    {
        let depth_total_bits = df.0.get_total_bits();
        let stencil_bits = df.0.get_alpha_stencil_bits();
        let attr = window.subsystem().gl_attr();
        attr.set_framebuffer_srgb_compatible(cf.1 == ChannelType::Srgb);
        attr.set_alpha_size(cf.0.get_alpha_stencil_bits());
        attr.set_depth_size(depth_total_bits - stencil_bits);
        attr.set_stencil_size(stencil_bits);
        attr.set_context_flags().set();
    }

    let context = window.gl_create_context()?;

    let (device, factory) = gfx_device_gl::create(|s| {
        window.subsystem().gl_get_proc_address(s) as *const std::os::raw::c_void
    });

    let (width, height) = window.drawable_size();
    let dim = (width as Size, height as Size, 1, AaMode::Single);
    let (color_view, ds_view) = gfx_device_gl::create_main_targets_raw(dim, cf.0, df.0);

    Ok((window, context, device, factory, color_view, ds_view))
}