d3d11-subsystem.cpp 38.0 KB
Newer Older
J
jp9000 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/******************************************************************************
    Copyright (C) 2013 by Hugh Bailey <obs.jim@gmail.com>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/

#include "util/base.h"
#include "util/platform.h"
#include "graphics/matrix3.h"
21
#include "d3d11-subsystem.hpp"
J
jp9000 已提交
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 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399

static const IID dxgiFactory2 =
{0x50c83a1c, 0xe072, 0x4c48, {0x87, 0xb0, 0x36, 0x30, 0xfa, 0x36, 0xa6, 0xd0}};

static inline void make_swap_desc(DXGI_SWAP_CHAIN_DESC &desc,
		gs_init_data *data)
{
	memset(&desc, 0, sizeof(desc));
	desc.BufferCount       = data->num_backbuffers;
	desc.BufferDesc.Format = ConvertGSTextureFormat(data->format);
	desc.BufferDesc.Width  = data->cx;
	desc.BufferDesc.Height = data->cy;
	desc.BufferUsage       = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	desc.OutputWindow      = (HWND)data->hwnd;
	desc.SampleDesc.Count  = 1;
	desc.Windowed          = true;
}

void gs_swap_chain::InitTarget(uint32_t cx, uint32_t cy)
{
	HRESULT hr;

	target.width  = cx;
	target.height = cy;

	hr = swap->GetBuffer(0, __uuidof(ID3D11Texture2D),
			(void**)target.texture.Assign());
	if (FAILED(hr))
		throw HRError("Failed to get swap buffer texture", hr);

	hr = device->device->CreateRenderTargetView(target.texture, NULL,
			target.renderTarget[0].Assign());
	if (FAILED(hr))
		throw HRError("Failed to create swap render target view", hr);
}

void gs_swap_chain::InitZStencilBuffer(uint32_t cx, uint32_t cy)
{
	zs.width  = cx;
	zs.height = cy;

	if (zs.format != GS_ZS_NONE && cx != 0 && cy != 0) {
		zs.InitBuffer();
	} else {
		zs.texture.Clear();
		zs.view.Clear();
	}
}

void gs_swap_chain::Resize(uint32_t cx, uint32_t cy)
{
	RECT clientRect;
	HRESULT hr;

	target.texture.Clear();
	target.renderTarget[0].Clear();
	zs.texture.Clear();
	zs.view.Clear();

	if (cx == 0 || cy == 0) {
		GetClientRect(hwnd, &clientRect);
		if (cx == 0) cx = clientRect.right;
		if (cy == 0) cy = clientRect.bottom;
	}

	hr = swap->ResizeBuffers(numBuffers, cx, cy, target.dxgiFormat, 0);
	if (FAILED(hr))
		throw HRError("Failed to resize swap buffers", hr);

	InitTarget(cx, cy);
	InitZStencilBuffer(cx, cy);
}

void gs_swap_chain::Init(gs_init_data *data)
{
	target.device         = device;
	target.isRenderTarget = true;
	target.format         = data->format;
	target.dxgiFormat     = ConvertGSTextureFormat(data->format);
	InitTarget(data->cx, data->cy);

	zs.device     = device;
	zs.format     = data->zsformat;
	zs.dxgiFormat = ConvertGSZStencilFormat(data->zsformat);
	InitZStencilBuffer(data->cx, data->cy);
}

gs_swap_chain::gs_swap_chain(gs_device *device, gs_init_data *data)
	: device     (device),
	  numBuffers (data->num_backbuffers),
	  hwnd       ((HWND)data->hwnd)
{
	HRESULT hr;
	DXGI_SWAP_CHAIN_DESC swapDesc;

	make_swap_desc(swapDesc, data);
	hr = device->factory->CreateSwapChain(device->device, &swapDesc,
			swap.Assign());
	if (FAILED(hr))
		throw HRError("Failed to create swap chain", hr);

	Init(data);
}

void gs_device::InitFactory(uint32_t adapterIdx, IDXGIAdapter1 **padapter)
{
	HRESULT hr;
	IID factoryIID = (GetWinVer() >= 0x602) ? dxgiFactory2 :
		__uuidof(IDXGIFactory1);

	hr = CreateDXGIFactory1(factoryIID, (void**)factory.Assign());
	if (FAILED(hr))
		throw HRError("Failed to create DXGIFactory", hr);

	hr = factory->EnumAdapters1(adapterIdx, padapter);
	if (FAILED(hr))
		throw HRError("Failed to enumerate DXGIAdapter", hr);
}

const static D3D_FEATURE_LEVEL featureLevels[] =
{
	D3D_FEATURE_LEVEL_11_0,
	D3D_FEATURE_LEVEL_10_1,
	D3D_FEATURE_LEVEL_10_0,
	D3D_FEATURE_LEVEL_9_3,
};

void gs_device::InitDevice(gs_init_data *data, IDXGIAdapter *adapter)
{
	wstring adapterName;
	DXGI_SWAP_CHAIN_DESC swapDesc;
	DXGI_ADAPTER_DESC desc;
	D3D_FEATURE_LEVEL levelUsed;
	HRESULT hr;

	make_swap_desc(swapDesc, data);

	uint32_t createFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
#ifdef _DEBUG
	createFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif

	adapterName = (adapter->GetDesc(&desc) == S_OK) ? desc.Description :
		L"<unknown>";

	char *adapterNameUTF8;
	os_wcs_to_utf8(adapterName.c_str(), 0, &adapterNameUTF8);
	blog(LOG_INFO, "Loading up D3D11 on adapter %s", adapterNameUTF8);
	bfree(adapterNameUTF8);

	hr = D3D11CreateDeviceAndSwapChain(adapter, D3D_DRIVER_TYPE_UNKNOWN,
			NULL, createFlags, featureLevels,
			sizeof(featureLevels) / sizeof(D3D_FEATURE_LEVEL),
			D3D11_SDK_VERSION, &swapDesc,
			defaultSwap.swap.Assign(), device.Assign(),
			&levelUsed, context.Assign());
	if (FAILED(hr))
		throw HRError("Failed to create device and swap chain", hr);

	blog(LOG_INFO, "D3D11 loaded sucessfully, feature level used: %u",
			(uint32_t)levelUsed);

	defaultSwap.device     = this;
	defaultSwap.hwnd       = (HWND)data->hwnd;
	defaultSwap.numBuffers = data->num_backbuffers;
	defaultSwap.Init(data);
}

static inline void ConvertStencilSide(D3D11_DEPTH_STENCILOP_DESC &desc,
		const StencilSide &side)
{
	desc.StencilFunc        = ConvertGSDepthTest(side.test);
	desc.StencilFailOp      = ConvertGSStencilOp(side.fail);
	desc.StencilDepthFailOp = ConvertGSStencilOp(side.zfail);
	desc.StencilPassOp      = ConvertGSStencilOp(side.zpass);
}

ID3D11DepthStencilState *gs_device::AddZStencilState()
{
	HRESULT hr;
	D3D11_DEPTH_STENCIL_DESC dsd;
	SavedZStencilState savedState(zstencilState);
	ID3D11DepthStencilState *state;

	dsd.DepthEnable      = zstencilState.depthEnabled;
	dsd.DepthFunc        = ConvertGSDepthTest(zstencilState.depthFunc);
	dsd.DepthWriteMask   = zstencilState.depthWriteEnabled ?
		D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO;
	dsd.StencilEnable    = zstencilState.stencilEnabled;
	dsd.StencilReadMask  = D3D11_DEFAULT_STENCIL_READ_MASK;
	dsd.StencilWriteMask = zstencilState.stencilWriteEnabled ?
		D3D11_DEFAULT_STENCIL_WRITE_MASK : 0;
	ConvertStencilSide(dsd.FrontFace, zstencilState.stencilFront);
	ConvertStencilSide(dsd.BackFace,  zstencilState.stencilBack);

	hr = device->CreateDepthStencilState(&dsd, savedState.state.Assign());
	if (FAILED(hr))
		throw HRError("Failed to create depth stencil state", hr);

	state = savedState.state;
	zstencilStates.push_back(savedState);

	return state;
}

ID3D11RasterizerState *gs_device::AddRasterState()
{
	HRESULT hr;
	D3D11_RASTERIZER_DESC rd;
	SavedRasterState savedState(rasterState);
	ID3D11RasterizerState *state;

	memset(&rd, 0, sizeof(rd));
	rd.FillMode        = D3D11_FILL_SOLID;
	rd.CullMode        = ConvertGSCullMode(rasterState.cullMode);
	rd.DepthClipEnable = true;
	rd.ScissorEnable   = rasterState.scissorEnabled;

	hr = device->CreateRasterizerState(&rd, savedState.state.Assign());
	if (FAILED(hr))
		throw HRError("Failed to create rasterizer state", hr);

	state = savedState.state;
	rasterStates.push_back(savedState);

	return state;
}

ID3D11BlendState *gs_device::AddBlendState()
{
	HRESULT hr;
	D3D11_BLEND_DESC bd;
	SavedBlendState savedState(blendState);
	ID3D11BlendState *state;

	memset(&bd, 0, sizeof(bd));
	for (int i = 0; i < 8; i++) {
		bd.RenderTarget[i].BlendEnable    = blendState.blendEnabled;
		bd.RenderTarget[i].BlendOp        = D3D11_BLEND_OP_ADD;
		bd.RenderTarget[i].BlendOpAlpha   = D3D11_BLEND_OP_ADD;
		bd.RenderTarget[i].SrcBlendAlpha  = D3D11_BLEND_ONE;
		bd.RenderTarget[i].DestBlendAlpha = D3D11_BLEND_ZERO;
		bd.RenderTarget[i].SrcBlend =
			ConvertGSBlendType(blendState.srcFactor);
		bd.RenderTarget[i].DestBlend =
			ConvertGSBlendType(blendState.destFactor);
		bd.RenderTarget[i].RenderTargetWriteMask =
			D3D11_COLOR_WRITE_ENABLE_ALL;
	}

	hr = device->CreateBlendState(&bd, savedState.state.Assign());
	if (FAILED(hr))
		throw HRError("Failed to create disabled blend state", hr);

	state = savedState.state;
	blendStates.push_back(savedState);

	return state;
}

void gs_device::UpdateZStencilState()
{
	ID3D11DepthStencilState *state = NULL;

	if (!zstencilStateChanged)
		return;

	for (size_t i = 0; i < zstencilStates.size(); i++) {
		SavedZStencilState &s = zstencilStates[i];
		if (memcmp(&s, &zstencilState, sizeof(zstencilState)) == 0) {
			state = s.state;
			break;
		}
	}

	if (!state)
		state = AddZStencilState();

	if (state != curDepthStencilState) {
		context->OMSetDepthStencilState(state, 0);
		curDepthStencilState = state;
	}

	zstencilStateChanged = false;
}

void gs_device::UpdateRasterState()
{
	ID3D11RasterizerState *state = NULL;

	if (!rasterStateChanged)
		return;

	for (size_t i = 0; i < rasterStates.size(); i++) {
		SavedRasterState &s = rasterStates[i];
		if (memcmp(&s, &rasterState, sizeof(rasterState)) == 0) {
			state = s.state;
			break;
		}
	}

	if (!state)
		state = AddRasterState();

	if (state != curRasterState) {
		context->RSSetState(state);
		curRasterState = state;
	}

	rasterStateChanged = false;
}

void gs_device::UpdateBlendState()
{
	ID3D11BlendState *state = NULL;

	if (!blendStateChanged)
		return;

	for (size_t i = 0; i < blendStates.size(); i++) {
		SavedBlendState &s = blendStates[i];
		if (memcmp(&s, &blendState, sizeof(blendState)) == 0) {
			state = s.state;
			break;
		}
	}

	if (!state)
		state = AddBlendState();

	if (state != curBlendState) {
		float f[4] = {1.0f, 1.0f, 1.0f, 1.0f};
		context->OMSetBlendState(state, f, 0xFFFFFFFF);
		curBlendState = state;
	}

	blendStateChanged = false;
}

void gs_device::UpdateViewProjMatrix()
{
	matrix3 cur_matrix;
	gs_matrix_get(&cur_matrix);

	matrix4_from_matrix3(&curViewMatrix, &cur_matrix);
	matrix4_mul(&curViewProjMatrix, &curViewMatrix, &curProjMatrix);
	matrix4_transpose(&curViewProjMatrix, &curViewProjMatrix);

	if (curVertexShader->viewProj)
		shader_setmatrix4(curVertexShader, curVertexShader->viewProj,
				&curViewProjMatrix);
}

gs_device::gs_device(gs_init_data *data)
	: curRenderTarget      (NULL),
	  curZStencilBuffer    (NULL),
	  curRenderSide        (0),
	  curIndexBuffer       (NULL),
	  curVertexBuffer      (NULL),
	  curVertexShader      (NULL),
	  curPixelShader       (NULL),
	  curSwapChain         (&defaultSwap),
	  zstencilStateChanged (true),
	  rasterStateChanged   (true),
	  blendStateChanged    (true),
	  curDepthStencilState (NULL),
	  curRasterState       (NULL),
	  curBlendState        (NULL),
	  curToplogy           (D3D11_PRIMITIVE_TOPOLOGY_UNDEFINED)
{
	ComPtr<IDXGIAdapter1> adapter;

	matrix4_identity(&curProjMatrix);
	matrix4_identity(&curViewMatrix);
	matrix4_identity(&curViewProjMatrix);

	memset(&viewport, 0, sizeof(viewport));

400
	for (size_t i = 0; i < GS_MAX_TEXTURES; i++) {
J
jp9000 已提交
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
		curTextures[i] = NULL;
		curSamplers[i] = NULL;
	}

	InitFactory(data->adapter, adapter.Assign());
	InitDevice(data, adapter);
	device_setrendertarget(this, NULL, NULL);
}

gs_device *device_create(gs_init_data *data)
{
	gs_device *device = NULL;

	try {
		device = new gs_device(data);
	} catch (HRError error) {
		blog(LOG_ERROR, "device_create (D3D11): %s (%08lX)", error.str,
				error.hr);
	}

	return device;
}

void device_destroy(device_t device)
{
	delete device;
}

swapchain_t device_create_swapchain(device_t device, struct gs_init_data *data)
{
	gs_swap_chain *swap = NULL;

	try {
		swap = new gs_swap_chain(device, data);
	} catch (HRError error) {
		blog(LOG_ERROR, "device_create_swapchain (D3D11): %s (%08lX)",
				error.str, error.hr);
	}

	return swap;
}

void device_resize(device_t device, uint32_t cx, uint32_t cy)
{
	try {
		ID3D11RenderTargetView *renderView = NULL;
		ID3D11DepthStencilView *depthView  = NULL;
		int i = device->curRenderSide;

		device->context->OMSetRenderTargets(1, &renderView, depthView);
		device->curSwapChain->Resize(cx, cy);

		if (device->curRenderTarget)
			renderView = device->curRenderTarget->renderTarget[i];
		if (device->curZStencilBuffer)
			depthView  = device->curZStencilBuffer->view;
		device->context->OMSetRenderTargets(1, &renderView, depthView);

	} catch (HRError error) {
		blog(LOG_ERROR, "device_resize (D3D11): %s (%08lX)",
				error.str, error.hr);
	}
}

void device_getsize(device_t device, uint32_t *cx, uint32_t *cy)
{
	*cx = device->curSwapChain->target.width;
	*cy = device->curSwapChain->target.height;
}

uint32_t device_getwidth(device_t device)
{
	return device->curSwapChain->target.width;
}

uint32_t device_getheight(device_t device)
{
	return device->curSwapChain->target.height;
}

texture_t device_create_texture(device_t device, uint32_t width,
482 483
		uint32_t height, enum gs_color_format color_format,
		uint32_t levels, void **data, uint32_t flags)
J
jp9000 已提交
484 485 486 487
{
	gs_texture *texture = NULL;
	try {
		texture = new gs_texture_2d(device, width, height, color_format,
488 489
				levels, data, flags, GS_TEXTURE_2D, false,
				false);
J
jp9000 已提交
490 491 492 493 494 495 496 497 498 499 500
	} catch (HRError error) {
		blog(LOG_ERROR, "device_create_texture (D3D11): %s (%08lX)",
				error.str, error.hr);
	} catch (const char *error) {
		blog(LOG_ERROR, "device_create_texture (D3D11): %s", error);
	}

	return texture;
}

texture_t device_create_cubetexture(device_t device, uint32_t size,
501
		enum gs_color_format color_format, uint32_t levels, void **data,
J
jp9000 已提交
502 503 504 505 506
		uint32_t flags)
{
	gs_texture *texture = NULL;
	try {
		texture = new gs_texture_2d(device, size, size, color_format,
507 508
				levels, data, flags, GS_TEXTURE_CUBE, false,
				false);
J
jp9000 已提交
509 510 511 512 513 514 515 516 517 518 519 520 521 522
	} catch (HRError error) {
		blog(LOG_ERROR, "device_create_cubetexture (D3D11): %s "
		                "(%08lX)",
		                error.str, error.hr);
	} catch (const char *error) {
		blog(LOG_ERROR, "device_create_cubetexture (D3D11): %s",
				error);
	}

	return texture;
}

texture_t device_create_volumetexture(device_t device, uint32_t width,
		uint32_t height, uint32_t depth,
523 524
		enum gs_color_format color_format, uint32_t levels,
		void **data, uint32_t flags)
J
jp9000 已提交
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
{
	/* TODO */
	return NULL;
}

zstencil_t device_create_zstencil(device_t device, uint32_t width,
		uint32_t height, enum gs_zstencil_format format)
{
	gs_zstencil_buffer *zstencil = NULL;
	try {
		zstencil = new gs_zstencil_buffer(device, width, height,
				format);
	} catch (HRError error) {
		blog(LOG_ERROR, "device_create_zstencil (D3D11): %s (%08lX)",
				error.str, error.hr);
	}

	return zstencil;
}

stagesurf_t device_create_stagesurface(device_t device, uint32_t width,
		uint32_t height, enum gs_color_format color_format)
{
	gs_stage_surface *surf = NULL;
	try {
		surf = new gs_stage_surface(device, width, height,
				color_format);
	} catch (HRError error) {
		blog(LOG_ERROR, "device_create_stagesurface (D3D11): %s "
		                "(%08lX)",
				error.str, error.hr);
	}

	return surf;
}

samplerstate_t device_create_samplerstate(device_t device,
		struct gs_sampler_info *info)
{
	gs_sampler_state *ss = NULL;
	try {
		ss = new gs_sampler_state(device, info);
	} catch (HRError error) {
		blog(LOG_ERROR, "device_create_samplerstate (D3D11): %s "
		                "(%08lX)",
				error.str, error.hr);
	}

	return ss;
}

shader_t device_create_vertexshader(device_t device,
		const char *shader_string, const char *file,
		char **error_string)
{
	gs_vertex_shader *shader = NULL;
	try {
		shader = new gs_vertex_shader(device, file, shader_string);

	} catch (HRError error) {
		blog(LOG_ERROR, "device_create_vertexshader (D3D11): %s "
		                "(%08lX)",
				error.str, error.hr);

	} catch (ShaderError error) {
		const char *buf = (const char*)error.errors->GetBufferPointer();
		if (error_string)
			*error_string = bstrdup(buf);
		blog(LOG_ERROR, "device_create_vertexshader (D3D11): "
		                "Compile errors for %s:\n%s",
		                file, buf);

	} catch (const char *error) {
		blog(LOG_ERROR, "device_create_vertexshader (D3D11): %s",
				error);
	}

	return shader;
}

shader_t device_create_pixelshader(device_t device,
		const char *shader_string, const char *file,
		char **error_string)
{
	gs_pixel_shader *shader = NULL;
	try {
		shader = new gs_pixel_shader(device, file, shader_string);

	} catch (HRError error) {
		blog(LOG_ERROR, "device_create_pixelshader (D3D11): %s "
		                "(%08lX)",
				error.str, error.hr);

	} catch (ShaderError error) {
		const char *buf = (const char*)error.errors->GetBufferPointer();
		if (error_string)
			*error_string = bstrdup(buf);
		blog(LOG_ERROR, "device_create_pixelshader (D3D11): "
		                "Compiler errors for %s:\n%s",
		                file, buf);

	} catch (const char *error) {
		blog(LOG_ERROR, "device_create_pixelshader (D3D11): %s",
				error);
	}

	return shader;
}

vertbuffer_t device_create_vertexbuffer(device_t device,
		struct vb_data *data, uint32_t flags)
{
	gs_vertex_buffer *buffer = NULL;
	try {
		buffer = new gs_vertex_buffer(device, data, flags);
	} catch (HRError error) {
		blog(LOG_ERROR, "device_create_vertexbuffer (D3D11): %s "
		                "(%08lX)",
				error.str, error.hr);
	} catch (const char *error) {
		blog(LOG_ERROR, "device_create_vertexbuffer (D3D11): %s",
				error);
	}

	return buffer;
}

indexbuffer_t device_create_indexbuffer(device_t device,
		enum gs_index_type type, void *indices, size_t num,
		uint32_t flags)
{
	gs_index_buffer *buffer = NULL;
	try {
		buffer = new gs_index_buffer(device, type, indices, num, flags);
	} catch (HRError error) {
		blog(LOG_ERROR, "device_create_indexbuffer (D3D11): %s (%08lX)",
				error.str, error.hr);
	}

	return buffer;
}

enum gs_texture_type device_gettexturetype(device_t device, texture_t texture)
{
	return texture->type;
}

void device_load_vertexbuffer(device_t device, vertbuffer_t vertbuffer)
{
	if (device->curVertexBuffer == vertbuffer)
		return;

	device->curVertexBuffer = vertbuffer;

	if (!device->curVertexShader)
		return;

	vector<ID3D11Buffer*> buffers;
	vector<uint32_t> strides;
	vector<uint32_t> offsets;

	if (vertbuffer) {
		vertbuffer->MakeBufferList(device->curVertexShader,
				buffers, strides);
	} else {
		size_t buffersToClear =
			device->curVertexShader->NumBuffersExpected();
		buffers.resize(buffersToClear);
		strides.resize(buffersToClear);
	}

	offsets.resize(buffers.size());
	device->context->IASetVertexBuffers(0, (UINT)buffers.size(),
			buffers.data(), strides.data(), offsets.data());
}

void device_load_indexbuffer(device_t device, indexbuffer_t indexbuffer)
{
	DXGI_FORMAT format;
	ID3D11Buffer *buffer;

	if (device->curIndexBuffer == indexbuffer)
		return;

	if (indexbuffer) {
		switch (indexbuffer->indexSize) {
		case 2: format = DXGI_FORMAT_R16_UINT; break;
		case 4: format = DXGI_FORMAT_R32_UINT; break;
		}

		buffer = indexbuffer->indexBuffer;
	} else {
		buffer = NULL;
		format = DXGI_FORMAT_R32_UINT;
	}

	device->curIndexBuffer = indexbuffer;
	device->context->IASetIndexBuffer(buffer, format, 0);
}

void device_load_texture(device_t device, texture_t tex, int unit)
{
	ID3D11ShaderResourceView *view = NULL;

	if (device->curTextures[unit] == tex)
		return;

	if (tex)
		view = tex->shaderRes;

	device->curTextures[unit] = tex;
	device->context->PSSetShaderResources(unit, 1, &view);
}

void device_load_samplerstate(device_t device,
		samplerstate_t samplerstate, int unit)
{
	ID3D11SamplerState *state = NULL;

	if (device->curSamplers[unit] == samplerstate)
		return;

	if (samplerstate)
		state = samplerstate->state;

	device->curSamplers[unit] = samplerstate;
	device->context->PSSetSamplers(unit, 1, &state);
}

void device_load_vertexshader(device_t device, shader_t vertshader)
{
	ID3D11VertexShader *shader    = NULL;
	ID3D11InputLayout  *layout    = NULL;
	ID3D11Buffer       *constants = NULL;

	if (device->curVertexShader == vertshader)
		return;

	gs_vertex_shader *vs = static_cast<gs_vertex_shader*>(vertshader);
	gs_vertex_buffer *curVB = device->curVertexBuffer;

	if (vertshader) {
		if (vertshader->type != SHADER_VERTEX) {
			blog(LOG_ERROR, "device_load_vertexshader (D3D11): "
769 770
			                "Specified shader is not a vertex "
			                "shader");
J
jp9000 已提交
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
			return;
		}

		if (curVB)
			device_load_vertexbuffer(device, NULL);

		shader    = vs->shader;
		layout    = vs->layout;
		constants = vs->constants;
	}

	device->curVertexShader = vs;
	device->context->VSSetShader(shader, NULL, 0);
	device->context->IASetInputLayout(layout);
	device->context->VSSetConstantBuffers(0, 1, &constants);

	if (vertshader && curVB)
		device_load_vertexbuffer(device, curVB);
}

static inline void clear_textures(device_t device)
{
793
	ID3D11ShaderResourceView *views[GS_MAX_TEXTURES];
J
jp9000 已提交
794 795
	memset(views,               0, sizeof(views));
	memset(device->curTextures, 0, sizeof(device->curTextures));
796
	device->context->PSSetShaderResources(0, GS_MAX_TEXTURES, views);
J
jp9000 已提交
797 798 799 800 801 802
}

void device_load_pixelshader(device_t device, shader_t pixelshader)
{
	ID3D11PixelShader  *shader    = NULL;
	ID3D11Buffer       *constants = NULL;
803
	ID3D11SamplerState *states[GS_MAX_TEXTURES];
J
jp9000 已提交
804 805 806 807 808 809 810 811 812

	if (device->curPixelShader == pixelshader)
		return;

	gs_pixel_shader *ps = static_cast<gs_pixel_shader*>(pixelshader);

	if (pixelshader) {
		if (pixelshader->type != SHADER_PIXEL) {
			blog(LOG_ERROR, "device_load_pixelshader (D3D11): "
813 814
			                "Specified shader is not a pixel "
			                "shader");
J
jp9000 已提交
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
			return;
		}

		shader    = ps->shader;
		constants = ps->constants;
		ps->GetSamplerStates(states);
	} else {
		memset(states, 0, sizeof(states));
	}

	clear_textures(device);

	device->curPixelShader = ps;
	device->context->PSSetShader(shader, NULL, 0);
	device->context->PSSetConstantBuffers(0, 1, &constants);
830
	device->context->PSSetSamplers(0, GS_MAX_TEXTURES, states);
J
jp9000 已提交
831 832
}

833
void device_load_defaultsamplerstate(device_t device, bool b_3d, int unit)
J
jp9000 已提交
834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
{
	/* TODO */
}

shader_t device_getvertexshader(device_t device)
{
	return device->curVertexShader;
}

shader_t device_getpixelshader(device_t device)
{
	return device->curPixelShader;
}

texture_t device_getrendertarget(device_t device)
{
	if (device->curRenderTarget == &device->curSwapChain->target)
		return NULL;

	return device->curRenderTarget;
}

zstencil_t device_getzstenciltarget(device_t device)
{
	if (device->curZStencilBuffer == &device->curSwapChain->zs)
		return NULL;

	return device->curZStencilBuffer;
}

void device_setrendertarget(device_t device, texture_t tex, zstencil_t zstencil)
{
	if (!tex)
		tex = &device->curSwapChain->target;
	if (!zstencil)
		zstencil = &device->curSwapChain->zs;

	if (device->curRenderTarget   == tex &&
	    device->curZStencilBuffer == zstencil)
		return;

	if (tex->type != GS_TEXTURE_2D) {
		blog(LOG_ERROR, "device_setrendertarget (D3D11): "
				"texture is not a 2D texture");
		return;
	}

	gs_texture_2d *tex2d = static_cast<gs_texture_2d*>(tex);
	if (!tex2d->renderTarget[0]) {
		blog(LOG_ERROR, "device_setrendertarget (D3D11): "
				"texture is not a render target");
		return;
	}

	ID3D11RenderTargetView *rt = tex2d->renderTarget[0];

	device->curRenderTarget   = tex2d;
	device->curRenderSide     = 0;
	device->curZStencilBuffer = zstencil;
	device->context->OMSetRenderTargets(1, &rt, zstencil->view);
}

void device_setcuberendertarget(device_t device, texture_t tex, int side,
		zstencil_t zstencil)
{
	if (!tex) {
		tex = &device->curSwapChain->target;
		side = 0;
	}

	if (!zstencil)
		zstencil = &device->curSwapChain->zs;

	if (device->curRenderTarget   == tex  &&
	    device->curRenderSide     == side &&
	    device->curZStencilBuffer == zstencil)
		return;

	if (tex->type != GS_TEXTURE_CUBE) {
		blog(LOG_ERROR, "device_setcuberendertarget (D3D11): "
		                "texture is not a cube texture");
		return;
	}

	gs_texture_2d *tex2d = static_cast<gs_texture_2d*>(tex);
	if (!tex2d->renderTarget[side]) {
		blog(LOG_ERROR, "device_setcuberendertarget (D3D11): "
				"texture is not a render target");
		return;
	}

	ID3D11RenderTargetView *rt = tex2d->renderTarget[0];

	device->curRenderTarget   = tex2d;
	device->curRenderSide     = side;
	device->curZStencilBuffer = zstencil;
	device->context->OMSetRenderTargets(1, &rt, zstencil->view);
}

inline void gs_device::CopyTex(ID3D11Texture2D *dst, texture_t src)
{
	if (!src)
		src = curRenderTarget;
	if (src->type != GS_TEXTURE_2D)
		throw "Source texture must be a 2D texture";

	gs_texture_2d *tex2d = static_cast<gs_texture_2d*>(src);
	context->CopyResource(dst, tex2d->texture);
}

void device_copy_texture(device_t device, texture_t dst, texture_t src)
{
	try {
		if (!dst)
			throw "Failed because destination texture is NULL";
		if (dst->type != GS_TEXTURE_2D)
			throw "Destination texture must be a 2D texture";

		gs_texture_2d *tex2d = static_cast<gs_texture_2d*>(dst);
		device->CopyTex(tex2d->texture, src);

	} catch (const char *error) {
		blog(LOG_ERROR, "device_copy_texture (D3D11): %s", error);
	}
}

void device_stage_texture(device_t device, stagesurf_t dst, texture_t src)
{
	try {
		if (!dst)
			throw "Failed because destination texture is NULL";

		device->CopyTex(dst->texture, src);

	} catch (const char *error) {
		blog(LOG_ERROR, "device_copy_texture (D3D11): %s", error);
	}
}

void device_beginscene(device_t device)
{
	clear_textures(device);
}

void device_draw(device_t device, enum gs_draw_mode draw_mode,
		uint32_t start_vert, uint32_t num_verts)
{
	try {
		if (!device->curVertexShader)
			throw "No vertex shader specified";

		if (!device->curPixelShader)
			throw "No pixel shader specified";

		if (!device->curVertexBuffer)
			throw "No vertex buffer specified";

		effect_t effect = gs_geteffect();
		if (effect)
			effect_updateparams(effect);

		device->UpdateBlendState();
		device->UpdateRasterState();
		device->UpdateZStencilState();
		device->UpdateViewProjMatrix();
		device->curVertexShader->UploadParams();
		device->curPixelShader->UploadParams();

	} catch (const char *error) {
		blog(LOG_ERROR, "device_draw (D3D11): %s", error);
		return;

	} catch (HRError error) {
		blog(LOG_ERROR, "device_draw (D3D11): %s (%08lX)", error.str,
				error.hr);
		return;
	}

	D3D10_PRIMITIVE_TOPOLOGY newTopology = ConvertGSTopology(draw_mode);
	if (device->curToplogy != newTopology) {
		device->context->IASetPrimitiveTopology(newTopology);
		device->curToplogy = newTopology;
	}

	if (num_verts == 0)
		num_verts = (uint32_t)device->curVertexBuffer->numVerts;

	if (device->curIndexBuffer)
		device->context->DrawIndexed(num_verts, start_vert, 0);
	else
		device->context->Draw(num_verts, start_vert);
}

void device_endscene(device_t device)
{
	/* does nothing in D3D11 */
}

void device_load_swapchain(device_t device, swapchain_t swapchain)
{
	texture_t  target = device->curRenderTarget;
	zstencil_t zs     = device->curZStencilBuffer;
	bool is_cube = device->curRenderTarget->type == GS_TEXTURE_CUBE;

	if (target == &device->curSwapChain->target)
		target = NULL;
	if (zs == &device->curSwapChain->zs)
		zs = NULL;

	if (swapchain == NULL)
		swapchain = &device->defaultSwap;

	device->curSwapChain = swapchain;

	if (is_cube)
		device_setcuberendertarget(device, target,
				device->curRenderSide, zs);
	else
		device_setrendertarget(device, target, zs);
}

void device_clear(device_t device, uint32_t clear_flags, struct vec4 *color,
		float depth, uint8_t stencil)
{
	int side = device->curRenderSide;
	if ((clear_flags & GS_CLEAR_COLOR) != 0 && device->curRenderTarget)
		device->context->ClearRenderTargetView(
				device->curRenderTarget->renderTarget[side],
				color->ptr);

	if (device->curZStencilBuffer) {
		uint32_t flags = 0;
		if ((clear_flags & GS_CLEAR_DEPTH) != 0)
			flags |= D3D11_CLEAR_DEPTH;
		if ((clear_flags & GS_CLEAR_STENCIL) != 0)
			flags |= D3D11_CLEAR_STENCIL;

		if (flags && device->curZStencilBuffer->view)
			device->context->ClearDepthStencilView(
					device->curZStencilBuffer->view,
					flags, depth, stencil);
	}
}

void device_present(device_t device)
{
	device->curSwapChain->swap->Present(0, 0);
}

void device_setcullmode(device_t device, enum gs_cull_mode mode)
{
	if (mode == device->rasterState.cullMode)
		return;

	device->rasterState.cullMode = mode;
	device->rasterStateChanged = true;
}

enum gs_cull_mode device_getcullmode(device_t device)
{
	return device->rasterState.cullMode;
}

void device_enable_blending(device_t device, bool enable)
{
	if (enable == device->blendState.blendEnabled)
		return;

	device->blendState.blendEnabled = enable;
	device->blendStateChanged = true;
}

void device_enable_depthtest(device_t device, bool enable)
{
	if (enable == device->zstencilState.depthEnabled)
		return;

	device->zstencilState.depthEnabled = enable;
	device->zstencilStateChanged = true;
}

void device_enable_stenciltest(device_t device, bool enable)
{
	if (enable == device->zstencilState.stencilEnabled)
		return;

	device->zstencilState.stencilEnabled = enable;
	device->zstencilStateChanged = true;
}

void device_enable_stencilwrite(device_t device, bool enable)
{
	if (enable == device->zstencilState.stencilWriteEnabled)
		return;

	device->zstencilState.stencilWriteEnabled = enable;
	device->zstencilStateChanged = true;
}

1133 1134
void device_enable_color(device_t device, bool red, bool green,
		bool blue, bool alpha)
J
jp9000 已提交
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
{
	if (device->blendState.redEnabled   == red   &&
	    device->blendState.greenEnabled == green &&
	    device->blendState.blueEnabled  == blue  &&
	    device->blendState.alphaEnabled == alpha)
		return;

	device->blendState.redEnabled   = red;
	device->blendState.greenEnabled = green;
	device->blendState.blueEnabled  = blue;
	device->blendState.alphaEnabled = alpha;
	device->blendStateChanged       = true;
}

void device_blendfunction(device_t device, enum gs_blend_type src,
		enum gs_blend_type dest)
{
	if (device->blendState.srcFactor  == src &&
	    device->blendState.destFactor == dest)
		return;

	device->blendState.srcFactor  = src;
	device->blendState.destFactor = dest;
	device->blendStateChanged     = true;
}

void device_depthfunction(device_t device, enum gs_depth_test test)
{
	if (device->zstencilState.depthFunc == test)
		return;

	device->zstencilState.depthFunc = test;
	device->zstencilStateChanged    = true;
}

static inline void update_stencilside_test(device_t device, StencilSide &side,
		gs_depth_test test)
{
	if (side.test == test)
		return;

	side.test = test;
	device->zstencilStateChanged = true;
}

void device_stencilfunction(device_t device, enum gs_stencil_side side,
		enum gs_depth_test test)
{
	int sideVal = (int)side;

	if (sideVal & GS_STENCIL_FRONT)
		update_stencilside_test(device,
				device->zstencilState.stencilFront, test);
	if (sideVal & GS_STENCIL_BACK)
		update_stencilside_test(device,
				device->zstencilState.stencilBack, test);
}

static inline void update_stencilside_op(device_t device, StencilSide &side,
		enum gs_stencil_op fail, enum gs_stencil_op zfail,
		enum gs_stencil_op zpass)
{
	if (side.fail == fail && side.zfail == zfail && side.zpass == zpass)
		return;

	side.fail  = fail;
	side.zfail = zfail;
	side.zpass = zpass;
	device->zstencilStateChanged = true;
}

void device_stencilop(device_t device, enum gs_stencil_side side,
		enum gs_stencil_op fail, enum gs_stencil_op zfail,
		enum gs_stencil_op zpass)
{
	int sideVal = (int)side;

	if (sideVal & GS_STENCIL_FRONT)
		update_stencilside_op(device,
				device->zstencilState.stencilFront,
				fail, zfail, zpass);
	if (sideVal & GS_STENCIL_BACK)
		update_stencilside_op(device,
				device->zstencilState.stencilBack,
				fail, zfail, zpass);
}

void device_enable_fullscreen(device_t device, bool enable)
{
	/* TODO */
}

int device_fullscreen_enabled(device_t device)
{
	/* TODO */
	return 0;
}

void device_setdisplaymode(device_t device,
		const struct gs_display_mode *mode)
{
	/* TODO */
}

void device_getdisplaymode(device_t device,
		struct gs_display_mode *mode)
{
	/* TODO */
}

void device_setcolorramp(device_t device, float gamma, float brightness,
		float contrast)
{
	/* TODO */
}

void device_setviewport(device_t device, int x, int y, int width,
		int height)
{
	D3D11_VIEWPORT vp;
	memset(&vp, 0, sizeof(vp));
	vp.MaxDepth = 1.0f;
	vp.TopLeftX = (float)x;
	vp.TopLeftY = (float)y;
	vp.Width    = (float)width;
	vp.Height   = (float)height;
	device->context->RSSetViewports(1, &vp);

	device->viewport.x  = x;
	device->viewport.y  = y;
	device->viewport.cx = width;
	device->viewport.cy = height;
}

void device_getviewport(device_t device, struct gs_rect *rect)
{
	memcpy(rect, &device->viewport, sizeof(gs_rect));
}

void device_setscissorrect(device_t device, struct gs_rect *rect)
{
	D3D11_RECT d3drect;
	d3drect.left   = rect->x;
	d3drect.top    = rect->y;
	d3drect.right  = rect->x + rect->cx;
	d3drect.bottom = rect->y + rect->cy;
	device->context->RSSetScissorRects(1, &d3drect);
}

void device_ortho(device_t device, float left, float right, float top,
		float bottom, float znear, float zfar)
{
	matrix4_ortho(&device->curProjMatrix, left, right, top, bottom, znear,
			zfar);
}

void device_frustum(device_t device, float left, float right, float top,
		float bottom, float znear, float zfar)
{
	matrix4_frustum(&device->curProjMatrix, left, right, top, bottom,
			znear, zfar);
}

void device_perspective(device_t device, float fovy, float aspect,
		float znear, float zfar)
{
	matrix4_perspective(&device->curProjMatrix, fovy, aspect, znear, zfar);
}

void device_projection_push(device_t device)
{
	mat4float mat;
	memcpy(&mat, &device->curProjMatrix, sizeof(matrix4));
	device->projStack.push_back(mat);
}

void device_projection_pop(device_t device)
{
	if (!device->projStack.size())
		return;

	mat4float *mat = device->projStack.data();
	size_t end = device->projStack.size()-1;

	/* XXX - does anyone know a better way of doing this? */
	memcpy(&device->curProjMatrix, mat+end, sizeof(matrix4));
	device->projStack.pop_back();
}

void swapchain_destroy(swapchain_t swapchain)
{
	if (!swapchain)
		return;

	gs_device *device = swapchain->device;
	if (device->curSwapChain == swapchain)
		device->curSwapChain = &device->defaultSwap;

	delete swapchain;
}

void texture_destroy(texture_t tex)
{
	delete tex;
}

uint32_t texture_getwidth(texture_t tex)
{
	if (tex->type != GS_TEXTURE_2D)
		return 0;

	return static_cast<gs_texture_2d*>(tex)->width;
}

uint32_t texture_getheight(texture_t tex)
{
	if (tex->type != GS_TEXTURE_2D)
		return 0;

	return static_cast<gs_texture_2d*>(tex)->height;
}

enum gs_color_format texture_getcolorformat(texture_t tex)
{
	if (tex->type != GS_TEXTURE_2D)
		return GS_UNKNOWN;

	return static_cast<gs_texture_2d*>(tex)->format;
}

bool texture_map(texture_t tex, void **ptr, uint32_t *byte_width)
{
	HRESULT hr;

	if (tex->type != GS_TEXTURE_2D)
		return false;

	gs_texture_2d *tex2d = static_cast<gs_texture_2d*>(tex);

	D3D11_MAPPED_SUBRESOURCE map;
	hr = tex2d->device->context->Map(tex2d->texture, 0,
			D3D11_MAP_WRITE_DISCARD, 0, &map);
	if (FAILED(hr))
		return false;

	*ptr = map.pData;
	*byte_width = map.RowPitch;
	return true;
}

void texture_unmap(texture_t tex)
{
	if (tex->type != GS_TEXTURE_2D)
		return;

	gs_texture_2d *tex2d = static_cast<gs_texture_2d*>(tex);
	tex2d->device->context->Unmap(tex2d->texture, 0);
}


void cubetexture_destroy(texture_t cubetex)
{
	delete cubetex;
}

uint32_t cubetexture_getsize(texture_t cubetex)
{
	if (cubetex->type != GS_TEXTURE_CUBE)
		return 0;

	gs_texture_2d *tex = static_cast<gs_texture_2d*>(cubetex);
	return tex->width;
}

enum gs_color_format cubetexture_getcolorformat(texture_t cubetex)
{
	if (cubetex->type != GS_TEXTURE_CUBE)
		return GS_UNKNOWN;

	gs_texture_2d *tex = static_cast<gs_texture_2d*>(cubetex);
	return tex->format;
}


void volumetexture_destroy(texture_t voltex)
{
	delete voltex;
}

uint32_t volumetexture_getwidth(texture_t voltex)
{
	/* TODO */
	return 0;
}

uint32_t volumetexture_getheight(texture_t voltex)
{
	/* TODO */
	return 0;
}

uint32_t volumetexture_getdepth(texture_t voltex)
{
	/* TODO */
	return 0;
}

enum gs_color_format volumetexture_getcolorformat(texture_t voltex)
{
	/* TODO */
	return GS_UNKNOWN;
}


void stagesurface_destroy(stagesurf_t stagesurf)
{
	delete stagesurf;
}

uint32_t stagesurface_getwidth(stagesurf_t stagesurf)
{
	return stagesurf->width;
}

uint32_t stagesurface_getheight(stagesurf_t stagesurf)
{
	return stagesurf->height;
}

enum gs_color_format stagesurface_getcolorformat(stagesurf_t stagesurf)
{
	return stagesurf->format;
}

bool stagesurface_map(stagesurf_t stagesurf, const void **data,
		uint32_t *byte_width)
{
	D3D11_MAPPED_SUBRESOURCE map;
	if (FAILED(stagesurf->device->context->Map(stagesurf->texture, 0,
			D3D11_MAP_READ, 0, &map)))
		return false;

	*data = map.pData;
	*byte_width = map.RowPitch;
	return true;
}

void stagesurface_unmap(stagesurf_t stagesurf)
{
	stagesurf->device->context->Unmap(stagesurf->texture, 0);
}


void zstencil_destroy(zstencil_t zstencil)
{
	delete zstencil;
}


void samplerstate_destroy(samplerstate_t samplerstate)
{
	delete samplerstate;
}


void vertexbuffer_destroy(vertbuffer_t vertbuffer)
{
	delete vertbuffer;
}

void vertexbuffer_flush(vertbuffer_t vertbuffer, bool rebuild)
{
	if (!vertbuffer->dynamic) {
		blog(LOG_WARNING, "vertexbuffer_flush: vertex buffer is "
		                  "not dynamic");
		return;
	}

	vertbuffer->FlushBuffer(vertbuffer->vertexBuffer,
			vertbuffer->vbd.data->points, sizeof(vec3));

	if (vertbuffer->normalBuffer)
		vertbuffer->FlushBuffer(vertbuffer->normalBuffer,
				vertbuffer->vbd.data->normals, sizeof(vec3));

	if (vertbuffer->tangentBuffer)
		vertbuffer->FlushBuffer(vertbuffer->tangentBuffer,
				vertbuffer->vbd.data->tangents, sizeof(vec3));

	if (vertbuffer->colorBuffer)
		vertbuffer->FlushBuffer(vertbuffer->colorBuffer,
				vertbuffer->vbd.data->colors, sizeof(uint32_t));

	for (size_t i = 0; i < vertbuffer->uvBuffers.size(); i++) {
		tvertarray &tv = vertbuffer->vbd.data->tvarray[i];
		vertbuffer->FlushBuffer(vertbuffer->uvBuffers[i],
				tv.array, tv.width*sizeof(float));
	}
}

struct vb_data *vertexbuffer_getdata(vertbuffer_t vertbuffer)
{
	return vertbuffer->vbd.data;
}


void indexbuffer_destroy(indexbuffer_t indexbuffer)
{
	delete indexbuffer;
}

void indexbuffer_flush(indexbuffer_t indexbuffer)
{
	HRESULT hr;

	if (!indexbuffer->dynamic)
		return;

	D3D11_MAPPED_SUBRESOURCE map;
	hr = indexbuffer->device->context->Map(indexbuffer->indexBuffer, 0,
			D3D11_MAP_WRITE_DISCARD, 0, &map);
	if (FAILED(hr))
		return;

	memcpy(map.pData, indexbuffer->indices.data,
			indexbuffer->num * indexbuffer->indexSize);

	indexbuffer->device->context->Unmap(indexbuffer->indexBuffer, 0);
}

void *indexbuffer_getdata(indexbuffer_t indexbuffer)
{
	return indexbuffer->indices.data;
}

size_t indexbuffer_numindices(indexbuffer_t indexbuffer)
{
	return indexbuffer->num;
}

enum gs_index_type indexbuffer_gettype(indexbuffer_t indexbuffer)
{
	return indexbuffer->type;
}