<commit_before>/* The Halfling Project - A Graphics Engine and Projects
 *
 * The Halfling Project is the legal property of Adrian Astley
 * Copyright Adrian Astley 2013
 */

#include "lighting_demo/graphics_manager.h"

#include "common/d3d_util.h"

#include "lighting_demo/game_state_manager.h"

#include "assert.h"
#include <AntTweakBar.h>

namespace LightingDemo {

GraphicsManager::GraphicsManager(GameStateManager *gameStateManager)
	: Common::GraphicsManagerBase(),
	  m_gameStateManager(gameStateManager),
	  m_vsync(false),
	  m_renderTargetView(nullptr),
	  m_inputLayout(nullptr),
	  m_vertexShaderFrameConstantsBuffer(nullptr),
	  m_vertexShaderObjectConstantsBuffer(nullptr),
	  m_pixelShaderFrameConstantsBuffer(nullptr),
	  m_pixelShaderObjectConstantsBuffer(nullptr),
	  m_pointLightBuffer(nullptr),
	  m_spotLightBuffer(nullptr),
	  m_vertexShader(nullptr),
	  m_pixelShader(nullptr),
	  m_wireframeRS(nullptr) {
}

bool GraphicsManager::Initialize(int clientWidth, int clientHeight, HWND hwnd, bool fullscreen) {
	if (!Common::GraphicsManagerBase::Initialize(clientWidth, clientHeight, hwnd, fullscreen))
		return false;

	InitTweakBar();

	if (!m_gameStateManager->Initialize(hwnd, &m_device))
		return false;

	LoadShaders();

	D3D11_RASTERIZER_DESC wireframeDesc;
	ZeroMemory(&wireframeDesc, sizeof(D3D11_RASTERIZER_DESC));
	wireframeDesc.FillMode = D3D11_FILL_WIREFRAME;
	wireframeDesc.CullMode = D3D11_CULL_BACK;
	wireframeDesc.FrontCounterClockwise = false;
	wireframeDesc.DepthClipEnable = true;

	HR(m_device->CreateRasterizerState(&wireframeDesc, &m_wireframeRS));

	return true;
}

void GraphicsManager::Shutdown() {
	// Release in the opposite order we initialized in
	ReleaseCOM(m_vertexShaderFrameConstantsBuffer);
	ReleaseCOM(m_vertexShaderObjectConstantsBuffer);
	ReleaseCOM(m_pixelShaderFrameConstantsBuffer);
	ReleaseCOM(m_pixelShaderObjectConstantsBuffer);
	delete m_pointLightBuffer;
	delete m_spotLightBuffer;
	ReleaseCOM(m_wireframeRS);
	ReleaseCOM(m_vertexShader);
	ReleaseCOM(m_pixelShader);
	ReleaseCOM(m_inputLayout);
	ReleaseCOM(m_renderTargetView);

	TwTerminate();

	Common::GraphicsManagerBase::Shutdown();
}

void GraphicsManager::DrawFrame(float deltaTime) {
	CalculateFrameStats(deltaTime);

	m_immediateContext->ClearRenderTargetView(m_renderTargetView, reinterpret_cast<const float*>(&Colors::Blue));
	m_immediateContext->ClearDepthStencilView(m_depthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);

	// Transpose the matrices to prepare them for the shader.
	DirectX::XMMATRIX worldMatrix = m_gameStateManager->WorldViewProj.world;
	DirectX::XMMATRIX viewMatrix = m_gameStateManager->WorldViewProj.view;
	DirectX::XMMATRIX projectionMatrix = m_gameStateManager->WorldViewProj.projection;

	// Cache the matrix multiplications
	DirectX::XMMATRIX viewProj = DirectX::XMMatrixTranspose(viewMatrix * projectionMatrix);
	DirectX::XMMATRIX worldViewProjection = DirectX::XMMatrixTranspose(worldMatrix * viewMatrix * projectionMatrix);

	SetFrameConstants(DirectX::XMMatrixTranspose(projectionMatrix), viewProj);

	SetObjectConstants(DirectX::XMMatrixTranspose(worldMatrix), worldViewProjection, m_gameStateManager->Models[0].GetSubsetMaterial(0));
	SetLightBuffers(viewMatrix);

	m_immediateContext->IASetInputLayout(m_inputLayout);
	m_immediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

	// Set the vertex and pixel shaders that will be used to render this triangle.
	m_immediateContext->VSSetShader(m_vertexShader, NULL, 0);
	m_immediateContext->PSSetShader(m_pixelShader, NULL, 0);

	m_gameStateManager->Models[0].DrawSubset(m_immediateContext);

	TwDraw();

	if (m_vsync)
		m_swapChain->Present(1, 0);
	else
		m_swapChain->Present(0, 0);
}

void GraphicsManager::SetFrameConstants(DirectX::XMMATRIX &projMatrix, DirectX::XMMATRIX &viewProjMatrix) {
	// Fill in frame constants
	D3D11_MAPPED_SUBRESOURCE mappedResource;

	// Lock the constant buffer so it can be written to.
	HR(m_immediateContext->Map(m_vertexShaderFrameConstantsBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));

	VertexShaderFrameConstants *vertexShaderFrameConstants = static_cast<VertexShaderFrameConstants *>(mappedResource.pData);
	vertexShaderFrameConstants->proj = projMatrix;
	vertexShaderFrameConstants->viewProj = viewProjMatrix;

	m_immediateContext->Unmap(m_vertexShaderFrameConstantsBuffer, 0);
	m_immediateContext->VSSetConstantBuffers(0, 1, &m_vertexShaderFrameConstantsBuffer);
}

void GraphicsManager::SetObjectConstants(DirectX::XMMATRIX &worldMatrix, DirectX::XMMATRIX &worldViewProjMatrix, const Common::Material &material) {
	// Fill in object constants
	D3D11_MAPPED_SUBRESOURCE mappedResource;

	// Lock the constant buffer so it can be written to.
	HR(m_immediateContext->Map(m_vertexShaderObjectConstantsBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));

	VertexShaderObjectConstants *vertexShaderObjectConstants = static_cast<VertexShaderObjectConstants *>(mappedResource.pData);
	vertexShaderObjectConstants->world = worldMatrix;
	vertexShaderObjectConstants->worldViewProj = worldViewProjMatrix;

	m_immediateContext->Unmap(m_vertexShaderObjectConstantsBuffer, 0);
	m_immediateContext->VSSetConstantBuffers(1, 1, &m_vertexShaderObjectConstantsBuffer);

	// Lock the constant buffer so it can be written to.
	HR(m_immediateContext->Map(m_pixelShaderObjectConstantsBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));

	PixelShaderObjectConstants *pixelShaderObjectConstants = static_cast<PixelShaderObjectConstants *>(mappedResource.pData);
	pixelShaderObjectConstants->material = material;

	m_immediateContext->Unmap(m_pixelShaderObjectConstantsBuffer, 0);
	m_immediateContext->PSSetConstantBuffers(3, 1, &m_pixelShaderObjectConstantsBuffer);

	// Lock the constant buffer so it can be written to.
	HR(m_immediateContext->Map(m_pixelShaderFrameConstantsBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));

	PixelShaderFrameConstants *pixelShaderFrameConstants = static_cast<PixelShaderFrameConstants *>(mappedResource.pData);
	pixelShaderFrameConstants->directionalLight = *(m_gameStateManager->LightManager.GetDirectionalLight());
	pixelShaderFrameConstants->eyePosition = m_gameStateManager->GetCameraPosition();

	m_immediateContext->Unmap(m_pixelShaderFrameConstantsBuffer, 0);
	m_immediateContext->PSSetConstantBuffers(2, 1, &m_pixelShaderFrameConstantsBuffer);
}

void GraphicsManager::SetLightBuffers(DirectX::XMMATRIX &viewMatrix) {
	//{
	//	Common::PointLight* light = m_pointLightBuffer->MapDiscard(m_immediateContext);
	//	for (unsigned int i = 0; i < mActiveLights; ++i) {
	//		light[i] = mPointLightParameters[i];
	//	}
	//	mLightBuffer->Unmap(d3dDeviceContext);
	//}
}

void GraphicsManager::OnResize(int newClientWidth, int newClientHeight) {
	if (!m_d3dInitialized) {
		return;
	}

	// Release the render target view
	ReleaseCOM(m_renderTargetView);

	Common::GraphicsManagerBase::OnResize(newClientWidth, newClientHeight);

	// Recreate the render target view.
	ID3D11Texture2D* backBuffer;
	HR(m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&backBuffer)));
	HR(m_device->CreateRenderTargetView(backBuffer, 0, &m_renderTargetView));
	ReleaseCOM(backBuffer);

	// Bind the render target view and depth/stencil view to the pipeline.
	m_immediateContext->OMSetRenderTargets(1, &m_renderTargetView, m_depthStencilView);
}

void GraphicsManager::InitTweakBar() {
	int success = TwInit(TW_DIRECT3D11, m_device);

	m_tweakBar = TwNewBar("RootMenu");
	TwAddVarRW(m_tweakBar, "V-Sync", TwType::TW_TYPE_BOOLCPP, &m_vsync, "");
	TwDefine(" RootMenu movable=false resizable=false fontresizable=false contained=true ");
}

void GraphicsManager::LoadShaders() {
	D3D11_INPUT_ELEMENT_DESC vertexDesc[] = {
		{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},
		{"NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0}
	};

	HR(Common::LoadVertexShader("vertex_shader.cso", m_device, vertexDesc, 2, &m_vertexShader, &m_inputLayout));
	HR(Common::LoadPixelShader("pixel_shader.cso", m_device, &m_pixelShader));

	// Create the constant shader buffers
	D3D11_BUFFER_DESC vertexShaderFrameBufferDesc;
	vertexShaderFrameBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
	vertexShaderFrameBufferDesc.ByteWidth = sizeof(VertexShaderFrameConstants);
	vertexShaderFrameBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	vertexShaderFrameBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	vertexShaderFrameBufferDesc.MiscFlags = 0;
	vertexShaderFrameBufferDesc.StructureByteStride = 0;

	m_device->CreateBuffer(&vertexShaderFrameBufferDesc, NULL, &m_vertexShaderFrameConstantsBuffer);

	D3D11_BUFFER_DESC vertexShaderObjectBufferDesc;
	vertexShaderObjectBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
	vertexShaderObjectBufferDesc.ByteWidth = sizeof(VertexShaderObjectConstants);
	vertexShaderObjectBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	vertexShaderObjectBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	vertexShaderObjectBufferDesc.MiscFlags = 0;
	vertexShaderObjectBufferDesc.StructureByteStride = 0;

	m_device->CreateBuffer(&vertexShaderObjectBufferDesc, NULL, &m_vertexShaderObjectConstantsBuffer);

	D3D11_BUFFER_DESC pixelShaderFrameBufferDesc;
	pixelShaderFrameBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
	pixelShaderFrameBufferDesc.ByteWidth = sizeof(PixelShaderFrameConstants);
	pixelShaderFrameBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	pixelShaderFrameBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	pixelShaderFrameBufferDesc.MiscFlags = 0;
	pixelShaderFrameBufferDesc.StructureByteStride = 0;

	m_device->CreateBuffer(&pixelShaderFrameBufferDesc, NULL, &m_pixelShaderFrameConstantsBuffer);

	D3D11_BUFFER_DESC pixelShaderObjectBufferDesc;
	pixelShaderObjectBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
	pixelShaderObjectBufferDesc.ByteWidth = sizeof(PixelShaderObjectConstants);
	pixelShaderObjectBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	pixelShaderObjectBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	pixelShaderObjectBufferDesc.MiscFlags = 0;
	pixelShaderObjectBufferDesc.StructureByteStride = 0;

	m_device->CreateBuffer(&pixelShaderObjectBufferDesc, NULL, &m_pixelShaderObjectConstantsBuffer);

	m_pointLightBuffer = new Common::StructuredBuffer<Common::PointLight>(m_device, 1, D3D11_BIND_SHADER_RESOURCE, true);
	m_spotLightBuffer = new Common::StructuredBuffer<Common::SpotLight>(m_device, 1, D3D11_BIND_SHADER_RESOURCE, true);
}

} // End of namespace CrateDemo
<commit_msg>LIGHTING_DEMO: Add TweakBar values for fps and frame time<commit_after>/* The Halfling Project - A Graphics Engine and Projects
 *
 * The Halfling Project is the legal property of Adrian Astley
 * Copyright Adrian Astley 2013
 */

#include "lighting_demo/graphics_manager.h"

#include "common/d3d_util.h"

#include "lighting_demo/game_state_manager.h"

#include "assert.h"
#include <AntTweakBar.h>

namespace LightingDemo {

GraphicsManager::GraphicsManager(GameStateManager *gameStateManager)
	: Common::GraphicsManagerBase(),
	  m_gameStateManager(gameStateManager),
	  m_vsync(false),
	  m_renderTargetView(nullptr),
	  m_inputLayout(nullptr),
	  m_vertexShaderFrameConstantsBuffer(nullptr),
	  m_vertexShaderObjectConstantsBuffer(nullptr),
	  m_pixelShaderFrameConstantsBuffer(nullptr),
	  m_pixelShaderObjectConstantsBuffer(nullptr),
	  m_pointLightBuffer(nullptr),
	  m_spotLightBuffer(nullptr),
	  m_vertexShader(nullptr),
	  m_pixelShader(nullptr),
	  m_wireframeRS(nullptr) {
}

bool GraphicsManager::Initialize(int clientWidth, int clientHeight, HWND hwnd, bool fullscreen) {
	if (!Common::GraphicsManagerBase::Initialize(clientWidth, clientHeight, hwnd, fullscreen))
		return false;

	InitTweakBar();

	if (!m_gameStateManager->Initialize(hwnd, &m_device))
		return false;

	LoadShaders();

	D3D11_RASTERIZER_DESC wireframeDesc;
	ZeroMemory(&wireframeDesc, sizeof(D3D11_RASTERIZER_DESC));
	wireframeDesc.FillMode = D3D11_FILL_WIREFRAME;
	wireframeDesc.CullMode = D3D11_CULL_BACK;
	wireframeDesc.FrontCounterClockwise = false;
	wireframeDesc.DepthClipEnable = true;

	HR(m_device->CreateRasterizerState(&wireframeDesc, &m_wireframeRS));

	return true;
}

void GraphicsManager::Shutdown() {
	// Release in the opposite order we initialized in
	ReleaseCOM(m_vertexShaderFrameConstantsBuffer);
	ReleaseCOM(m_vertexShaderObjectConstantsBuffer);
	ReleaseCOM(m_pixelShaderFrameConstantsBuffer);
	ReleaseCOM(m_pixelShaderObjectConstantsBuffer);
	delete m_pointLightBuffer;
	delete m_spotLightBuffer;
	ReleaseCOM(m_wireframeRS);
	ReleaseCOM(m_vertexShader);
	ReleaseCOM(m_pixelShader);
	ReleaseCOM(m_inputLayout);
	ReleaseCOM(m_renderTargetView);

	TwTerminate();

	Common::GraphicsManagerBase::Shutdown();
}

void GraphicsManager::DrawFrame(float deltaTime) {
	CalculateFrameStats(deltaTime);

	m_immediateContext->ClearRenderTargetView(m_renderTargetView, reinterpret_cast<const float*>(&Colors::Blue));
	m_immediateContext->ClearDepthStencilView(m_depthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);

	// Transpose the matrices to prepare them for the shader.
	DirectX::XMMATRIX worldMatrix = m_gameStateManager->WorldViewProj.world;
	DirectX::XMMATRIX viewMatrix = m_gameStateManager->WorldViewProj.view;
	DirectX::XMMATRIX projectionMatrix = m_gameStateManager->WorldViewProj.projection;

	// Cache the matrix multiplications
	DirectX::XMMATRIX viewProj = DirectX::XMMatrixTranspose(viewMatrix * projectionMatrix);
	DirectX::XMMATRIX worldViewProjection = DirectX::XMMatrixTranspose(worldMatrix * viewMatrix * projectionMatrix);

	SetFrameConstants(DirectX::XMMatrixTranspose(projectionMatrix), viewProj);

	SetObjectConstants(DirectX::XMMatrixTranspose(worldMatrix), worldViewProjection, m_gameStateManager->Models[0].GetSubsetMaterial(0));
	SetLightBuffers(viewMatrix);

	m_immediateContext->IASetInputLayout(m_inputLayout);
	m_immediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

	// Set the vertex and pixel shaders that will be used to render this triangle.
	m_immediateContext->VSSetShader(m_vertexShader, NULL, 0);
	m_immediateContext->PSSetShader(m_pixelShader, NULL, 0);

	m_gameStateManager->Models[0].DrawSubset(m_immediateContext);

	TwDraw();

	if (m_vsync)
		m_swapChain->Present(1, 0);
	else
		m_swapChain->Present(0, 0);
}

void GraphicsManager::SetFrameConstants(DirectX::XMMATRIX &projMatrix, DirectX::XMMATRIX &viewProjMatrix) {
	// Fill in frame constants
	D3D11_MAPPED_SUBRESOURCE mappedResource;

	// Lock the constant buffer so it can be written to.
	HR(m_immediateContext->Map(m_vertexShaderFrameConstantsBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));

	VertexShaderFrameConstants *vertexShaderFrameConstants = static_cast<VertexShaderFrameConstants *>(mappedResource.pData);
	vertexShaderFrameConstants->proj = projMatrix;
	vertexShaderFrameConstants->viewProj = viewProjMatrix;

	m_immediateContext->Unmap(m_vertexShaderFrameConstantsBuffer, 0);
	m_immediateContext->VSSetConstantBuffers(0, 1, &m_vertexShaderFrameConstantsBuffer);
}

void GraphicsManager::SetObjectConstants(DirectX::XMMATRIX &worldMatrix, DirectX::XMMATRIX &worldViewProjMatrix, const Common::Material &material) {
	// Fill in object constants
	D3D11_MAPPED_SUBRESOURCE mappedResource;

	// Lock the constant buffer so it can be written to.
	HR(m_immediateContext->Map(m_vertexShaderObjectConstantsBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));

	VertexShaderObjectConstants *vertexShaderObjectConstants = static_cast<VertexShaderObjectConstants *>(mappedResource.pData);
	vertexShaderObjectConstants->world = worldMatrix;
	vertexShaderObjectConstants->worldViewProj = worldViewProjMatrix;

	m_immediateContext->Unmap(m_vertexShaderObjectConstantsBuffer, 0);
	m_immediateContext->VSSetConstantBuffers(1, 1, &m_vertexShaderObjectConstantsBuffer);

	// Lock the constant buffer so it can be written to.
	HR(m_immediateContext->Map(m_pixelShaderObjectConstantsBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));

	PixelShaderObjectConstants *pixelShaderObjectConstants = static_cast<PixelShaderObjectConstants *>(mappedResource.pData);
	pixelShaderObjectConstants->material = material;

	m_immediateContext->Unmap(m_pixelShaderObjectConstantsBuffer, 0);
	m_immediateContext->PSSetConstantBuffers(3, 1, &m_pixelShaderObjectConstantsBuffer);

	// Lock the constant buffer so it can be written to.
	HR(m_immediateContext->Map(m_pixelShaderFrameConstantsBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));

	PixelShaderFrameConstants *pixelShaderFrameConstants = static_cast<PixelShaderFrameConstants *>(mappedResource.pData);
	pixelShaderFrameConstants->directionalLight = *(m_gameStateManager->LightManager.GetDirectionalLight());
	pixelShaderFrameConstants->eyePosition = m_gameStateManager->GetCameraPosition();

	m_immediateContext->Unmap(m_pixelShaderFrameConstantsBuffer, 0);
	m_immediateContext->PSSetConstantBuffers(2, 1, &m_pixelShaderFrameConstantsBuffer);
}

void GraphicsManager::SetLightBuffers(DirectX::XMMATRIX &viewMatrix) {
	//{
	//	Common::PointLight* light = m_pointLightBuffer->MapDiscard(m_immediateContext);
	//	for (unsigned int i = 0; i < mActiveLights; ++i) {
	//		light[i] = mPointLightParameters[i];
	//	}
	//	mLightBuffer->Unmap(d3dDeviceContext);
	//}
}

void GraphicsManager::OnResize(int newClientWidth, int newClientHeight) {
	if (!m_d3dInitialized) {
		return;
	}

	// Release the render target view
	ReleaseCOM(m_renderTargetView);

	Common::GraphicsManagerBase::OnResize(newClientWidth, newClientHeight);

	// Recreate the render target view.
	ID3D11Texture2D* backBuffer;
	HR(m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&backBuffer)));
	HR(m_device->CreateRenderTargetView(backBuffer, 0, &m_renderTargetView));
	ReleaseCOM(backBuffer);

	// Bind the render target view and depth/stencil view to the pipeline.
	m_immediateContext->OMSetRenderTargets(1, &m_renderTargetView, m_depthStencilView);
}

void GraphicsManager::InitTweakBar() {
	int success = TwInit(TW_DIRECT3D11, m_device);

	m_tweakBar = TwNewBar("RootMenu");
	TwAddVarRO(m_tweakBar, "FPS", TwType::TW_TYPE_UINT32, &m_fps, "");
	TwAddVarRO(m_tweakBar, "Frame Time (ms)", TwType::TW_TYPE_FLOAT, &m_frameTime, "");
	TwAddVarRW(m_tweakBar, "V-Sync", TwType::TW_TYPE_BOOLCPP, &m_vsync, "");
	TwDefine(" RootMenu movable=false resizable=false fontresizable=false contained=true ");
}

void GraphicsManager::LoadShaders() {
	D3D11_INPUT_ELEMENT_DESC vertexDesc[] = {
		{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},
		{"NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0}
	};

	HR(Common::LoadVertexShader("vertex_shader.cso", m_device, vertexDesc, 2, &m_vertexShader, &m_inputLayout));
	HR(Common::LoadPixelShader("pixel_shader.cso", m_device, &m_pixelShader));

	// Create the constant shader buffers
	D3D11_BUFFER_DESC vertexShaderFrameBufferDesc;
	vertexShaderFrameBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
	vertexShaderFrameBufferDesc.ByteWidth = sizeof(VertexShaderFrameConstants);
	vertexShaderFrameBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	vertexShaderFrameBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	vertexShaderFrameBufferDesc.MiscFlags = 0;
	vertexShaderFrameBufferDesc.StructureByteStride = 0;

	m_device->CreateBuffer(&vertexShaderFrameBufferDesc, NULL, &m_vertexShaderFrameConstantsBuffer);

	D3D11_BUFFER_DESC vertexShaderObjectBufferDesc;
	vertexShaderObjectBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
	vertexShaderObjectBufferDesc.ByteWidth = sizeof(VertexShaderObjectConstants);
	vertexShaderObjectBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	vertexShaderObjectBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	vertexShaderObjectBufferDesc.MiscFlags = 0;
	vertexShaderObjectBufferDesc.StructureByteStride = 0;

	m_device->CreateBuffer(&vertexShaderObjectBufferDesc, NULL, &m_vertexShaderObjectConstantsBuffer);

	D3D11_BUFFER_DESC pixelShaderFrameBufferDesc;
	pixelShaderFrameBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
	pixelShaderFrameBufferDesc.ByteWidth = sizeof(PixelShaderFrameConstants);
	pixelShaderFrameBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	pixelShaderFrameBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	pixelShaderFrameBufferDesc.MiscFlags = 0;
	pixelShaderFrameBufferDesc.StructureByteStride = 0;

	m_device->CreateBuffer(&pixelShaderFrameBufferDesc, NULL, &m_pixelShaderFrameConstantsBuffer);

	D3D11_BUFFER_DESC pixelShaderObjectBufferDesc;
	pixelShaderObjectBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
	pixelShaderObjectBufferDesc.ByteWidth = sizeof(PixelShaderObjectConstants);
	pixelShaderObjectBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	pixelShaderObjectBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	pixelShaderObjectBufferDesc.MiscFlags = 0;
	pixelShaderObjectBufferDesc.StructureByteStride = 0;

	m_device->CreateBuffer(&pixelShaderObjectBufferDesc, NULL, &m_pixelShaderObjectConstantsBuffer);

	m_pointLightBuffer = new Common::StructuredBuffer<Common::PointLight>(m_device, 1, D3D11_BIND_SHADER_RESOURCE, true);
	m_spotLightBuffer = new Common::StructuredBuffer<Common::SpotLight>(m_device, 1, D3D11_BIND_SHADER_RESOURCE, true);
}

} // End of namespace CrateDemo
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: hlnkitem.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 17:53:55 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _SVX_HLNKITEM_HXX
#define _SVX_HLNKITEM_HXX

#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _SFXPOOLITEM_HXX
#include <svtools/poolitem.hxx>
#endif
#ifndef _SFXSIDS_HRC
#include <sfx2/sfxsids.hrc>
#endif

#ifndef _SFXMACITEM_HXX
#include <svtools/macitem.hxx>
#endif

#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif

#define HYPERDLG_EVENT_MOUSEOVER_OBJECT     0x0001
#define HYPERDLG_EVENT_MOUSECLICK_OBJECT    0x0002
#define HYPERDLG_EVENT_MOUSEOUT_OBJECT      0x0004

enum SvxLinkInsertMode
{
    HLINK_DEFAULT,
    HLINK_FIELD,
    HLINK_BUTTON,
    HLINK_HTMLMODE = 0x0080
};

class SVX_DLLPUBLIC SvxHyperlinkItem : public SfxPoolItem
{
    String sName;
    String sURL;
    String sTarget;
    SvxLinkInsertMode eType;

    String sIntName;
    SvxMacroTableDtor*  pMacroTable;

    USHORT nMacroEvents;

public:
    TYPEINFO();

    SvxHyperlinkItem( USHORT nWhich = SID_HYPERLINK_GETLINK ):
                SfxPoolItem(nWhich), pMacroTable(NULL)  { eType = HLINK_DEFAULT; nMacroEvents=0; };
    SvxHyperlinkItem( const SvxHyperlinkItem& rHyperlinkItem );
    SvxHyperlinkItem( USHORT nWhich, String& rName, String& rURL,
                                    String& rTarget, String& rIntName,
                                    SvxLinkInsertMode eTyp = HLINK_FIELD,
                                    USHORT nEvents = 0,
                                    SvxMacroTableDtor *pMacroTbl =NULL );
    virtual ~SvxHyperlinkItem () { delete pMacroTable; }

    inline SvxHyperlinkItem& operator=( const SvxHyperlinkItem &rItem );

    virtual int              operator==( const SfxPoolItem& ) const;
    virtual SfxPoolItem*     Clone( SfxItemPool *pPool = 0 ) const;
    virtual BOOL             QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;
    virtual BOOL             PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );

    const   String& GetName() const { return sName; }
    void    SetName(const String& rName) { sName = rName; }

    const   String& GetURL() const { return sURL; }
    void    SetURL(const String& rURL) { sURL = rURL; }

    const   String& GetIntName () const { return sIntName; }
    void    SetIntName(const String& rIntName) { sIntName = rIntName; }

    const   String& GetTargetFrame() const { return sTarget; }
    void    SetTargetFrame(const String& rTarget) { sTarget = rTarget; }

    SvxLinkInsertMode GetInsertMode() const { return eType; }
    void    SetInsertMode( SvxLinkInsertMode eNew ) { eType = eNew; }

    void SetMacro( USHORT nEvent, const SvxMacro& rMacro );

    void SetMacroTable( const SvxMacroTableDtor& rTbl );
    const SvxMacroTableDtor* GetMacroTbl() const    { return pMacroTable; }

    void SetMacroEvents (const USHORT nEvents) { nMacroEvents = nEvents; }
    const   USHORT GetMacroEvents() const { return nMacroEvents; }

    virtual SvStream&           Store( SvStream &, USHORT nItemVersion ) const;
    virtual SfxPoolItem*        Create( SvStream &, USHORT nVer ) const;

};

#endif

<commit_msg>INTEGRATION: CWS warnings01 (1.4.220); FILE MERGED 2006/04/20 14:47:58 cl 1.4.220.1: warning free code changes<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: hlnkitem.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 14:38:43 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _SVX_HLNKITEM_HXX
#define _SVX_HLNKITEM_HXX

#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _SFXPOOLITEM_HXX
#include <svtools/poolitem.hxx>
#endif
#ifndef _SFXSIDS_HRC
#include <sfx2/sfxsids.hrc>
#endif

#ifndef _SFXMACITEM_HXX
#include <svtools/macitem.hxx>
#endif

#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif

#define HYPERDLG_EVENT_MOUSEOVER_OBJECT     0x0001
#define HYPERDLG_EVENT_MOUSECLICK_OBJECT    0x0002
#define HYPERDLG_EVENT_MOUSEOUT_OBJECT      0x0004

enum SvxLinkInsertMode
{
    HLINK_DEFAULT,
    HLINK_FIELD,
    HLINK_BUTTON,
    HLINK_HTMLMODE = 0x0080
};

class SVX_DLLPUBLIC SvxHyperlinkItem : public SfxPoolItem
{
    String sName;
    String sURL;
    String sTarget;
    SvxLinkInsertMode eType;

    String sIntName;
    SvxMacroTableDtor*  pMacroTable;

    USHORT nMacroEvents;

public:
    TYPEINFO();

    SvxHyperlinkItem( USHORT _nWhich = SID_HYPERLINK_GETLINK ):
                SfxPoolItem(_nWhich), pMacroTable(NULL) { eType = HLINK_DEFAULT; nMacroEvents=0; };
    SvxHyperlinkItem( const SvxHyperlinkItem& rHyperlinkItem );
    SvxHyperlinkItem( USHORT nWhich, String& rName, String& rURL,
                                    String& rTarget, String& rIntName,
                                    SvxLinkInsertMode eTyp = HLINK_FIELD,
                                    USHORT nEvents = 0,
                                    SvxMacroTableDtor *pMacroTbl =NULL );
    virtual ~SvxHyperlinkItem () { delete pMacroTable; }

    inline SvxHyperlinkItem& operator=( const SvxHyperlinkItem &rItem );

    virtual int              operator==( const SfxPoolItem& ) const;
    virtual SfxPoolItem*     Clone( SfxItemPool *pPool = 0 ) const;
    virtual BOOL             QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;
    virtual BOOL             PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );

    const   String& GetName() const { return sName; }
    void    SetName(const String& rName) { sName = rName; }

    const   String& GetURL() const { return sURL; }
    void    SetURL(const String& rURL) { sURL = rURL; }

    const   String& GetIntName () const { return sIntName; }
    void    SetIntName(const String& rIntName) { sIntName = rIntName; }

    const   String& GetTargetFrame() const { return sTarget; }
    void    SetTargetFrame(const String& rTarget) { sTarget = rTarget; }

    SvxLinkInsertMode GetInsertMode() const { return eType; }
    void    SetInsertMode( SvxLinkInsertMode eNew ) { eType = eNew; }

    void SetMacro( USHORT nEvent, const SvxMacro& rMacro );

    void SetMacroTable( const SvxMacroTableDtor& rTbl );
    const SvxMacroTableDtor* GetMacroTbl() const    { return pMacroTable; }

    void SetMacroEvents (const USHORT nEvents) { nMacroEvents = nEvents; }
    const   USHORT GetMacroEvents() const { return nMacroEvents; }

    virtual SvStream&           Store( SvStream &, USHORT nItemVersion ) const;
    virtual SfxPoolItem*        Create( SvStream &, USHORT nVer ) const;

};

#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: linectrl.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: obo $ $Date: 2006-10-12 11:45:45 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _SVX_LINECTRL_HXX
#define _SVX_LINECTRL_HXX

#ifndef _VALUESET_HXX //autogen
#include <svtools/valueset.hxx>
#endif
#ifndef _SFXLSTNER_HXX //autogen
#include <svtools/lstner.hxx>
#endif
#ifndef _SFXTBXCTRL_HXX //autogen
#include <sfx2/tbxctrl.hxx>
#endif
#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif

class XLineStyleItem;
class XLineDashItem;
class SvxLineBox;
class SvxMetricField;
class SvxColorBox;
class XLineEndList;

//========================================================================
// SvxLineStyleController:
//========================================================================

class SVX_DLLPUBLIC SvxLineStyleToolBoxControl : public SfxToolBoxControl
{
private:
    XLineStyleItem*     pStyleItem;
    XLineDashItem*      pDashItem;

    BOOL                bUpdate;

public:
    SFX_DECL_TOOLBOX_CONTROL();

    SvxLineStyleToolBoxControl( USHORT nSlotId, USHORT nId, ToolBox& rTbx );
    ~SvxLineStyleToolBoxControl();

    virtual void        StateChanged( USHORT nSID, SfxItemState eState,
                                      const SfxPoolItem* pState );
    void                Update( const SfxPoolItem* pState );
    virtual Window*     CreateItemWindow( Window *pParent );
};

//========================================================================
// SvxLineWidthController:
//========================================================================

class SVX_DLLPUBLIC SvxLineWidthToolBoxControl : public SfxToolBoxControl
{
public:
    SFX_DECL_TOOLBOX_CONTROL();

    SvxLineWidthToolBoxControl( USHORT nSlotId, USHORT nId, ToolBox& rTbx );
    ~SvxLineWidthToolBoxControl();

    virtual void        StateChanged( USHORT nSID, SfxItemState eState,
                                      const SfxPoolItem* pState );
    virtual Window*     CreateItemWindow( Window *pParent );
};

//========================================================================
// SvxLineColorController:
//========================================================================

class SVX_DLLPUBLIC SvxLineColorToolBoxControl : public SfxToolBoxControl
{
public:
    SFX_DECL_TOOLBOX_CONTROL();

    SvxLineColorToolBoxControl( USHORT nSlotId, USHORT nId, ToolBox& rTbx );
    ~SvxLineColorToolBoxControl();

    virtual void        StateChanged( USHORT nSID, SfxItemState eState,
                                      const SfxPoolItem* pState );
    void                Update( const SfxPoolItem* pState );
    virtual Window*     CreateItemWindow( Window *pParent );
};

//========================================================================
// class SvxLineEndWindow
//========================================================================
class SvxLineEndWindow : public SfxPopupWindow
{
    using FloatingWindow::StateChanged;

private:
    XLineEndList*   pLineEndList;
    ValueSet        aLineEndSet;
    USHORT          nCols;
    USHORT          nLines;
    ULONG           nLineEndWidth;
    Size            aBmpSize;
    BOOL            bPopupMode;
    bool            mbInResize;
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > mxFrame;

    DECL_LINK( SelectHdl, void * );
    void            FillValueSet();
    void            SetSize();
    void            implInit();

protected:
    virtual void    Resizing( Size& rSize );
    virtual void    Resize();
    virtual BOOL    Close();
    virtual void    PopupModeEnd();

    /** This function is called when the window gets the focus.  It grabs
        the focus to the line ends value set so that it can be controlled with
        the keyboard.
    */
    virtual void GetFocus (void);

public:
    SvxLineEndWindow( USHORT nId,
                      const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame,
                      const String& rWndTitle );
    SvxLineEndWindow( USHORT nId,
                      const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame,
                      Window* pParentWindow,
                      const String& rWndTitle );
    ~SvxLineEndWindow();

    void            StartSelection();

    virtual void    StateChanged( USHORT nSID, SfxItemState eState,
                                  const SfxPoolItem* pState );
    virtual SfxPopupWindow* Clone() const;
};

//========================================================================
// class SvxColorToolBoxControl
//========================================================================

class SVX_DLLPUBLIC SvxLineEndToolBoxControl : public SfxToolBoxControl
{
public:
    SFX_DECL_TOOLBOX_CONTROL();
    SvxLineEndToolBoxControl( USHORT nSlotId, USHORT nId, ToolBox& rTbx );
    ~SvxLineEndToolBoxControl();

    virtual void                StateChanged( USHORT nSID, SfxItemState eState,
                                              const SfxPoolItem* pState );
    virtual SfxPopupWindowType  GetPopupWindowType() const;
    virtual SfxPopupWindow*     CreatePopupWindow();
};

#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.8.700); FILE MERGED 2008/04/01 15:49:17 thb 1.8.700.3: #i85898# Stripping all external header guards 2008/04/01 12:46:22 thb 1.8.700.2: #i85898# Stripping all external header guards 2008/03/31 14:17:56 rt 1.8.700.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: linectrl.hxx,v $
 * $Revision: 1.9 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _SVX_LINECTRL_HXX
#define _SVX_LINECTRL_HXX

#include <svtools/valueset.hxx>
#include <svtools/lstner.hxx>
#include <sfx2/tbxctrl.hxx>
#include "svx/svxdllapi.h"

class XLineStyleItem;
class XLineDashItem;
class SvxLineBox;
class SvxMetricField;
class SvxColorBox;
class XLineEndList;

//========================================================================
// SvxLineStyleController:
//========================================================================

class SVX_DLLPUBLIC SvxLineStyleToolBoxControl : public SfxToolBoxControl
{
private:
    XLineStyleItem*     pStyleItem;
    XLineDashItem*      pDashItem;

    BOOL                bUpdate;

public:
    SFX_DECL_TOOLBOX_CONTROL();

    SvxLineStyleToolBoxControl( USHORT nSlotId, USHORT nId, ToolBox& rTbx );
    ~SvxLineStyleToolBoxControl();

    virtual void        StateChanged( USHORT nSID, SfxItemState eState,
                                      const SfxPoolItem* pState );
    void                Update( const SfxPoolItem* pState );
    virtual Window*     CreateItemWindow( Window *pParent );
};

//========================================================================
// SvxLineWidthController:
//========================================================================

class SVX_DLLPUBLIC SvxLineWidthToolBoxControl : public SfxToolBoxControl
{
public:
    SFX_DECL_TOOLBOX_CONTROL();

    SvxLineWidthToolBoxControl( USHORT nSlotId, USHORT nId, ToolBox& rTbx );
    ~SvxLineWidthToolBoxControl();

    virtual void        StateChanged( USHORT nSID, SfxItemState eState,
                                      const SfxPoolItem* pState );
    virtual Window*     CreateItemWindow( Window *pParent );
};

//========================================================================
// SvxLineColorController:
//========================================================================

class SVX_DLLPUBLIC SvxLineColorToolBoxControl : public SfxToolBoxControl
{
public:
    SFX_DECL_TOOLBOX_CONTROL();

    SvxLineColorToolBoxControl( USHORT nSlotId, USHORT nId, ToolBox& rTbx );
    ~SvxLineColorToolBoxControl();

    virtual void        StateChanged( USHORT nSID, SfxItemState eState,
                                      const SfxPoolItem* pState );
    void                Update( const SfxPoolItem* pState );
    virtual Window*     CreateItemWindow( Window *pParent );
};

//========================================================================
// class SvxLineEndWindow
//========================================================================
class SvxLineEndWindow : public SfxPopupWindow
{
    using FloatingWindow::StateChanged;

private:
    XLineEndList*   pLineEndList;
    ValueSet        aLineEndSet;
    USHORT          nCols;
    USHORT          nLines;
    ULONG           nLineEndWidth;
    Size            aBmpSize;
    BOOL            bPopupMode;
    bool            mbInResize;
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > mxFrame;

    DECL_LINK( SelectHdl, void * );
    void            FillValueSet();
    void            SetSize();
    void            implInit();

protected:
    virtual void    Resizing( Size& rSize );
    virtual void    Resize();
    virtual BOOL    Close();
    virtual void    PopupModeEnd();

    /** This function is called when the window gets the focus.  It grabs
        the focus to the line ends value set so that it can be controlled with
        the keyboard.
    */
    virtual void GetFocus (void);

public:
    SvxLineEndWindow( USHORT nId,
                      const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame,
                      const String& rWndTitle );
    SvxLineEndWindow( USHORT nId,
                      const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame,
                      Window* pParentWindow,
                      const String& rWndTitle );
    ~SvxLineEndWindow();

    void            StartSelection();

    virtual void    StateChanged( USHORT nSID, SfxItemState eState,
                                  const SfxPoolItem* pState );
    virtual SfxPopupWindow* Clone() const;
};

//========================================================================
// class SvxColorToolBoxControl
//========================================================================

class SVX_DLLPUBLIC SvxLineEndToolBoxControl : public SfxToolBoxControl
{
public:
    SFX_DECL_TOOLBOX_CONTROL();
    SvxLineEndToolBoxControl( USHORT nSlotId, USHORT nId, ToolBox& rTbx );
    ~SvxLineEndToolBoxControl();

    virtual void                StateChanged( USHORT nSID, SfxItemState eState,
                                              const SfxPoolItem* pState );
    virtual SfxPopupWindowType  GetPopupWindowType() const;
    virtual SfxPopupWindow*     CreatePopupWindow();
};

#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: txencbox.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: er $ $Date: 2002-07-29 15:07:41 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library 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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _SVX_TXENCBOX_HXX
#define _SVX_TXENCBOX_HXX

// include ---------------------------------------------------------------

#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif

class SvxTextEncodingTable;

class SvxTextEncodingBox : public ListBox
{
private:
    const SvxTextEncodingTable*     m_pEncTable;

    USHORT              EncodingToPos_Impl( rtl_TextEncoding nEnc ) const;

public:
                        SvxTextEncodingBox( Window* pParent, const ResId& rResId );
                        ~SvxTextEncodingBox();

    /** Fill with all known encodings but exclude those matching one or more
        given flags as defined in rtl/tencinfo.h

         <p> If nButIncludeInfoFlags is given, encodings are included even if they
         match nExcludeInfoFlags. Thus it is possible to exclude 16/32-bit
         Unicode with RTL_TEXTENCODING_INFO_UNICODE but to include UTF7 and UTF8
         with RTL_TEXTENCODING_INFO_MIME </p>

        @param bExcludeImportSubsets
            If <TRUE/>, some specific encodings are not listed, as they are a
            subset of another encoding. This is the case for
            RTL_TEXTENCODING_GB_2312, RTL_TEXTENCODING_GBK,
            RTL_TEXTENCODING_MS_936, which are covered by
            RTL_TEXTENCODING_GB_18030. Normally, this flag should be set to
            <TRUE/> whenever the box is used in import dialogs. */
    void                FillFromTextEncodingTable(
                            sal_Bool bExcludeImportSubsets = FALSE,
                            sal_uInt32 nExcludeInfoFlags = 0,
                            sal_uInt32 nButIncludeInfoFlags = 0
                            );

    /** Fill with all encodings known to the dbtools::OCharsetMap but exclude
        those matching one or more given flags as defined in rtl/tencinfo.h

         <p> If nButIncludeInfoFlags is given, encodings are included even if they
         match nExcludeInfoFlags. Thus it is possible to exclude 16/32-bit
         Unicode with RTL_TEXTENCODING_INFO_UNICODE but to include UTF7 and UTF8
         with RTL_TEXTENCODING_INFO_MIME </p>

        @param bExcludeImportSubsets
            If <TRUE/>, some specific encodings are not listed, as they are a
            subset of another encoding. This is the case for
            RTL_TEXTENCODING_GB_2312, RTL_TEXTENCODING_GBK,
            RTL_TEXTENCODING_MS_936, which are covered by
            RTL_TEXTENCODING_GB_18030. Normally, this flag should be set to
            <TRUE/> whenever the box is used in import dialogs. */
    void                FillFromDbTextEncodingMap(
                            sal_Bool bExcludeImportSubsets = FALSE,
                            sal_uInt32 nExcludeInfoFlags = 0,
                            sal_uInt32 nButIncludeInfoFlags = 0
                            );

    /** Fill with all known MIME encodings and select the best one matching
        the system encoding.
     */
    void                FillWithMimeAndSelectBest();

    const SvxTextEncodingTable*     GetTextEncodingTable() const
                            { return m_pEncTable; }

    void                InsertTextEncoding( const rtl_TextEncoding nEnc,
                            USHORT nPos = LISTBOX_APPEND );

    void                InsertTextEncoding( const rtl_TextEncoding nEnc,
                            const String& rEntry,
                            USHORT nPos = LISTBOX_APPEND );

    void                RemoveTextEncoding( const rtl_TextEncoding nEnc );

    void                SelectTextEncoding( const rtl_TextEncoding nEnc,
                            BOOL bSelect = TRUE );

    rtl_TextEncoding    GetSelectTextEncoding() const;

    const String&       GetSelectTextString() const;

    BOOL                IsTextEncodingSelected( const rtl_TextEncoding nEnc ) const;
};

#endif

<commit_msg>INTEGRATION: CWS calc06 (1.4.148); FILE MERGED 2003/03/18 15:44:45 er 1.4.148.1: #i11797# GetBestMimeEncoding() even if locale unknown, take UI locale, or UTF8 fallback<commit_after>/*************************************************************************
 *
 *  $RCSfile: txencbox.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2003-04-08 16:12:37 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library 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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _SVX_TXENCBOX_HXX
#define _SVX_TXENCBOX_HXX

// include ---------------------------------------------------------------

#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _RTL_TEXTENC_H
#include <rtl/textenc.h>
#endif

class SvxTextEncodingTable;

class SvxTextEncodingBox : public ListBox
{
private:
    const SvxTextEncodingTable*     m_pEncTable;

    USHORT              EncodingToPos_Impl( rtl_TextEncoding nEnc ) const;

public:
                        SvxTextEncodingBox( Window* pParent, const ResId& rResId );
                        ~SvxTextEncodingBox();

    /** Fill with all known encodings but exclude those matching one or more
        given flags as defined in rtl/tencinfo.h

         <p> If nButIncludeInfoFlags is given, encodings are included even if they
         match nExcludeInfoFlags. Thus it is possible to exclude 16/32-bit
         Unicode with RTL_TEXTENCODING_INFO_UNICODE but to include UTF7 and UTF8
         with RTL_TEXTENCODING_INFO_MIME </p>

        @param bExcludeImportSubsets
            If <TRUE/>, some specific encodings are not listed, as they are a
            subset of another encoding. This is the case for
            RTL_TEXTENCODING_GB_2312, RTL_TEXTENCODING_GBK,
            RTL_TEXTENCODING_MS_936, which are covered by
            RTL_TEXTENCODING_GB_18030. Normally, this flag should be set to
            <TRUE/> whenever the box is used in import dialogs. */
    void                FillFromTextEncodingTable(
                            sal_Bool bExcludeImportSubsets = FALSE,
                            sal_uInt32 nExcludeInfoFlags = 0,
                            sal_uInt32 nButIncludeInfoFlags = 0
                            );

    /** Fill with all encodings known to the dbtools::OCharsetMap but exclude
        those matching one or more given flags as defined in rtl/tencinfo.h

         <p> If nButIncludeInfoFlags is given, encodings are included even if they
         match nExcludeInfoFlags. Thus it is possible to exclude 16/32-bit
         Unicode with RTL_TEXTENCODING_INFO_UNICODE but to include UTF7 and UTF8
         with RTL_TEXTENCODING_INFO_MIME </p>

        @param bExcludeImportSubsets
            If <TRUE/>, some specific encodings are not listed, as they are a
            subset of another encoding. This is the case for
            RTL_TEXTENCODING_GB_2312, RTL_TEXTENCODING_GBK,
            RTL_TEXTENCODING_MS_936, which are covered by
            RTL_TEXTENCODING_GB_18030. Normally, this flag should be set to
            <TRUE/> whenever the box is used in import dialogs. */
    void                FillFromDbTextEncodingMap(
                            sal_Bool bExcludeImportSubsets = FALSE,
                            sal_uInt32 nExcludeInfoFlags = 0,
                            sal_uInt32 nButIncludeInfoFlags = 0
                            );

    /** Fill with all known MIME encodings and select the best according to
        <method>GetBestMimeEncoding</method>
     */
    void                FillWithMimeAndSelectBest();

    /** Get the best MIME encoding matching the system locale, or if that isn't
        determinable one that matches the UI locale, or UTF8 if everything else
        fails.
     */
    static  rtl_TextEncoding    GetBestMimeEncoding();

    const SvxTextEncodingTable*     GetTextEncodingTable() const
                            { return m_pEncTable; }

    void                InsertTextEncoding( const rtl_TextEncoding nEnc,
                            USHORT nPos = LISTBOX_APPEND );

    void                InsertTextEncoding( const rtl_TextEncoding nEnc,
                            const String& rEntry,
                            USHORT nPos = LISTBOX_APPEND );

    void                RemoveTextEncoding( const rtl_TextEncoding nEnc );

    void                SelectTextEncoding( const rtl_TextEncoding nEnc,
                            BOOL bSelect = TRUE );

    rtl_TextEncoding    GetSelectTextEncoding() const;

    const String&       GetSelectTextString() const;

    BOOL                IsTextEncodingSelected( const rtl_TextEncoding nEnc ) const;
};

#endif

<|endoftext|>


<commit_before>/*=========================================================================

Library   : Image Registration Toolkit (IRTK)
Module    : $Id$
Copyright : Imperial College, Department of Computing
Visual Information Processing (VIP), 2008 onwards
Date      : $Date$
Version   : $Revision$
Changes   : $Author$

=========================================================================*/

#include <irtkImage.h>

#include <irtkFileToImage.h>

#include <irtkTransformation.h>

char *input_name = NULL, *output_name = NULL, *dof_name  = NULL, *output_header = NULL;

void usage()
{
	cerr << "Usage: headertool [in] [out] <options>\n" << endl;
	cerr << "where <options> can be one or more of the following:\n";
	cerr << "<-size        dx dy dz>                      \t Voxel size   (in mm)\n";
	cerr << "<-tsize       dt>                            \t Voxel size   (in ms)\n";
	cerr << "<-orientation x1 x2 x3   y1 y2 y3  z1 z2 z3> \t Image orientation\n";
	cerr << "<-origin      x  y  z>                       \t Image origin (in mm)\n";
	cerr << "<-torigin     t>                             \t Image origin (in ms)\n";
	cerr << "<-outputheader matrixfilename>               \t Output header in matrix\n";
	cerr << "<-target      image>                         \t Copy header from target image\n\n";
    cerr << "<-rmatr>									  \t Remove orientation and origon information\n";
    cerr << "<-ref image>								  \t Copy reference's coordinate system (orientation and origin)\n";
    cerr << "<-reforigin image>						      \t Copy reference's origin\n";
    cerr << "<-dofin       transformation>                \t Apply transformation to axis, spacing and origin information in the" << endl;
	cerr << "	                                            \t header. Transformation may be rigid or affine and with no shearing.\n";
	exit(1);
}

int main(int argc, char **argv)
{
	int i, ok, rmatr, refon,refoon;
	double xsize, ysize, zsize, tsize, xaxis[3], yaxis[3], zaxis[3], origin[4];
	irtkTransformation *transformation = NULL;
    irtkImageAttributes refatr;

	if (argc < 3) {
		usage();
	}

    rmatr  = 0;
    refon = 0;
    refoon = 0;

	// Parse filenames
	input_name  = argv[1];
	argc--;
	argv++;
	output_name = argv[1];
	argc--;
	argv++;

	// Read image
	irtkFileToImage *reader = irtkFileToImage::New(input_name);
	irtkBaseImage *image = reader->GetOutput();

	while (argc > 1) {
		ok = false;
		if ((ok == false) && (strcmp(argv[1], "-dofin") == 0)) {
			argc--;
			argv++;
			dof_name = argv[1];
			argc--;
			argv++;
			ok = true;
		}
		if ((ok == false) && (strcmp(argv[1], "-outputheader") == 0)) {
			argc--;
			argv++;
			output_header = argv[1];
			argc--;
			argv++;
			ok = true;
		}
		if ((ok == false) && (strcmp(argv[1], "-target") == 0)) {
			argc--;
			argv++;
			irtkGreyImage target(argv[1]);
			argc--;
			argv++;
			target.GetPixelSize(&xsize, &ysize, &zsize);
			image->PutPixelSize(xsize, ysize, zsize);
			target.GetOrientation(xaxis, yaxis, zaxis);
			image->PutOrientation(xaxis, yaxis, zaxis);
			target.GetOrigin(origin[0], origin[1], origin[2]);
			image->PutOrigin(origin[0], origin[1], origin[2]);
			ok = true;
		}
        if ((ok == false) && strcmp(argv[1], "-rmatr") == 0) {
            argc--;
            argv++;
            rmatr = 1;
            ok = true;
        }
        if ((ok == false) && strcmp(argv[1], "-ref") == 0) {
            argc--;
            argv++;
            refon = 1;
            ok = true;
            irtkGreyImage ref(argv[1]);
            refatr = ref.GetImageAttributes();
            argc--;
            argv++;
        }
        if ((ok == false) && strcmp(argv[1], "-reforigin") == 0) {
            argc--;
            argv++;
            refoon = 1;
            ok = true;
            irtkGreyImage ref(argv[1]);
            refatr = ref.GetImageAttributes();
            argc--;
            argv++;
        }
		if ((ok == false) && (strcmp(argv[1], "-size") == 0)) {
			argc--;
			argv++;
			xsize = atof(argv[1]);
			argc--;
			argv++;
			ysize = atof(argv[1]);
			argc--;
			argv++;
			zsize = atof(argv[1]);
			argc--;
			argv++;
			ok = true;

			// Set voxel size
			image->PutPixelSize(xsize, ysize, zsize);
		}
		if ((ok == false) && (strcmp(argv[1], "-tsize") == 0)) {
			argc--;
			argv++;
			tsize = atof(argv[1]);
			argc--;
			argv++;
			ok = true;

			// Set voxel size
			image->GetPixelSize(&xsize, &ysize, &zsize);
			image->PutPixelSize(xsize, ysize, zsize, tsize);
		}
		if ((ok == false) && (strcmp(argv[1], "-orientation") == 0)) {
			argc--;
			argv++;
			xaxis[0] = atof(argv[1]);
			argc--;
			argv++;
			xaxis[1] = atof(argv[1]);
			argc--;
			argv++;
			xaxis[2] = atof(argv[1]);
			argc--;
			argv++;
			yaxis[0] = atof(argv[1]);
			argc--;
			argv++;
			yaxis[1] = atof(argv[1]);
			argc--;
			argv++;
			yaxis[2] = atof(argv[1]);
			argc--;
			argv++;
			zaxis[0] = atof(argv[1]);
			argc--;
			argv++;
			zaxis[1] = atof(argv[1]);
			argc--;
			argv++;
			zaxis[2] = atof(argv[1]);
			argc--;
			argv++;
			ok = true;

			// Set orientation (third argument now required)
			image->PutOrientation(xaxis, yaxis, zaxis);
		}
		if ((ok == false) && (strcmp(argv[1], "-origin") == 0)) {
			argc--;
			argv++;
			origin[0] = atof(argv[1]);
			argc--;
			argv++;
			origin[1] = atof(argv[1]);
			argc--;
			argv++;
			origin[2] = atof(argv[1]);
			argc--;
			argv++;
			ok = true;

			// Set origin
			image->PutOrigin(origin[0], origin[1], origin[2]);
		}
		if ((ok == false) && (strcmp(argv[1], "-torigin") == 0)) {
			argc--;
			argv++;
			origin[3] = atof(argv[1]);
			argc--;
			argv++;
			ok = true;

			// Set origin
			image->GetOrigin(origin[0], origin[1], origin[2]);
			image->PutOrigin(origin[0], origin[1], origin[2], origin[3]);
		}

		if (ok == false) {
			cout << "Can't parse argument: " << argv[1] << endl;
			usage();
		}
	}

	// Transform header
	if (dof_name != NULL) {

		// Read transformation
		transformation = irtkTransformation::New(dof_name);

		if (strcmp(transformation->NameOfClass(), "irtkAffineTransformation") == 0) {
			irtkAffineTransformation *affineTransf = dynamic_cast<irtkAffineTransformation*> (transformation);

			if (fabs(affineTransf->GetShearXY()) +
					fabs(affineTransf->GetShearXZ()) +
					fabs(affineTransf->GetShearYZ()) > 0.001){
				cerr << "Affine transformation provided contains shearing : Cannot be used to modify header" << endl;
				exit(1);
			}
		} else if (strcmp(transformation->NameOfClass(), "irtkRigidTransformation") != 0) {
			cerr<<"header tool: Can only modify header with a rigid or a no-shear affine transformation"<<endl;
			exit(1);
		}

		irtkImageAttributes attr = image->GetImageAttributes();

		// Origin:

		transformation->Transform(attr._xorigin, attr._yorigin, attr._zorigin);

		// Grid spacings:

		irtkVector v(3);
		irtkVector u(3);

		// Zero vector.
		u.Initialize(3);
		transformation->Transform(u(0), u(1), u(2));

		for (i = 0; i < 3; i++){
			v(i) = attr._xaxis[i];
		}
		transformation->Transform(v(0), v(1), v(2));
		v = v - u;
		attr._dx = attr._dx * v.Norm();

		for (i = 0; i < 3; i++){
			v(i) = attr._yaxis[i];
		}
		transformation->Transform(v(0), v(1), v(2));
		v = v - u;
		attr._dy = attr._dy * v.Norm();

		for (i = 0; i < 3; i++){
			v(i) = attr._zaxis[i];
		}
		transformation->Transform(v(0), v(1), v(2));
		v = v - u;
		attr._dz = attr._dz * v.Norm();

		// Axes:

		// Isolate rotation part of transformation.
		irtkRigidTransformation rotation;
		for (i = 3; i < 6; i++){
			rotation.Put(i, transformation->Get(i));
		}

		rotation.Transform(attr._xaxis[0], attr._xaxis[1], attr._xaxis[2]);
		rotation.Transform(attr._yaxis[0], attr._yaxis[1], attr._yaxis[2]);
		rotation.Transform(attr._zaxis[0], attr._zaxis[1], attr._zaxis[2]);

		// Grid size:

		// Remains the same so no need to do anything.

		// Update image attributes
        image->PutOrientation(attr._xaxis,attr._yaxis,attr._zaxis);
        image->PutOrigin(attr._xorigin,attr._yorigin,attr._zorigin);
        image->PutPixelSize(attr._dx,attr._dy,attr._dz);

        delete transformation;
	}

    // Remove Attributes
    if (rmatr == 1) {
        irtkImageAttributes tmpatr;
        image->PutOrientation(tmpatr._xaxis,tmpatr._yaxis,tmpatr._zaxis);
        image->PutOrigin(tmpatr._xorigin,tmpatr._yorigin,tmpatr._zorigin);
    }

    // use reference image's setting
    if (refon == 1) {
        image->PutOrientation(refatr._xaxis,refatr._yaxis,refatr._zaxis);
        image->PutOrigin(refatr._xorigin,refatr._yorigin,refatr._zorigin);
    }

    // use reference image's setting
    if (refoon == 1) {
        image->PutOrigin(refatr._xorigin,refatr._yorigin,refatr._zorigin);
    }

	image->Write(output_name);

	if(output_header != NULL){
		irtkMatrix header(4,4);
		header = image->GetImageToWorldMatrix();
		header.Write(output_header);
	}

    delete image;
    delete reader;

	return 0;
}

<commit_msg>General tidying.<commit_after>/*=========================================================================

Library   : Image Registration Toolkit (IRTK)
Module    : $Id$
Copyright : Imperial College, Department of Computing
Visual Information Processing (VIP), 2008 onwards
Date      : $Date$
Version   : $Revision$
Changes   : $Author$

=========================================================================*/

#include <irtkImage.h>

#include <irtkFileToImage.h>

#include <irtkTransformation.h>

char *input_name = NULL, *output_name = NULL, *dof_name  = NULL, *output_matrix_name = NULL;

void usage()
{
	cerr << "Usage: headertool [in] [out] <options>" << endl;
	cerr << "where <options> can be one or more of the following:" << endl;

	cerr << "<-size        dx dy dz>                         Voxel size   (in mm)" << endl;
	cerr << "<-tsize       dt>                               Voxel size   (in ms)" << endl;
	cerr << "<-orientation x1 x2 x3   y1 y2 y3  z1 z2 z3>    Image orientation" << endl;
	cerr << "<-origin      x  y  z>                          Image origin (in mm)" << endl;
	cerr << "<-torigin     t>                                Image origin (in ms)" << endl;
	cerr << " " << endl;
	cerr << "<-target                image>                  Copy target image's orientation, origin and pixel size" << endl;
	cerr << "<-targetOriginAndOrient image>                  Copy target image's orientation and origin)" << endl;
	cerr << "<-targetOrigin          image>                  Copy target image's origin only" << endl;
	cerr << " " << endl;
	cerr << "<-writeMatrix           filename>               Save image to world matrix to a file" << endl;
	cerr << "<-reset>                                        Reset orientation and origin information to default values" << endl;
	cerr << " " << endl;
	cerr << "<-dofin                 transformation>         Apply transformation to axis, spacing and origin information in the" << endl;
	cerr << "                                                header. Transformation may be rigid or affine and with no shearing." << endl;
	exit(1);
}

int main(int argc, char **argv)
{
	int i, ok, resetAttributes, useRefImageOriginAndOrientation, useRefImageOrigin;
	double xsize, ysize, zsize, tsize, xaxis[3], yaxis[3], zaxis[3], origin[4];
	irtkTransformation *transformation = NULL;
	irtkImageAttributes refImageAttr;

	if (argc < 3) {
		usage();
	}

	resetAttributes  = 0;
	useRefImageOriginAndOrientation = 0;
	useRefImageOrigin = 0;

	// Parse filenames
	input_name  = argv[1];
	argc--;
	argv++;
	output_name = argv[1];
	argc--;
	argv++;

	// Read image
	irtkFileToImage *reader = irtkFileToImage::New(input_name);
	irtkBaseImage *image = reader->GetOutput();

	while (argc > 1) {
		ok = false;
		if ((ok == false) && (strcmp(argv[1], "-dofin") == 0)) {
			argc--;
			argv++;
			dof_name = argv[1];
			argc--;
			argv++;
			ok = true;
		}
		if ((ok == false) && (strcmp(argv[1], "-writeMatrix") == 0)) {
			argc--;
			argv++;
			output_matrix_name = argv[1];
			argc--;
			argv++;
			ok = true;
		}
		if ((ok == false) && (strcmp(argv[1], "-target") == 0)) {
			argc--;
			argv++;
			irtkGreyImage target(argv[1]);
			argc--;
			argv++;
			target.GetPixelSize(&xsize, &ysize, &zsize);
			image->PutPixelSize(xsize, ysize, zsize);
			target.GetOrientation(xaxis, yaxis, zaxis);
			image->PutOrientation(xaxis, yaxis, zaxis);
			target.GetOrigin(origin[0], origin[1], origin[2]);
			image->PutOrigin(origin[0], origin[1], origin[2]);
			ok = true;
		}
		if ((ok == false) && strcmp(argv[1], "-reset") == 0) {
			argc--;
			argv++;
			resetAttributes = 1;
			ok = true;
		}
		if ((ok == false) && strcmp(argv[1], "-targetOriginAndOrient") == 0) {
			argc--;
			argv++;
			useRefImageOriginAndOrientation = 1;
			ok = true;
			irtkGreyImage ref(argv[1]);
			refImageAttr = ref.GetImageAttributes();
			argc--;
			argv++;
		}
		if ((ok == false) && strcmp(argv[1], "-targetOrigin") == 0) {
			argc--;
			argv++;
			useRefImageOrigin = 1;
			ok = true;
			irtkGreyImage ref(argv[1]);
			refImageAttr = ref.GetImageAttributes();
			argc--;
			argv++;
		}
		if ((ok == false) && (strcmp(argv[1], "-size") == 0)) {
			argc--;
			argv++;
			xsize = atof(argv[1]);
			argc--;
			argv++;
			ysize = atof(argv[1]);
			argc--;
			argv++;
			zsize = atof(argv[1]);
			argc--;
			argv++;
			ok = true;

			// Set voxel size
			image->PutPixelSize(xsize, ysize, zsize);
		}
		if ((ok == false) && (strcmp(argv[1], "-tsize") == 0)) {
			argc--;
			argv++;
			tsize = atof(argv[1]);
			argc--;
			argv++;
			ok = true;

			// Set voxel size
			image->GetPixelSize(&xsize, &ysize, &zsize);
			image->PutPixelSize(xsize, ysize, zsize, tsize);
		}
		if ((ok == false) && (strcmp(argv[1], "-orientation") == 0)) {
			argc--;
			argv++;
			xaxis[0] = atof(argv[1]);
			argc--;
			argv++;
			xaxis[1] = atof(argv[1]);
			argc--;
			argv++;
			xaxis[2] = atof(argv[1]);
			argc--;
			argv++;
			yaxis[0] = atof(argv[1]);
			argc--;
			argv++;
			yaxis[1] = atof(argv[1]);
			argc--;
			argv++;
			yaxis[2] = atof(argv[1]);
			argc--;
			argv++;
			zaxis[0] = atof(argv[1]);
			argc--;
			argv++;
			zaxis[1] = atof(argv[1]);
			argc--;
			argv++;
			zaxis[2] = atof(argv[1]);
			argc--;
			argv++;
			ok = true;

			// Set orientation (third argument now required)
			image->PutOrientation(xaxis, yaxis, zaxis);
		}
		if ((ok == false) && (strcmp(argv[1], "-origin") == 0)) {
			argc--;
			argv++;
			origin[0] = atof(argv[1]);
			argc--;
			argv++;
			origin[1] = atof(argv[1]);
			argc--;
			argv++;
			origin[2] = atof(argv[1]);
			argc--;
			argv++;
			ok = true;

			// Set origin
			image->PutOrigin(origin[0], origin[1], origin[2]);
		}
		if ((ok == false) && (strcmp(argv[1], "-torigin") == 0)) {
			argc--;
			argv++;
			origin[3] = atof(argv[1]);
			argc--;
			argv++;
			ok = true;

			// Set origin
			image->GetOrigin(origin[0], origin[1], origin[2]);
			image->PutOrigin(origin[0], origin[1], origin[2], origin[3]);
		}

		if (ok == false) {
			cout << "Can't parse argument: " << argv[1] << endl;
			usage();
		}
	}

	// Transform header
	if (dof_name != NULL) {

		// Read transformation
		transformation = irtkTransformation::New(dof_name);

		if (strcmp(transformation->NameOfClass(), "irtkAffineTransformation") == 0) {
			irtkAffineTransformation *affineTransf = dynamic_cast<irtkAffineTransformation*> (transformation);

			if (fabs(affineTransf->GetShearXY()) +
					fabs(affineTransf->GetShearXZ()) +
					fabs(affineTransf->GetShearYZ()) > 0.001){
				cerr << "Affine transformation provided contains shearing : Cannot be used to modify header" << endl;
				exit(1);
			}
		} else if (strcmp(transformation->NameOfClass(), "irtkRigidTransformation") != 0) {
			cerr<<"header tool: Can only modify header with a rigid or a no-shear affine transformation"<<endl;
			exit(1);
		}

		irtkImageAttributes attr = image->GetImageAttributes();

		// Origin:

		transformation->Transform(attr._xorigin, attr._yorigin, attr._zorigin);

		// Grid spacings:

		irtkVector v(3);
		irtkVector u(3);

		// Zero vector.
		u.Initialize(3);
		transformation->Transform(u(0), u(1), u(2));

		for (i = 0; i < 3; i++){
			v(i) = attr._xaxis[i];
		}
		transformation->Transform(v(0), v(1), v(2));
		v = v - u;
		attr._dx = attr._dx * v.Norm();

		for (i = 0; i < 3; i++){
			v(i) = attr._yaxis[i];
		}
		transformation->Transform(v(0), v(1), v(2));
		v = v - u;
		attr._dy = attr._dy * v.Norm();

		for (i = 0; i < 3; i++){
			v(i) = attr._zaxis[i];
		}
		transformation->Transform(v(0), v(1), v(2));
		v = v - u;
		attr._dz = attr._dz * v.Norm();

		// Axes:

		// Isolate rotation part of transformation.
		irtkRigidTransformation rotation;
		for (i = 3; i < 6; i++){
			rotation.Put(i, transformation->Get(i));
		}

		rotation.Transform(attr._xaxis[0], attr._xaxis[1], attr._xaxis[2]);
		rotation.Transform(attr._yaxis[0], attr._yaxis[1], attr._yaxis[2]);
		rotation.Transform(attr._zaxis[0], attr._zaxis[1], attr._zaxis[2]);

		// Grid size:

		// Remains the same so no need to do anything.

		// Update image attributes
		image->PutOrientation(attr._xaxis,attr._yaxis,attr._zaxis);
		image->PutOrigin(attr._xorigin,attr._yorigin,attr._zorigin);
		image->PutPixelSize(attr._dx,attr._dy,attr._dz);

		delete transformation;
	}

	// Remove Attributes
	if (resetAttributes == 1) {
		irtkImageAttributes tmpatr;
		image->PutOrientation(tmpatr._xaxis,tmpatr._yaxis,tmpatr._zaxis);
		image->PutOrigin(tmpatr._xorigin,tmpatr._yorigin,tmpatr._zorigin);
	}

	// use reference image's setting
	if (useRefImageOriginAndOrientation == 1) {
		image->PutOrientation(refImageAttr._xaxis,refImageAttr._yaxis,refImageAttr._zaxis);
		image->PutOrigin(refImageAttr._xorigin,refImageAttr._yorigin,refImageAttr._zorigin);
	}

	// use reference image's setting
	if (useRefImageOrigin == 1) {
		image->PutOrigin(refImageAttr._xorigin,refImageAttr._yorigin,refImageAttr._zorigin);
	}

	image->Write(output_name);

	if(output_matrix_name != NULL){
		irtkMatrix header(4,4);
		header = image->GetImageToWorldMatrix();
		header.Write(output_matrix_name);
	}

	delete image;
	delete reader;

	return 0;
}

<|endoftext|>


<commit_before>// (C) 2014 Arek Olek

#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/adjacency_matrix.hpp>

#include <omp.h>

#include "bfs.hpp"
#include "dfs.hpp"
#include "fifodfs.hpp"
#include "fivethree.hpp"
#include "lost.hpp"
#include "rdfs.hpp"
#include "random.hpp"
#include "ilst.hpp"
#include "greedy.hpp"

#include "test_suite.hpp"

#include "debug.hpp"
#include "graph.hpp"
#include "options.hpp"
#include "range.hpp"
#include "timing.hpp"

boost::adjacency_matrix<boost::undirectedS> typedef amatrix;
boost::adjacency_list<boost::hash_setS, boost::vecS, boost::undirectedS> typedef ahash;
boost::adjacency_list<boost::listS, boost::vecS, boost::undirectedS> typedef alist;
boost::adjacency_list<boost::slistS, boost::vecS, boost::undirectedS> typedef aslist;
boost::adjacency_list<boost::setS, boost::vecS, boost::undirectedS> typedef aset;
boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS> typedef avec;

template<class Graph, class Tree>
std::function<Tree(Graph&)> make_construction(std::string name) {
  if (name == "bfs")
    return bfs_tree<Graph, Tree> ;
  if (name == "dfs")
    return dfs_tree<Graph, Tree> ;
  if (name == "rdfs")
    return rdfs_tree<Graph, Tree> ;
  if (name == "rdfs50")
    return rdfs_best_tree<Graph, Tree> ;
  if (name == "fifo")
    return fifo_dfs_tree<Graph, Tree> ;
  if (name == "random")
    return random_tree<Graph, Tree> ;
  if (name == "wilson")
    return wilson_tree<Graph, Tree> ;
  if (name == "greedy")
    return greedy_tree<Graph, Tree> ;
  if (name == "ilst")
    return ilst<Graph, Tree> ;
  if (name == "5/3")
    return five_three_tree<Graph, Tree> ;
  throw std::invalid_argument("Unknown construction method: " + name);
}

template<class Graph>
std::function<unsigned(Graph&)> make_upper(std::string name) {
  if (name == "5/3") {
    return [](const Graph& G) {
      return 5*(num_vertices(G)-3)/6;
    };
  }
  return upper_bound<Graph> ;
}

template <class Graph, class Tree, class Suite, class Strings>
void run(Suite& suite, Strings const & constructions, Strings const & improvements, bool scratch) {
  timing total(CLOCK_REALTIME);
  total.start();
  std::cerr << "Suite size: " << suite.size() << std::endl;
  #pragma omp parallel
  {
    auto id = omp_get_thread_num();
    double elapsed_c, elapsed_i;
    timing timer;
    #pragma omp for schedule(dynamic) nowait
    for(uint i = 0; i < suite.size(); ++i) {
      std::stringstream buffer;
      auto trial = suite.get(i);
      auto G = std::get<0>(trial);
      if(!is_connected(G)) continue;

      for(auto cname : constructions) {
        auto construct = make_construction<Graph, Tree>(cname);
        auto upper = make_upper<Graph>(cname);
        timer.start();
        auto T = construct(G);
        elapsed_c = timer.stop();

        assert(num_edges(T) == num_vertices(T)-1);

        const auto tree(T);

        for(auto iname : improvements) {
          if(scratch) T = tree;

          auto improve = make_improvement<Graph, Tree>(iname);
          timer.start();
          auto rules = improve(G, T);
          elapsed_i = timer.stop();

//  1    2       3      4       5      6         7      8      9             10           11        12     13     14     15
//  run  thread  model  degree  param  vertices  edges  upper  construction  improvement  internal  ctime  itime  steps  rules
          buffer
            << i << '\t'
            << id << '\t'
            << suite.type() << '\t'
            << std::get<1>(trial) << '\t'
            << std::get<2>(trial) << '\t'
            << num_vertices(G) << '\t'
            << num_edges(G) << '\t'
            << upper(G) << '\t'
            << cname << '\t'
            << iname << '\t'
            << num_internal(T) << '\t'
            << elapsed_c << '\t'
            << elapsed_i << '\t'
            << sum(rules) << '\t'
            << join(rules, "-") << '\t'
            << std::endl;
            ;
          //show("graph" + std::to_string(i) + ".dot", G, T);

          if(!scratch) elapsed_c += elapsed_i;
        }
      }
      #pragma omp critical
      std::cout << buffer.str() << std::flush;

      if(id == 0) {
        std::cerr << "\t" << 100*i/suite.size() << "%\t";
        std::cerr << readable(total.stop()) << " elapsed    \r";
      }
    }
  }
  std::cerr << "\t100%\n";
}

template <class Graph, class Tree, class Sizes, class Params, class Strings>
void run(std::string t, unsigned z, Sizes sizes, Params params,
         Strings const & constructions, Strings const & improvements, bool scratch) {
  if (t.find(".xml") != std::string::npos) {
    real_suite<Graph> suite(t, z);
    run<Graph, Tree>(suite, constructions, improvements, scratch);
  } else if (t.find('.') != std::string::npos) {
    file_suite<Graph> suite(t);
    run<Graph, Tree>(suite, constructions, improvements, scratch);
  } else {
    test_suite<Graph> suite(t, z, sizes, params);
    run<Graph, Tree>(suite, constructions, improvements, scratch);
  }
}

int main(int argc, char** argv){
  using std::string;
  using std::vector;

  std::ios_base::sync_with_stdio(0);

  options opt(argc, argv);
  auto z = opt.get<int>("-z", 1);
  auto sizes = opt.getList<unsigned>("-n", {100});
  auto tests = opt.getList<string>("-t", {"gnp+mst"});
  auto degrees = opt.getList<double>("-d", { 3. });
  auto constructions = opt.getList<string>("-c", {"bfs", "dfs", "rdfs", "fifo", "rdfs50", "ilst", "random"});
  auto improvements = opt.getList<string>("-i", {"none", "prieto", "lost-light", "lost", "lost-ex"});
  auto scratch = opt.has("--scratch");

  for(auto t : tests) {
    run<alist, avec>(t, z, sizes, degrees, constructions, improvements, scratch);
  }

  return 0;
}
<commit_msg>update progress output<commit_after>// (C) 2014 Arek Olek

#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/adjacency_matrix.hpp>

#include <omp.h>

#include "bfs.hpp"
#include "dfs.hpp"
#include "fifodfs.hpp"
#include "fivethree.hpp"
#include "lost.hpp"
#include "rdfs.hpp"
#include "random.hpp"
#include "ilst.hpp"
#include "greedy.hpp"

#include "test_suite.hpp"

#include "debug.hpp"
#include "graph.hpp"
#include "options.hpp"
#include "range.hpp"
#include "timing.hpp"

boost::adjacency_matrix<boost::undirectedS> typedef amatrix;
boost::adjacency_list<boost::hash_setS, boost::vecS, boost::undirectedS> typedef ahash;
boost::adjacency_list<boost::listS, boost::vecS, boost::undirectedS> typedef alist;
boost::adjacency_list<boost::slistS, boost::vecS, boost::undirectedS> typedef aslist;
boost::adjacency_list<boost::setS, boost::vecS, boost::undirectedS> typedef aset;
boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS> typedef avec;

template<class Graph, class Tree>
std::function<Tree(Graph&)> make_construction(std::string name) {
  if (name == "bfs")
    return bfs_tree<Graph, Tree> ;
  if (name == "dfs")
    return dfs_tree<Graph, Tree> ;
  if (name == "rdfs")
    return rdfs_tree<Graph, Tree> ;
  if (name == "rdfs50")
    return rdfs_best_tree<Graph, Tree> ;
  if (name == "fifo")
    return fifo_dfs_tree<Graph, Tree> ;
  if (name == "random")
    return random_tree<Graph, Tree> ;
  if (name == "wilson")
    return wilson_tree<Graph, Tree> ;
  if (name == "greedy")
    return greedy_tree<Graph, Tree> ;
  if (name == "ilst")
    return ilst<Graph, Tree> ;
  if (name == "5/3")
    return five_three_tree<Graph, Tree> ;
  throw std::invalid_argument("Unknown construction method: " + name);
}

template<class Graph>
std::function<unsigned(Graph&)> make_upper(std::string name) {
  if (name == "5/3") {
    return [](const Graph& G) {
      return 5*(num_vertices(G)-3)/6;
    };
  }
  return upper_bound<Graph> ;
}

template <class Graph, class Tree, class Suite, class Strings>
void run(Suite& suite, Strings const & constructions, Strings const & improvements, bool scratch) {
  timing total(CLOCK_REALTIME);
  total.start();
  #pragma omp parallel
  {
    auto id = omp_get_thread_num();
    double elapsed_c, elapsed_i;
    timing timer;
    #pragma omp for schedule(dynamic) nowait
    for(uint i = 0; i < suite.size(); ++i) {
      std::stringstream buffer;
      auto trial = suite.get(i);
      auto G = std::get<0>(trial);
      if(!is_connected(G)) continue;

      for(auto cname : constructions) {
        auto construct = make_construction<Graph, Tree>(cname);
        auto upper = make_upper<Graph>(cname);
        timer.start();
        auto T = construct(G);
        elapsed_c = timer.stop();

        assert(num_edges(T) == num_vertices(T)-1);

        const auto tree(T);

        for(auto iname : improvements) {
          if(scratch) T = tree;

          auto improve = make_improvement<Graph, Tree>(iname);
          timer.start();
          auto rules = improve(G, T);
          elapsed_i = timer.stop();

//  1    2       3      4       5      6         7      8      9             10           11        12     13     14     15
//  run  thread  model  degree  param  vertices  edges  upper  construction  improvement  internal  ctime  itime  steps  rules
          buffer
            << i << '\t'
            << id << '\t'
            << suite.type() << '\t'
            << std::get<1>(trial) << '\t'
            << std::get<2>(trial) << '\t'
            << num_vertices(G) << '\t'
            << num_edges(G) << '\t'
            << upper(G) << '\t'
            << cname << '\t'
            << iname << '\t'
            << num_internal(T) << '\t'
            << elapsed_c << '\t'
            << elapsed_i << '\t'
            << sum(rules) << '\t'
            << join(rules, "-") << '\t'
            << std::endl;
            ;
          //show("graph" + std::to_string(i) + ".dot", G, T);

          if(!scratch) elapsed_c += elapsed_i;
        }
      }
      #pragma omp critical
      std::cout << buffer.str() << std::flush;

      if(id == 0) {
        std::cerr << '\t' << 100*(i+1)/suite.size() << "% of " << suite.size();
        std::cerr << '\t' << readable(total.stop()) << " elapsed    \r";
      }
    }
  }
  std::cerr << "\t100%\n";
}

template <class Graph, class Tree, class Sizes, class Params, class Strings>
void run(std::string t, unsigned z, Sizes sizes, Params params,
         Strings const & constructions, Strings const & improvements, bool scratch) {
  if (t.find(".xml") != std::string::npos) {
    real_suite<Graph> suite(t, z);
    run<Graph, Tree>(suite, constructions, improvements, scratch);
  } else if (t.find('.') != std::string::npos) {
    file_suite<Graph> suite(t);
    run<Graph, Tree>(suite, constructions, improvements, scratch);
  } else {
    test_suite<Graph> suite(t, z, sizes, params);
    run<Graph, Tree>(suite, constructions, improvements, scratch);
  }
}

int main(int argc, char** argv){
  using std::string;
  using std::vector;

  std::ios_base::sync_with_stdio(0);

  options opt(argc, argv);
  auto z = opt.get<int>("-z", 1);
  auto sizes = opt.getList<unsigned>("-n", {100});
  auto tests = opt.getList<string>("-t", {"gnp+mst"});
  auto degrees = opt.getList<double>("-d", { 3. });
  auto constructions = opt.getList<string>("-c", {"bfs", "dfs", "rdfs", "fifo", "rdfs50", "ilst", "random"});
  auto improvements = opt.getList<string>("-i", {"none", "prieto", "lost-light", "lost", "lost-ex"});
  auto scratch = opt.has("--scratch");

  for(auto t : tests) {
    run<alist, avec>(t, z, sizes, degrees, constructions, improvements, scratch);
  }

  return 0;
}
<|endoftext|>