+ storage(make_pixelformat(get_components(fmt), get_component_type(fmt), use_srgb_format), w, h, lv);
+ else if(w!=width || h!=height || (lv && lv!=levels))
+ throw incompatible_data("Texture2D::image");
+
+ PixelStore pstore = PixelStore::from_image(img);
+ BindRestore _bind_ps(pstore);
+
+ image(0, from_buffer ? 0 : img.get_pixels());
+}
+
+unsigned Texture2D::get_n_levels() const
+{
+ unsigned n = 0;
+ for(unsigned s=max(width, height); s; s>>=1, ++n) ;
+ return n;
+}
+
+void Texture2D::get_level_size(unsigned level, unsigned &w, unsigned &h) const
+{
+ w >>= level;
+ h >>= level;
+
+ if(!w && h)
+ w = 1;
+ else if(!h && w)
+ h = 1;
+}
+
+Resource::AsyncLoader *Texture2D::load(IO::Seekable &io, const Resources *)
+{
+ AsyncLoader *ldr = new AsyncLoader(*this, io);
+ return ldr;
+}
+
+UInt64 Texture2D::get_data_size() const
+{
+ return id ? width*height*get_pixel_size(format) : 0;
+}
+
+void Texture2D::unload()
+{
+ glDeleteTextures(1, &id);
+ id = 0;
+ allocated = 0;
+ default_sampler.unload();
+}
+
+
+Texture2D::Loader::Loader(Texture2D &t):
+ DataFile::DerivedObjectLoader<Texture2D, Texture::Loader>(t)
+{
+ init();
+}
+
+Texture2D::Loader::Loader(Texture2D &t, Collection &c):
+ DataFile::DerivedObjectLoader<Texture2D, Texture::Loader>(t, c)
+{
+ init();
+}
+
+void Texture2D::Loader::init()
+{
+ add("raw_data", &Loader::raw_data);
+ add("storage", &Loader::storage);
+ add("storage", &Loader::storage_levels);
+}
+
+void Texture2D::Loader::raw_data(const string &data)
+{
+ obj.image(0, data.data());
+}
+
+void Texture2D::Loader::storage(PixelFormat fmt, unsigned w, unsigned h)
+{
+ obj.storage(fmt, w, h);
+}
+
+void Texture2D::Loader::storage_levels(PixelFormat fmt, unsigned w, unsigned h, unsigned l)
+{
+ obj.storage(fmt, w, h, l);
+}
+
+
+Texture2D::AsyncLoader::AsyncLoader(Texture2D &t, IO::Seekable &i):
+ texture(t),
+ io(i),
+ pixel_buffer(PIXEL_UNPACK_BUFFER),
+ mapped_address(0),
+ img_loader(Graphics::ImageLoader::open_io(io)),
+ phase(0)
+{ }
+
+Texture2D::AsyncLoader::~AsyncLoader()
+{
+ if(mapped_address)
+ pixel_buffer.unmap();
+ delete img_loader;
+}
+
+bool Texture2D::AsyncLoader::needs_sync() const
+{
+ return phase%2;
+}
+
+bool Texture2D::AsyncLoader::process()
+{
+ if(phase==0)
+ {
+ image.load_headers(*img_loader);
+ n_bytes = image.get_stride()*image.get_height();
+ }
+ else if(phase==1)
+ {
+ pixel_buffer.storage(n_bytes);
+ mapped_address = reinterpret_cast<char *>(pixel_buffer.map());
+ }
+ else if(phase==2)
+ image.load_into(*img_loader, mapped_address);
+ else if(phase==3)
+ {
+ Bind _bind_buf(pixel_buffer, PIXEL_UNPACK_BUFFER);
+ mapped_address = 0;
+ if(!pixel_buffer.unmap())
+ {
+ phase = 1;
+ return false;
+ }
+
+ if(!texture.id)
+ {
+ if(ARB_direct_state_access)
+ glCreateTextures(texture.target, 1, &texture.id);
+ else
+ glGenTextures(1, &texture.id);
+ }
+ texture.image(image, 0, true);
+ }