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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
//! Texture related utilities.

use ::{std, glium, image};

/// An RGBA 16x16 square of pixels with white color values with an opaque cross
/// of two pixels thickness
pub const CROSSHAIR_PNG_FILE_BYTES : &'static [u8; 101]
  = include_bytes!("../crosshair.png");
/// For use with `BLEND_FUNC_INVERT_COLOR`-- transparent pixels have *black*
/// color values instead of white but the opaque portion is still white
pub const CROSSHAIR_INVERSE_PNG_FILE_BYTES : &'static [u8; 95]
  = include_bytes!("../crosshair-inverse.png");
pub const TILESET_EASCII_ACORN_8X8_PNG_FILE_BYTES : &'static [u8; 2538]
  = include_bytes!("../tileset_eascii_acorn-bbc-micro_8x8.png");
pub const TILESET_EASCII_ACORN_8X8_INVERSE_PNG_FILE_BYTES : &'static [u8; 2526]
  = include_bytes!("../tileset_eascii_acorn-bbc-micro_8x8-inverse.png");

#[derive(Debug)]
pub enum LoadError {
  IoError              (std::io::Error),
  ImageError           (image::ImageError),
  TextureCreationError (glium::texture::TextureCreationError)
}

/// Load a 2D texture from the given bytes with the given format and mipmaps.
pub fn texture2d_with_mipmaps_from_bytes (
  glium_facade : &glium::backend::Facade,
  bytes        : &[u8],
  image_format : image::ImageFormat,
  mipmaps      : glium::texture::MipmapsOption
) -> Result <glium::Texture2d, LoadError> {
  let img = {
    let img = try!(image::load_from_memory_with_format (bytes, image_format));
    img.to_rgba()
  };
  let img_dimensions = img.dimensions();
  debug!("texture load bytes image dimensions: {:?}", img_dimensions);
  let raw_image_2d = glium::texture::RawImage2d::from_raw_rgba_reversed (
    img.into_raw().as_slice(),
    img_dimensions);

  glium::Texture2d::with_mipmaps (glium_facade, raw_image_2d, mipmaps)
    .map_err (Into::into)
}

/// Load a 2D texture from the given path with the given format and mipmaps.
pub fn texture2d_with_mipmaps_from_file (
  glium_facade : &glium::backend::Facade,
  filepath     : &'static str,
  image_format : image::ImageFormat,
  mipmaps      : glium::texture::MipmapsOption
) -> Result <glium::Texture2d, LoadError> {
  use std::io::Read;
  debug!("texture load file path: {:?}", filepath);
  let mut file  = try!(std::fs::File::open (filepath));
  let mut bytes = Vec::new();
  let _         = try!(file.read_to_end (&mut bytes));
  texture2d_with_mipmaps_from_bytes (
    glium_facade, bytes.as_slice(), image_format, mipmaps)
}

/// Load a 2D texture array from the given vector of byte slices for each
/// individual texture, with the given format and mipmaps.
pub fn texture2darray_with_mipmaps_from_bytes (
  glium_facade : &glium::backend::Facade,
  bytes_vec    : Vec <&[u8]>,
  image_format : image::ImageFormat,
  mipmaps      : glium::texture::MipmapsOption
) -> Result <glium::texture::Texture2dArray, LoadError> {
  let raw_images = {
    let mut v = Vec::with_capacity (bytes_vec.len());
    for bytes in bytes_vec {
      let img = {
        let img = try!(image::load_from_memory_with_format (
          bytes, image_format));
        img.to_rgba()
      };
      let img_dimensions = img.dimensions();
      debug!("texture array load bytes image dimensions: {:?}", img_dimensions);
      let raw_image_2d = glium::texture::RawImage2d::from_raw_rgba_reversed (
        img.into_raw().as_slice(),
        img_dimensions);
      v.push (raw_image_2d);
    }
    v
  };

  glium::texture::Texture2dArray::with_mipmaps (
    glium_facade, raw_images, mipmaps
  ).map_err (Into::into)
}

/// Load a 2D texture array from the given paths with the given format and
/// mipmaps.
pub fn texture2darray_with_mipmaps_from_files (
  glium_facade : &glium::backend::Facade,
  filepaths    : &Vec <&'static str>,
  image_format : image::ImageFormat,
  mipmaps      : glium::texture::MipmapsOption
) -> Result <glium::texture::Texture2dArray, LoadError> {
  use std::io::Read;

  if filepaths.is_empty() {
    return Err (std::io::Error::new (std::io::ErrorKind::InvalidInput,
      "no input paths provided").into())
  }

  let bytes = {
    let mut v = Vec::with_capacity (filepaths.len());
    v.resize_default (filepaths.len());
    for (i, filepath) in filepaths.iter().enumerate() {
      debug!("texture load filepath: {:?}", filepath);
      let mut file  = try!(std::fs::File::open (filepath));
      let _         = try!(file.read_to_end (&mut v[i]));
    }
    v
  };

  let bytes_vec = {
    let mut v = Vec::with_capacity (filepaths.len());
    for bytes in bytes.iter() {
      v.push (bytes.as_slice());
    }
    v
  };

  let texture2darray = try!(texture2darray_with_mipmaps_from_bytes (
    glium_facade, bytes_vec, image_format, mipmaps));
  // bytes must live until here
  Ok (texture2darray)
}

//
//  impls
//
impl std::fmt::Display for LoadError {
  fn fmt (&self, fmt : &mut std::fmt::Formatter) -> std::fmt::Result {
    match *self {
      LoadError::IoError              (ref err) =>
         write!(fmt, "I/O error: {}", err),
      LoadError::ImageError           (ref err) => err.fmt (fmt),
      LoadError::TextureCreationError (ref err) => err.fmt (fmt)
    }
  }
}

impl std::error::Error for LoadError {
  fn description (&self) -> &str {
    match *self {
      LoadError::IoError              (ref err) => err.description(),
      LoadError::ImageError           (ref err) => err.description(),
      LoadError::TextureCreationError (ref err) => err.description()
    }
  }
  fn cause (&self) -> Option <&std::error::Error> {
    match *self {
      LoadError::IoError              (ref err) => err.cause(),
      LoadError::ImageError           (ref err) => err.cause(),
      LoadError::TextureCreationError (ref err) => err.cause()
    }
  }
}

impl From <std::io::Error> for LoadError {
  fn from (err : std::io::Error) -> Self {
    LoadError::IoError (err)
  }
}

impl From <image::ImageError> for LoadError {
  fn from (err : image::ImageError) -> Self {
    LoadError::ImageError (err)
  }
}

impl From <glium::texture::TextureCreationError> for LoadError {
  fn from (err : glium::texture::TextureCreationError) -> Self {
    LoadError::TextureCreationError (err)
  }
}