#include "stdafx.h"
#include "Texture.h"

#ifdef GUI_WIN32

namespace gui {

	D3DTexture::D3DTexture(Texture *t, ID3D10Device *device) {
		create(t, device);
	}

	void D3DTexture::create(Texture *t, ID3D10Device *device) {
		Engine &e = t->engine();
		Image *i = t->image();

		// TODO: We probably want the ability to render to textures and use them later on. That
		// requires more control over the flags passed here.
		D3D10_TEXTURE2D_DESC desc;
		zeroMem(desc);
		desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
		desc.Width = i->width();
		desc.Height = i->height();
		desc.ArraySize = 1;
		desc.MipLevels = 1;
		desc.BindFlags = D3D10_BIND_SHADER_RESOURCE;
		desc.Usage = D3D10_USAGE_IMMUTABLE;
		desc.CPUAccessFlags = 0; // No CPU access.
		desc.SampleDesc.Count = 1;
		desc.SampleDesc.Quality = 0;
		desc.MiscFlags = 0;

		D3D10_SUBRESOURCE_DATA data = {
			i->buffer(),
			i->stride(),
			0,
		};

		texture.clear();
		HRESULT r = device->CreateTexture2D(&desc, &data, &texture.v);
		verify(e, r, S("Failed to create a device texture: "));

		D3D10_SHADER_RESOURCE_VIEW_DESC viewDesc;
		zeroMem(viewDesc);
		viewDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
		viewDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D;
		viewDesc.Texture2D.MostDetailedMip = 0;
		viewDesc.Texture2D.MipLevels = 1; // Detect somehow?

		view.clear();
		r = device->CreateShaderResourceView(texture.v, &viewDesc, &view.v);
		verify(e, r, S("Failed to create a resource view for a texture: "));
	}

	void D3DTexture::update(Texture *t, const DirtyRange &dirty) {
		ComPtr<ID3D10Device> device;
		texture->GetDevice(&device.v);

		// Just re-create. We might want to do something more intelligent if we support different
		// kinds of textures in the future!
		create(t, device.v);
	}

}

#endif
