<commit_before>/*------------------------------------------------------------------------
 *  Vulkan Conformance Tests
 * ------------------------
 *
 * Copyright (c) 2015 The Khronos Group Inc.
 * Copyright (c) 2015 Samsung Electronics Co., Ltd.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and/or associated documentation files (the
 * "Materials"), to deal in the Materials without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Materials, and to
 * permit persons to whom the Materials are furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice(s) and this permission notice shall be included
 * in all copies or substantial portions of the Materials.
 *
 * The Materials are Confidential Information as defined by the
 * Khronos Membership Agreement until designated non-confidential by Khronos,
 * at which point this condition clause shall be removed.
 *
 * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
 *
 *//*!
 * \file
 * \brief Vulkan Buffers Tests
 *//*--------------------------------------------------------------------*/

#include "vktApiBufferTests.hpp"

#include "deStringUtil.hpp"
#include "gluVarType.hpp"
#include "tcuTestLog.hpp"
#include "vkPrograms.hpp"
#include "vktTestCase.hpp"

namespace vkt
{

using namespace vk;

namespace api
{

namespace
{

struct BufferCaseParameters
{
	VkBufferUsageFlags	usage;
	VkBufferCreateFlags	flags;
	VkSharingMode		sharingMode;
};

class BufferTestInstance : public TestInstance
{
public:
								BufferTestInstance			(Context&				ctx,
															 BufferCaseParameters	testCase)
									: TestInstance	(ctx)
									, m_testCase	(testCase)
								{}
	virtual tcu::TestStatus		iterate						(void);
	tcu::TestStatus				bufferCreateAndAllocTest	(VkDeviceSize		size);

private:
	BufferCaseParameters		m_testCase;
};

class BuffersTestCase : public TestCase
{
public:
							BuffersTestCase		(tcu::TestContext&		testCtx,
												 const std::string&		name,
												 const std::string&		description,
												 BufferCaseParameters	testCase)
								: TestCase(testCtx, name, description)
								, m_testCase(testCase)
							{}

	virtual					~BuffersTestCase	(void) {}
	virtual TestInstance*	createInstance		(Context&				ctx) const
							{
								tcu::TestLog& log	= m_testCtx.getLog();
								log << tcu::TestLog::Message << getBufferUsageFlagsStr(m_testCase.usage) << tcu::TestLog::EndMessage;
								return new BufferTestInstance(ctx, m_testCase);
							}

private:
	BufferCaseParameters		m_testCase;
};

 tcu::TestStatus BufferTestInstance::bufferCreateAndAllocTest (VkDeviceSize size)
{
	const VkDevice			vkDevice	= m_context.getDevice();
	const DeviceInterface&	vk			= m_context.getDeviceInterface();
	VkBuffer				testBuffer;
	VkMemoryRequirements	memReqs;
	VkDeviceMemory			memory;

	// Create buffer
	{
		const deUint32					queueFamilyIndex	= m_context.getUniversalQueueFamilyIndex();
		const VkBufferCreateInfo		bufferParams		=
		{
			VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
			DE_NULL,
			m_testCase.flags,
			size,
			m_testCase.usage,
			m_testCase.sharingMode,
			1u,										//	deUint32			queueFamilyCount;
			&queueFamilyIndex,
		};

		if (vk.createBuffer(vkDevice, &bufferParams, (const VkAllocationCallbacks*)DE_NULL, &testBuffer) != VK_SUCCESS)
			return tcu::TestStatus::fail("Buffer creation failed! (requested memory size: " + de::toString(size) + ")");

		vk.getBufferMemoryRequirements(vkDevice, testBuffer, &memReqs);

		if (size > memReqs.size)
		{
			std::ostringstream errorMsg;
			errorMsg << "Requied memory size (" << memReqs.size << " bytes) smaller than the buffer's size (" << size << " bytes)!";
			return tcu::TestStatus::fail(errorMsg.str());
		}
	}

	// Allocate and bind memory
	{
		const VkMemoryAllocateInfo memAlloc =
		{
			VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
			NULL,
			memReqs.size,
			0										//	deUint32		memoryTypeIndex
		};

		if (vk.allocateMemory(vkDevice, &memAlloc, (const VkAllocationCallbacks*)DE_NULL, &memory) != VK_SUCCESS)
			return tcu::TestStatus::fail("Alloc memory failed! (requested memory size: " + de::toString(size) + ")");

		if (vk.bindBufferMemory(vkDevice, testBuffer, memory, 0) != VK_SUCCESS)
			return tcu::TestStatus::fail("Bind buffer memory failed! (requested memory size: " + de::toString(size) + ")");
	}

	vk.freeMemory(vkDevice, memory, (const VkAllocationCallbacks*)DE_NULL);
	vk.destroyBuffer(vkDevice, testBuffer, (const VkAllocationCallbacks*)DE_NULL);

	return tcu::TestStatus::pass("Buffer test");
}

tcu::TestStatus BufferTestInstance::iterate (void)
{
	const VkDeviceSize testSizes[] =
	{
		1,
		1181,
		15991,
		16384
	};
	tcu::TestStatus	testStatus					= tcu::TestStatus::pass("Buffer test");

	for (int i = 0; i < DE_LENGTH_OF_ARRAY(testSizes); i++)
	{
		if ((testStatus = bufferCreateAndAllocTest(testSizes[i])).getCode() != QP_TEST_RESULT_PASS)
			return testStatus;
	}

	if (m_testCase.usage & (VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT))
	{
		const VkPhysicalDevice		vkPhysicalDevice	= m_context.getPhysicalDevice();
		const InstanceInterface&	vkInstance			= m_context.getInstanceInterface();
		VkPhysicalDeviceProperties	props;

		vkInstance.getPhysicalDeviceProperties(vkPhysicalDevice, &props);

		testStatus = bufferCreateAndAllocTest(props.limits.maxTexelBufferElements);
	}

	return testStatus;
}

} // anonymous

 tcu::TestCaseGroup* createBufferTests (tcu::TestContext& testCtx)
{
	const VkBufferUsageFlags bufferUsageModes[] =
	{
		VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
		VK_BUFFER_USAGE_TRANSFER_DST_BIT,
		VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT,
		VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT,
		VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
		VK_BUFFER_USAGE_STORAGE_BUFFER_BIT,
		VK_BUFFER_USAGE_INDEX_BUFFER_BIT,
		VK_BUFFER_USAGE_VERTEX_BUFFER_BIT,
		VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT
	};

	const VkBufferCreateFlags bufferCreateFlags[] =
	{
		VK_BUFFER_CREATE_SPARSE_BINDING_BIT,
		VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT,
		VK_BUFFER_CREATE_SPARSE_ALIASED_BIT
	};

	de::MovePtr<tcu::TestCaseGroup>	buffersTests	(new tcu::TestCaseGroup(testCtx, "buffer", "Buffer Tests"));

	deUint32	numberOfBufferUsageFlags			= DE_LENGTH_OF_ARRAY(bufferUsageModes);
	deUint32	numberOfBufferCreateFlags			= DE_LENGTH_OF_ARRAY(bufferCreateFlags);
	deUint32	maximumValueOfBufferUsageFlags		= (1 << (numberOfBufferUsageFlags - 1)) - 1;
	deUint32	maximumValueOfBufferCreateFlags		= (1 << (numberOfBufferCreateFlags)) - 1;

	for (deUint32 combinedBufferCreateFlags = 0; combinedBufferCreateFlags <= maximumValueOfBufferCreateFlags; combinedBufferCreateFlags++)
	{
		for (deUint32 combinedBufferUsageFlags = 0; combinedBufferUsageFlags <= maximumValueOfBufferUsageFlags; combinedBufferUsageFlags++)
		{
			BufferCaseParameters	testParams =
			{
				combinedBufferUsageFlags,
				combinedBufferCreateFlags,
				VK_SHARING_MODE_EXCLUSIVE
			};
			std::ostringstream	testName;
			std::ostringstream	testDescription;
			testName << "createBuffer_" << combinedBufferUsageFlags << "_" << combinedBufferCreateFlags;
			testDescription << "vkCreateBuffer test " << combinedBufferUsageFlags << " " << combinedBufferCreateFlags;
			buffersTests->addChild(new BuffersTestCase(testCtx, testName.str(), testDescription.str(), testParams));
		}
	}

	return buffersTests.release();
}

} // api
} // vk
<commit_msg>api.buffer.createBuffer: buffer usage cannot be 0.<commit_after>/*------------------------------------------------------------------------
 *  Vulkan Conformance Tests
 * ------------------------
 *
 * Copyright (c) 2015 The Khronos Group Inc.
 * Copyright (c) 2015 Samsung Electronics Co., Ltd.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and/or associated documentation files (the
 * "Materials"), to deal in the Materials without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Materials, and to
 * permit persons to whom the Materials are furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice(s) and this permission notice shall be included
 * in all copies or substantial portions of the Materials.
 *
 * The Materials are Confidential Information as defined by the
 * Khronos Membership Agreement until designated non-confidential by Khronos,
 * at which point this condition clause shall be removed.
 *
 * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
 *
 *//*!
 * \file
 * \brief Vulkan Buffers Tests
 *//*--------------------------------------------------------------------*/

#include "vktApiBufferTests.hpp"

#include "deStringUtil.hpp"
#include "gluVarType.hpp"
#include "tcuTestLog.hpp"
#include "vkPrograms.hpp"
#include "vktTestCase.hpp"

namespace vkt
{

using namespace vk;

namespace api
{

namespace
{

struct BufferCaseParameters
{
	VkBufferUsageFlags	usage;
	VkBufferCreateFlags	flags;
	VkSharingMode		sharingMode;
};

class BufferTestInstance : public TestInstance
{
public:
								BufferTestInstance			(Context&				ctx,
															 BufferCaseParameters	testCase)
									: TestInstance	(ctx)
									, m_testCase	(testCase)
								{}
	virtual tcu::TestStatus		iterate						(void);
	tcu::TestStatus				bufferCreateAndAllocTest	(VkDeviceSize		size);

private:
	BufferCaseParameters		m_testCase;
};

class BuffersTestCase : public TestCase
{
public:
							BuffersTestCase		(tcu::TestContext&		testCtx,
												 const std::string&		name,
												 const std::string&		description,
												 BufferCaseParameters	testCase)
								: TestCase(testCtx, name, description)
								, m_testCase(testCase)
							{}

	virtual					~BuffersTestCase	(void) {}
	virtual TestInstance*	createInstance		(Context&				ctx) const
							{
								tcu::TestLog& log	= m_testCtx.getLog();
								log << tcu::TestLog::Message << getBufferUsageFlagsStr(m_testCase.usage) << tcu::TestLog::EndMessage;
								return new BufferTestInstance(ctx, m_testCase);
							}

private:
	BufferCaseParameters		m_testCase;
};

 tcu::TestStatus BufferTestInstance::bufferCreateAndAllocTest (VkDeviceSize size)
{
	const VkDevice			vkDevice	= m_context.getDevice();
	const DeviceInterface&	vk			= m_context.getDeviceInterface();
	VkBuffer				testBuffer;
	VkMemoryRequirements	memReqs;
	VkDeviceMemory			memory;

	// Create buffer
	{
		const deUint32					queueFamilyIndex	= m_context.getUniversalQueueFamilyIndex();
		const VkBufferCreateInfo		bufferParams		=
		{
			VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
			DE_NULL,
			m_testCase.flags,
			size,
			m_testCase.usage,
			m_testCase.sharingMode,
			1u,										//	deUint32			queueFamilyCount;
			&queueFamilyIndex,
		};

		if (vk.createBuffer(vkDevice, &bufferParams, (const VkAllocationCallbacks*)DE_NULL, &testBuffer) != VK_SUCCESS)
			return tcu::TestStatus::fail("Buffer creation failed! (requested memory size: " + de::toString(size) + ")");

		vk.getBufferMemoryRequirements(vkDevice, testBuffer, &memReqs);

		if (size > memReqs.size)
		{
			std::ostringstream errorMsg;
			errorMsg << "Requied memory size (" << memReqs.size << " bytes) smaller than the buffer's size (" << size << " bytes)!";
			return tcu::TestStatus::fail(errorMsg.str());
		}
	}

	// Allocate and bind memory
	{
		const VkMemoryAllocateInfo memAlloc =
		{
			VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
			NULL,
			memReqs.size,
			0										//	deUint32		memoryTypeIndex
		};

		if (vk.allocateMemory(vkDevice, &memAlloc, (const VkAllocationCallbacks*)DE_NULL, &memory) != VK_SUCCESS)
			return tcu::TestStatus::fail("Alloc memory failed! (requested memory size: " + de::toString(size) + ")");

		if (vk.bindBufferMemory(vkDevice, testBuffer, memory, 0) != VK_SUCCESS)
			return tcu::TestStatus::fail("Bind buffer memory failed! (requested memory size: " + de::toString(size) + ")");
	}

	vk.freeMemory(vkDevice, memory, (const VkAllocationCallbacks*)DE_NULL);
	vk.destroyBuffer(vkDevice, testBuffer, (const VkAllocationCallbacks*)DE_NULL);

	return tcu::TestStatus::pass("Buffer test");
}

tcu::TestStatus BufferTestInstance::iterate (void)
{
	const VkDeviceSize testSizes[] =
	{
		1,
		1181,
		15991,
		16384
	};
	tcu::TestStatus	testStatus					= tcu::TestStatus::pass("Buffer test");

	for (int i = 0; i < DE_LENGTH_OF_ARRAY(testSizes); i++)
	{
		if ((testStatus = bufferCreateAndAllocTest(testSizes[i])).getCode() != QP_TEST_RESULT_PASS)
			return testStatus;
	}

	if (m_testCase.usage & (VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT))
	{
		const VkPhysicalDevice		vkPhysicalDevice	= m_context.getPhysicalDevice();
		const InstanceInterface&	vkInstance			= m_context.getInstanceInterface();
		VkPhysicalDeviceProperties	props;

		vkInstance.getPhysicalDeviceProperties(vkPhysicalDevice, &props);

		testStatus = bufferCreateAndAllocTest(props.limits.maxTexelBufferElements);
	}

	return testStatus;
}

} // anonymous

 tcu::TestCaseGroup* createBufferTests (tcu::TestContext& testCtx)
{
	const VkBufferUsageFlags bufferUsageModes[] =
	{
		VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
		VK_BUFFER_USAGE_TRANSFER_DST_BIT,
		VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT,
		VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT,
		VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
		VK_BUFFER_USAGE_STORAGE_BUFFER_BIT,
		VK_BUFFER_USAGE_INDEX_BUFFER_BIT,
		VK_BUFFER_USAGE_VERTEX_BUFFER_BIT,
		VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT
	};

	const VkBufferCreateFlags bufferCreateFlags[] =
	{
		VK_BUFFER_CREATE_SPARSE_BINDING_BIT,
		VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT,
		VK_BUFFER_CREATE_SPARSE_ALIASED_BIT
	};

	de::MovePtr<tcu::TestCaseGroup>	buffersTests	(new tcu::TestCaseGroup(testCtx, "buffer", "Buffer Tests"));

	deUint32	numberOfBufferUsageFlags			= DE_LENGTH_OF_ARRAY(bufferUsageModes);
	deUint32	numberOfBufferCreateFlags			= DE_LENGTH_OF_ARRAY(bufferCreateFlags);
	deUint32	maximumValueOfBufferUsageFlags		= (1 << (numberOfBufferUsageFlags - 1)) - 1;
	deUint32	maximumValueOfBufferCreateFlags		= (1 << (numberOfBufferCreateFlags)) - 1;

	for (deUint32 combinedBufferCreateFlags = 0; combinedBufferCreateFlags <= maximumValueOfBufferCreateFlags; combinedBufferCreateFlags++)
	{
		for (deUint32 combinedBufferUsageFlags = 1; combinedBufferUsageFlags <= maximumValueOfBufferUsageFlags; combinedBufferUsageFlags++)
		{
			BufferCaseParameters	testParams =
			{
				combinedBufferUsageFlags,
				combinedBufferCreateFlags,
				VK_SHARING_MODE_EXCLUSIVE
			};
			std::ostringstream	testName;
			std::ostringstream	testDescription;
			testName << "createBuffer_" << combinedBufferUsageFlags << "_" << combinedBufferCreateFlags;
			testDescription << "vkCreateBuffer test " << combinedBufferUsageFlags << " " << combinedBufferCreateFlags;
			buffersTests->addChild(new BuffersTestCase(testCtx, testName.str(), testDescription.str(), testParams));
		}
	}

	return buffersTests.release();
}

} // api
} // vk
<|endoftext|>


<commit_before>#include "game_window.h"
#include "command_menu.h"
#include "../parser_yaml/graphics_parser.h"
using namespace std;

CommandMenu::CommandMenu(GameWindow& owner, GraphicsParser& graphicsParser) :
	owner(owner),
	offset(0, owner.alto_pantalla - graphicsParser.getPantalla().hud_alto),
	size((owner.ancho_pantalla-graphicsParser.getPantalla().minimapa_ancho)/2, graphicsParser.getPantalla().hud_alto)
{
	isVisibleProducer = false;
	isVisibleWorker = false;
	isVisibleUnit = false;
	showOptions = false;
	currentSelection = nullptr;
}

CommandMenu::~CommandMenu() {
}

void CommandMenu::visit(Entity& entity) {
}
void CommandMenu::visit(Unit& entity) {
	visit((Entity&)entity);
	outText = outText + owner.completeLine("[] Ir", size.x);
	outText = outText + owner.completeLine("[a] Atacar", size.x);
	outText = outText + owner.completeLine("[f] Seguir", size.x);
	outText = outText + owner.completeLine("[s] Parar", size.x);
	isVisibleUnit = true;
}
void CommandMenu::visit(Worker& entity) {
	if (!showOptions) {
		visit((Unit&)entity);
		outText = outText + owner.completeLine("[r] Reparar", size.x);
		outText = outText + owner.completeLine("[g] Recolectar", size.x);
		outText = outText + owner.completeLine("[c] Construir", size.x);
	}
	else
		outText = outText + owner.completeLine("--> [] Posibles edificaciones", size.x);
	isVisibleWorker = true;
}
void CommandMenu::visit(ProducerBuilding& entity) {
	if (!showOptions) {
		visit((Entity&)entity);
		outText = outText + owner.completeLine("[p] Producir", size.x);
	}
	else {
		outText = outText + owner.completeLine("--> [] Posibles productos", size.x);
	}
	isVisibleProducer = true;
}

void CommandMenu::draw() {
	//Dibujo fondo
	SDL_Rect destinoFondoMenu = { (int)offset.x, (int)offset.y, (int)size.x, (int)size.y };
	SDL_SetRenderDrawColor(owner.getRenderer(), 15, 15, 15, 255);
	SDL_RenderFillRect(owner.getRenderer(), &destinoFondoMenu);
	outText = "";
	isVisibleProducer = false;
	isVisibleUnit = false;
	isVisibleWorker = false;
	SDL_Color colorBlanco = { 255, 255, 255 };
	if (owner.font) {
		if ((owner.sController->getSelection().size() == 1) && (owner.player.name == owner.sController->getSelection().at(0)->owner.name)){
			if (currentSelection != owner.sController->getSelection().at(0))
				showOptions = false;
			owner.sController->getSelection().at(0)->visit(*this);
			currentSelection = owner.sController->getSelection().at(0);
		}
		else if (owner.sController->getSelection().size() > 1) {
			outText = outText + owner.completeLine("[] Ir", size.x);
			outText = outText + owner.completeLine("[] Atacar", size.x);
			outText = outText + owner.completeLine("[] Seguir", size.x);
			outText = outText + owner.completeLine("[] Parar", size.x);
			currentSelection = nullptr;
			isVisibleUnit = true;
		}
		else {
			currentSelection = nullptr;
		}
		int access1, w1, h1;
		Uint32 format1;
		SDL_Surface * c1 = TTF_RenderText_Blended_Wrapped(owner.font, outText.c_str(), colorBlanco, (Uint32)(size.x));
		SDL_Texture * textureMenu1 = SDL_CreateTextureFromSurface(owner.getRenderer(), c1);

		SDL_QueryTexture(textureMenu1, &format1, &access1, &w1, &h1);
		SDL_Rect panel1 = { 0, 0, w1 , h1 };
		SDL_Rect text1 = { (int)offset.x, (int)offset.y,
			(int)((w1 > size.x) ? size.x : w1), (int)((h1 > size.y) ? size.y : h1) };
		SDL_RenderCopy(owner.getRenderer(), textureMenu1, &panel1, &text1);

		SDL_FreeSurface(c1);
		SDL_DestroyTexture(textureMenu1);
	}
}<commit_msg>Cambio letras de comandos<commit_after>#include "game_window.h"
#include "command_menu.h"
#include "../parser_yaml/graphics_parser.h"
using namespace std;

CommandMenu::CommandMenu(GameWindow& owner, GraphicsParser& graphicsParser) :
	owner(owner),
	offset(0, owner.alto_pantalla - graphicsParser.getPantalla().hud_alto),
	size((owner.ancho_pantalla-graphicsParser.getPantalla().minimapa_ancho)/2, graphicsParser.getPantalla().hud_alto)
{
	isVisibleProducer = false;
	isVisibleWorker = false;
	isVisibleUnit = false;
	showOptions = false;
	currentSelection = nullptr;
}

CommandMenu::~CommandMenu() {
}

void CommandMenu::visit(Entity& entity) {
}
void CommandMenu::visit(Unit& entity) {
	visit((Entity&)entity);
	outText = outText + owner.completeLine("[] Ir", size.x);
	outText = outText + owner.completeLine("[a] Atacar", size.x);
	outText = outText + owner.completeLine("[f] Seguir", size.x);
	outText = outText + owner.completeLine("[s] Parar", size.x);
	isVisibleUnit = true;
}
void CommandMenu::visit(Worker& entity) {
	if (!showOptions) {
		visit((Unit&)entity);
		outText = outText + owner.completeLine("[r] Reparar", size.x);
		outText = outText + owner.completeLine("[g] Recolectar", size.x);
		outText = outText + owner.completeLine("[c] Construir", size.x);
	}
	else
		outText = outText + owner.completeLine("--> [] Posibles edificaciones", size.x);
	isVisibleWorker = true;
}
void CommandMenu::visit(ProducerBuilding& entity) {
	if (!showOptions) {
		visit((Entity&)entity);
		outText = outText + owner.completeLine("[p] Producir", size.x);
	}
	else {
		outText = outText + owner.completeLine("--> [] Posibles productos", size.x);
	}
	isVisibleProducer = true;
}

void CommandMenu::draw() {
	//Dibujo fondo
	SDL_Rect destinoFondoMenu = { (int)offset.x, (int)offset.y, (int)size.x, (int)size.y };
	SDL_SetRenderDrawColor(owner.getRenderer(), 15, 15, 15, 255);
	SDL_RenderFillRect(owner.getRenderer(), &destinoFondoMenu);
	outText = "";
	isVisibleProducer = false;
	isVisibleUnit = false;
	isVisibleWorker = false;
	SDL_Color colorBlanco = { 255, 255, 255 };
	if (owner.font) {
		if ((owner.sController->getSelection().size() == 1) && (owner.player.name == owner.sController->getSelection().at(0)->owner.name)){
			if (currentSelection != owner.sController->getSelection().at(0))
				showOptions = false;
			owner.sController->getSelection().at(0)->visit(*this);
			currentSelection = owner.sController->getSelection().at(0);
		}
		else if (owner.sController->getSelection().size() > 1) {
			outText = outText + owner.completeLine("[] Ir", size.x);
			outText = outText + owner.completeLine("[a] Atacar", size.x);
			outText = outText + owner.completeLine("[f] Seguir", size.x);
			outText = outText + owner.completeLine("[s] Parar", size.x);
			currentSelection = nullptr;
			isVisibleUnit = true;
		}
		else {
			currentSelection = nullptr;
		}
		int access1, w1, h1;
		Uint32 format1;
		SDL_Surface * c1 = TTF_RenderText_Blended_Wrapped(owner.font, outText.c_str(), colorBlanco, (Uint32)(size.x));
		SDL_Texture * textureMenu1 = SDL_CreateTextureFromSurface(owner.getRenderer(), c1);

		SDL_QueryTexture(textureMenu1, &format1, &access1, &w1, &h1);
		SDL_Rect panel1 = { 0, 0, w1 , h1 };
		SDL_Rect text1 = { (int)offset.x, (int)offset.y,
			(int)((w1 > size.x) ? size.x : w1), (int)((h1 > size.y) ? size.y : h1) };
		SDL_RenderCopy(owner.getRenderer(), textureMenu1, &panel1, &text1);

		SDL_FreeSurface(c1);
		SDL_DestroyTexture(textureMenu1);
	}
}<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: _serviceregistration_charttypes.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: vg $ $Date: 2007-05-22 18:30:44 $
 *
 *  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 CHART2__SERVICEREGISTRATION_CHARTTYPES_HXX
#define CHART2__SERVICEREGISTRATION_CHARTTYPES_HXX

#ifndef _CPPUHELPER_IMPLEMENATIONENTRY_HXX_
#include <cppuhelper/implementationentry.hxx>
#endif

class ChartTypeEntriesForServiceRegistration
{
public:
    static struct ::cppu::ImplementationEntry*
        getImplementationEntries();
};

// CHART2__SERVICEREGISTRATION_CHARTTYPES_HXX
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.2.126); FILE MERGED 2008/04/01 15:04:16 thb 1.2.126.2: #i85898# Stripping all external header guards 2008/03/28 16:44:03 rt 1.2.126.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: _serviceregistration_charttypes.hxx,v $
 * $Revision: 1.3 $
 *
 * 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 CHART2__SERVICEREGISTRATION_CHARTTYPES_HXX
#define CHART2__SERVICEREGISTRATION_CHARTTYPES_HXX

#include <cppuhelper/implementationentry.hxx>

class ChartTypeEntriesForServiceRegistration
{
public:
    static struct ::cppu::ImplementationEntry*
        getImplementationEntries();
};

// CHART2__SERVICEREGISTRATION_CHARTTYPES_HXX
#endif
<|endoftext|>


<commit_before>/*****************************************************************************************
 *                                                                                *
 * OpenSpace                                                                             *
 *                                                                                *
 * Copyright (c) 2014-2021                                                               *
 *                                                                                *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this  *
 * software and associated documentation files (the "Software"), to deal in the Software *
 * without restriction, including without limitation the rights to use, copy, modify,    *
 * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to    *
 * permit persons to whom the Software is furnished to do so, subject to the following   *
 * conditions:                                                                           *
 *                                                                                *
 * The above copyright notice and this permission notice shall be included in all copies *
 * or substantial portions of the Software.                                              *
 *                                                                                *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,   *
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A         *
 * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT    *
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  *
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE  *
 * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                                         *
 ****************************************************************************************/

#include <modules/autonavigation/curves/zoomoutoverviewcurve.h>

#include <modules/autonavigation/autonavigationmodule.h>
#include <modules/autonavigation/helperfunctions.h>
#include <modules/autonavigation/waypoint.h>
#include <openspace/engine/globals.h>
#include <openspace/engine/moduleengine.h>
#include <openspace/query/query.h>
#include <openspace/scene/scenegraphnode.h>
#include <ghoul/logging/logmanager.h>
#include <glm/gtx/projection.hpp>
#include <algorithm>
#include <vector>

namespace {
    constexpr const char* _loggerCat = "ZoomOutOverviewCurve";
} // namespace

namespace openspace::autonavigation {

// Go far out to get a view of both tagets, aimed to match lookAt orientation
ZoomOutOverviewCurve::ZoomOutOverviewCurve(const Waypoint& start, const Waypoint& end) {
    const double startNodeRadius = start.validBoundingSphere;
    const double endNodeRadius = end.validBoundingSphere;

    const double endTangentsLengthFactor = 2.0;
    const double startTangentLength = endTangentsLengthFactor * startNodeRadius;
    const double endTangentLength = endTangentsLengthFactor * endNodeRadius;

    const glm::dvec3 startNodePos = start.node()->worldPosition();
    const glm::dvec3 endNodePos = end.node()->worldPosition();
    const glm::dvec3 startNodeToStartPos = start.position() - startNodePos;
    const glm::dvec3 startTangentDir = normalize(startNodeToStartPos);

    // Start by going outwards
    _points.push_back(start.position());
    _points.push_back(start.position() + startTangentLength * startTangentDir);

    const std::string& startNode = start.nodeIdentifier;
    const std::string& endNode = end.nodeIdentifier;

    // Zoom out
    if (startNode != endNode) {
        // TODO: set a smarter orthogonal direction
        glm::dvec3 startNodeToEndNode = endNodePos - startNodePos;
        glm::dvec3 parallell = glm::proj(startNodeToStartPos, startNodeToEndNode);
        glm::dvec3 orthogonal = normalize(startNodeToStartPos - parallell);

        glm::dvec3 extraKnot = startNodePos + 0.5 * startNodeToEndNode
            + 1.5 * glm::length(startNodeToEndNode) * orthogonal;

        const double midTangentLengthFactor = 0.3;
        _points.push_back(extraKnot - midTangentLengthFactor * startNodeToEndNode);
        _points.push_back(extraKnot);
        _points.push_back(extraKnot + midTangentLengthFactor * startNodeToEndNode);
    }

    // Closing in on end node
    const glm::dvec3 endNodeToEndPos = end.position() - endNodePos;
    const glm::dvec3 endTangentDir = normalize(endNodeToEndPos);

    _points.push_back(end.position() + endTangentLength * endTangentDir);
    _points.push_back(end.position());

    _nSegments = (unsigned int)std::floor((_points.size() - 1) / 3.0);

    initializeParameterData();
}

glm::dvec3 ZoomOutOverviewCurve::interpolate(double u) {
    if (u <= 0.0) {
        return _points[0];
    }
    if (u > 1.0) {
        return _points.back();
    }

    return interpolation::piecewiseCubicBezier(u, _points, _curveParameterSteps);
}

} // namespace openspace::autonavigation
<commit_msg>Convert the ZoomOutOverviewCurve to a CatmullRom spline<commit_after>/*****************************************************************************************
 *                                                                                *
 * OpenSpace                                                                             *
 *                                                                                *
 * Copyright (c) 2014-2021                                                               *
 *                                                                                *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this  *
 * software and associated documentation files (the "Software"), to deal in the Software *
 * without restriction, including without limitation the rights to use, copy, modify,    *
 * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to    *
 * permit persons to whom the Software is furnished to do so, subject to the following   *
 * conditions:                                                                           *
 *                                                                                *
 * The above copyright notice and this permission notice shall be included in all copies *
 * or substantial portions of the Software.                                              *
 *                                                                                *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,   *
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A         *
 * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT    *
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  *
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE  *
 * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                                         *
 ****************************************************************************************/

#include <modules/autonavigation/curves/zoomoutoverviewcurve.h>

#include <modules/autonavigation/autonavigationmodule.h>
#include <modules/autonavigation/helperfunctions.h>
#include <modules/autonavigation/waypoint.h>
#include <openspace/engine/globals.h>
#include <openspace/engine/moduleengine.h>
#include <openspace/query/query.h>
#include <openspace/scene/scenegraphnode.h>
#include <ghoul/logging/logmanager.h>
#include <glm/gtx/projection.hpp>
#include <algorithm>
#include <vector>

namespace {
    constexpr const char* _loggerCat = "ZoomOutOverviewCurve";
} // namespace

namespace openspace::autonavigation {

// Go far out to get a view of both tagets, aimed to match lookAt orientation
ZoomOutOverviewCurve::ZoomOutOverviewCurve(const Waypoint& start, const Waypoint& end) {
    const double startNodeRadius = start.validBoundingSphere;
    const double endNodeRadius = end.validBoundingSphere;

    const double endTangentsLengthFactor = 2.0;
    const double startTangentLength = endTangentsLengthFactor * startNodeRadius;
    const double endTangentLength = endTangentsLengthFactor * endNodeRadius;

    const glm::dvec3 startNodePos = start.node()->worldPosition();
    const glm::dvec3 endNodePos = end.node()->worldPosition();
    const glm::dvec3 startNodeToStartPos = start.position() - startNodePos;
    const glm::dvec3 startTangentDir = normalize(startNodeToStartPos);

    // Start by going outwards
    _points.push_back(start.position());
    _points.push_back(start.position());
    _points.push_back(start.position() + startTangentLength * startTangentDir);

    const std::string& startNode = start.nodeIdentifier;
    const std::string& endNode = end.nodeIdentifier;

    // Zoom out
    if (startNode != endNode) {
        // TODO: set a smarter orthogonal direction
        glm::dvec3 startNodeToEndNode = endNodePos - startNodePos;
        glm::dvec3 parallell = glm::proj(startNodeToStartPos, startNodeToEndNode);
        glm::dvec3 orthogonal = normalize(startNodeToStartPos - parallell);

        glm::dvec3 extraKnot = startNodePos + 0.5 * startNodeToEndNode
            + 1.5 * glm::length(startNodeToEndNode) * orthogonal;

        const double midTangentLengthFactor = 0.3;
        _points.push_back(extraKnot - midTangentLengthFactor * startNodeToEndNode);
        _points.push_back(extraKnot);
        _points.push_back(extraKnot + midTangentLengthFactor * startNodeToEndNode);
    }

    // Closing in on end node
    const glm::dvec3 endNodeToEndPos = end.position() - endNodePos;
    const glm::dvec3 endTangentDir = normalize(endNodeToEndPos);

    _points.push_back(end.position() + endTangentLength * endTangentDir);
    _points.push_back(end.position());
    _points.push_back(end.position());

    _nSegments = static_cast<int>(_points.size() - 3);

    initializeParameterData();
}

glm::dvec3 ZoomOutOverviewCurve::interpolate(double u) {
    if (u <= 0.0) {
        return _points[1];
    }
    if (u > 1.0) {
        return *(_points.end() - 2);
    }

    std::vector<double>::iterator segmentEndIt =
        std::lower_bound(_curveParameterSteps.begin(), _curveParameterSteps.end(), u);
    unsigned int index = static_cast<int>((segmentEndIt - 1) - _curveParameterSteps.begin());

    double segmentStart = _curveParameterSteps[index];
    double segmentDuration = (_curveParameterSteps[index + 1] - _curveParameterSteps[index]);
    double uSegment = (u - segmentStart) / segmentDuration;

    return interpolation::catmullRom(
        uSegment,
        _points[index],
        _points[index + 1],
        _points[index + 2],
        _points[index + 3],
        1.0
    );
}

} // namespace openspace::autonavigation
<|endoftext|>


<commit_before>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2011 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  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
//
//  Current versions can be found at www.libavg.de
//

#include "OGLShader.h"
#include "ShaderRegistry.h"

#include "../base/Logger.h"
#include "../base/Exception.h"

#include <iostream>

using namespace std;

namespace avg {

OGLShader::OGLShader(const string& sName, const string& sVertProgram,
        const string& sFragProgram, const string& sDefines)
    : m_sName(sName),
      m_sVertProgram(sVertProgram),
      m_sFragProgram(sFragProgram)
{
    m_hProgram = glproc::CreateProgramObject();
    if (sVertProgram == "") {
        m_hVertexShader = 0;
    } else {
        m_hVertexShader = compileShader(GL_VERTEX_SHADER, sVertProgram, sDefines);
        glproc::AttachObject(m_hProgram, m_hVertexShader);
    }
    m_hFragmentShader = compileShader(GL_FRAGMENT_SHADER, sFragProgram, sDefines);

    glproc::AttachObject(m_hProgram, m_hFragmentShader);
    glproc::LinkProgram(m_hProgram);
    GLContext::checkError("OGLShader::OGLShader: glLinkProgram()");

    GLint bLinked;
    glproc::GetObjectParameteriv(m_hProgram, GL_OBJECT_LINK_STATUS_ARB, &bLinked);
    dumpInfoLog(m_hProgram);
    if (!bLinked) {
        AVG_TRACE(Logger::ERROR, "Linking shader program '"+sName+"' failed. Aborting.");
        exit(-1);
    }
    m_pShaderRegistry = ShaderRegistry::get();
    if (m_hVertexShader) {
        m_pTransformParam = getParam<glm::mat4>("transform");
    }
}

OGLShader::~OGLShader()
{
}

void OGLShader::activate()
{
    OGLShaderPtr pCurShader = m_pShaderRegistry->getCurShader();
    if (!pCurShader || &*pCurShader != this) {
        glproc::UseProgramObject(m_hProgram);
        m_pShaderRegistry->setCurShader(m_sName);
        GLContext::checkError("OGLShader::activate: glUseProgramObject()");
    }
}

GLhandleARB OGLShader::getProgram()
{
    return m_hProgram;
}

const std::string OGLShader::getName() const
{
    return m_sName;
}

void OGLShader::setTransform(const glm::mat4& transform)
{
    if (m_hVertexShader) {
        m_pTransformParam->set(transform);
    } else {
        glLoadMatrixf(glm::value_ptr(transform));
    }
}

GLhandleARB OGLShader::compileShader(GLenum shaderType, const std::string& sProgram,
        const std::string& sDefines)
{
    const char * pProgramStrs[2];
    pProgramStrs[0] = sDefines.c_str();
    pProgramStrs[1] = sProgram.c_str();
    GLhandleARB hShader = glproc::CreateShaderObject(shaderType);
    glproc::ShaderSource(hShader, 2, pProgramStrs, 0);
    glproc::CompileShader(hShader);
    GLContext::checkError("OGLShader::compileShader()");
    dumpInfoLog(hShader);
    return hShader;
}

bool OGLShader::findParam(const std::string& sName, unsigned& pos)
{
    GLShaderParamPtr pParam;
    bool bFound = false;
    pos = 0;
    while (!bFound && pos<m_pParams.size() && m_pParams[pos]->getName() <= sName) {
        if (m_pParams[pos]->getName() == sName) {
            bFound = true;
        } else {
            ++pos;
        }
    }
    return bFound;
}

void OGLShader::dumpInfoLog(GLhandleARB hObj)
{
    int InfoLogLength;
    GLcharARB * pInfoLog;

    glproc::GetObjectParameteriv(hObj, GL_OBJECT_INFO_LOG_LENGTH_ARB, &InfoLogLength);
    GLContext::checkError("OGLShader::dumpInfoLog: glGetObjectParameteriv()");
    if (InfoLogLength > 1) {
        pInfoLog = (GLcharARB*)malloc(InfoLogLength);
        int CharsWritten;
        glproc::GetInfoLog(hObj, InfoLogLength, &CharsWritten, pInfoLog);
        string sLog = removeATIInfoLogSpam(pInfoLog);
        GLContext::checkError("OGLShader::dumpInfoLog: glGetInfoLog()");
        AVG_TRACE(Logger::WARNING, sLog);
        free(pInfoLog);
    }
}

string OGLShader::removeATIInfoLogSpam(const string& sOrigLog)
{
    istringstream stream(sOrigLog);
    string sLog;
    string sCurLine;
    while(getline(stream, sCurLine)) {
        if ((sCurLine.find(
                "Fragment shader was successfully compiled to run on hardware.")
                == string::npos) &&
                (sCurLine.find("Fragment shader(s) linked.") == string::npos))
        {
            sLog.append(sCurLine+"\n");
        }
    }
    return sLog;
}

}
<commit_msg>Removed AMD shader info spam.<commit_after>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2011 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  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
//
//  Current versions can be found at www.libavg.de
//

#include "OGLShader.h"
#include "ShaderRegistry.h"

#include "../base/Logger.h"
#include "../base/Exception.h"

#include <iostream>

using namespace std;

namespace avg {

OGLShader::OGLShader(const string& sName, const string& sVertProgram,
        const string& sFragProgram, const string& sDefines)
    : m_sName(sName),
      m_sVertProgram(sVertProgram),
      m_sFragProgram(sFragProgram)
{
    m_hProgram = glproc::CreateProgramObject();
    if (sVertProgram == "") {
        m_hVertexShader = 0;
    } else {
        m_hVertexShader = compileShader(GL_VERTEX_SHADER, sVertProgram, sDefines);
        glproc::AttachObject(m_hProgram, m_hVertexShader);
    }
    m_hFragmentShader = compileShader(GL_FRAGMENT_SHADER, sFragProgram, sDefines);

    glproc::AttachObject(m_hProgram, m_hFragmentShader);
    glproc::LinkProgram(m_hProgram);
    GLContext::checkError("OGLShader::OGLShader: glLinkProgram()");

    GLint bLinked;
    glproc::GetObjectParameteriv(m_hProgram, GL_OBJECT_LINK_STATUS_ARB, &bLinked);
    dumpInfoLog(m_hProgram);
    if (!bLinked) {
        AVG_TRACE(Logger::ERROR, "Linking shader program '"+sName+"' failed. Aborting.");
        exit(-1);
    }
    m_pShaderRegistry = ShaderRegistry::get();
    if (m_hVertexShader) {
        m_pTransformParam = getParam<glm::mat4>("transform");
    }
}

OGLShader::~OGLShader()
{
}

void OGLShader::activate()
{
    OGLShaderPtr pCurShader = m_pShaderRegistry->getCurShader();
    if (!pCurShader || &*pCurShader != this) {
        glproc::UseProgramObject(m_hProgram);
        m_pShaderRegistry->setCurShader(m_sName);
        GLContext::checkError("OGLShader::activate: glUseProgramObject()");
    }
}

GLhandleARB OGLShader::getProgram()
{
    return m_hProgram;
}

const std::string OGLShader::getName() const
{
    return m_sName;
}

void OGLShader::setTransform(const glm::mat4& transform)
{
    if (m_hVertexShader) {
        m_pTransformParam->set(transform);
    } else {
        glLoadMatrixf(glm::value_ptr(transform));
    }
}

GLhandleARB OGLShader::compileShader(GLenum shaderType, const std::string& sProgram,
        const std::string& sDefines)
{
    const char * pProgramStrs[2];
    pProgramStrs[0] = sDefines.c_str();
    pProgramStrs[1] = sProgram.c_str();
    GLhandleARB hShader = glproc::CreateShaderObject(shaderType);
    glproc::ShaderSource(hShader, 2, pProgramStrs, 0);
    glproc::CompileShader(hShader);
    GLContext::checkError("OGLShader::compileShader()");
    dumpInfoLog(hShader);
    return hShader;
}

bool OGLShader::findParam(const std::string& sName, unsigned& pos)
{
    GLShaderParamPtr pParam;
    bool bFound = false;
    pos = 0;
    while (!bFound && pos<m_pParams.size() && m_pParams[pos]->getName() <= sName) {
        if (m_pParams[pos]->getName() == sName) {
            bFound = true;
        } else {
            ++pos;
        }
    }
    return bFound;
}

void OGLShader::dumpInfoLog(GLhandleARB hObj)
{
    int InfoLogLength;
    GLcharARB * pInfoLog;

    glproc::GetObjectParameteriv(hObj, GL_OBJECT_INFO_LOG_LENGTH_ARB, &InfoLogLength);
    GLContext::checkError("OGLShader::dumpInfoLog: glGetObjectParameteriv()");
    if (InfoLogLength > 1) {
        pInfoLog = (GLcharARB*)malloc(InfoLogLength);
        int CharsWritten;
        glproc::GetInfoLog(hObj, InfoLogLength, &CharsWritten, pInfoLog);
        string sLog = removeATIInfoLogSpam(pInfoLog);
        GLContext::checkError("OGLShader::dumpInfoLog: glGetInfoLog()");
        AVG_TRACE(Logger::WARNING, sLog);
        free(pInfoLog);
    }
}

string OGLShader::removeATIInfoLogSpam(const string& sOrigLog)
{
    istringstream stream(sOrigLog);
    string sLog;
    string sCurLine;
    while(getline(stream, sCurLine)) {
        if ((sCurLine.find(
                "shader was successfully compiled to run on hardware.") == string::npos)
                && (sCurLine.find("shader(s) linked.") == string::npos))
        {
            sLog.append(sCurLine+"\n");
        }
    }
    return sLog;
}

}
<|endoftext|>


<commit_before>/*------------------------------------------------------------------------
 *  Vulkan Conformance Tests
 * ------------------------
 *
 * Copyright (c) 2015 The Khronos Group Inc.
 * Copyright (c) 2015 Samsung Electronics Co., Ltd.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and/or associated documentation files (the
 * "Materials"), to deal in the Materials without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Materials, and to
 * permit persons to whom the Materials are furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice(s) and this permission notice shall be included
 * in all copies or substantial portions of the Materials.
 *
 * The Materials are Confidential Information as defined by the
 * Khronos Membership Agreement until designated non-confidential by Khronos,
 * at which point this condition clause shall be removed.
 *
 * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
 *
 *//*!
 * \file
 * \brief Vulkan Buffers Tests
 *//*--------------------------------------------------------------------*/

#include "vktApiBufferTests.hpp"

#include "deStringUtil.hpp"
#include "gluVarType.hpp"
#include "tcuTestLog.hpp"
#include "vkPrograms.hpp"
#include "vktTestCase.hpp"

namespace vkt
{

using namespace vk;

namespace api
{

namespace
{

struct BufferCaseParameters
{
	VkBufferUsageFlags	usage;
	VkBufferCreateFlags	flags;
	VkSharingMode		sharingMode;
};

class BufferTestInstance : public TestInstance
{
public:
								BufferTestInstance			(Context&				ctx,
															 BufferCaseParameters	testCase)
									: TestInstance	(ctx)
									, m_testCase	(testCase)
								{}
	virtual tcu::TestStatus		iterate						(void);
	tcu::TestStatus				bufferCreateAndAllocTest	(VkDeviceSize		size);

private:
	BufferCaseParameters		m_testCase;
};

class BuffersTestCase : public TestCase
{
public:
							BuffersTestCase		(tcu::TestContext&		testCtx,
												 const std::string&		name,
												 const std::string&		description,
												 BufferCaseParameters	testCase)
								: TestCase(testCtx, name, description)
								, m_testCase(testCase)
							{}

	virtual					~BuffersTestCase	(void) {}
	virtual TestInstance*	createInstance		(Context&				ctx) const
							{
								tcu::TestLog& log	= m_testCtx.getLog();
								log << tcu::TestLog::Message << getBufferUsageFlagsStr(m_testCase.usage) << tcu::TestLog::EndMessage;
								return new BufferTestInstance(ctx, m_testCase);
							}

private:
	BufferCaseParameters		m_testCase;
};

 tcu::TestStatus BufferTestInstance::bufferCreateAndAllocTest (VkDeviceSize size)
{
	const VkDevice			vkDevice	= m_context.getDevice();
	const DeviceInterface&	vk			= m_context.getDeviceInterface();
	VkBuffer				testBuffer;
	VkMemoryRequirements	memReqs;
	VkDeviceMemory			memory;

	// Create buffer
	{
		const deUint32					queueFamilyIndex	= m_context.getUniversalQueueFamilyIndex();
		const VkBufferCreateInfo		bufferParams		=
		{
			VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
			DE_NULL,
			m_testCase.flags,
			size,
			m_testCase.usage,
			m_testCase.sharingMode,
			1u,										//	deUint32			queueFamilyCount;
			&queueFamilyIndex,
		};

		if (vk.createBuffer(vkDevice, &bufferParams, (const VkAllocationCallbacks*)DE_NULL, &testBuffer) != VK_SUCCESS)
			return tcu::TestStatus::fail("Buffer creation failed! (requested memory size: " + de::toString(size) + ")");

		vk.getBufferMemoryRequirements(vkDevice, testBuffer, &memReqs);

		if (size > memReqs.size)
		{
			std::ostringstream errorMsg;
			errorMsg << "Requied memory size (" << memReqs.size << " bytes) smaller than the buffer's size (" << size << " bytes)!";
			return tcu::TestStatus::fail(errorMsg.str());
		}
	}

	// Allocate and bind memory
	{
		const VkMemoryAllocateInfo memAlloc =
		{
			VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
			NULL,
			memReqs.size,
			0										//	deUint32		memoryTypeIndex
		};

		if (vk.allocateMemory(vkDevice, &memAlloc, (const VkAllocationCallbacks*)DE_NULL, &memory) != VK_SUCCESS)
			return tcu::TestStatus::fail("Alloc memory failed! (requested memory size: " + de::toString(size) + ")");

		if (vk.bindBufferMemory(vkDevice, testBuffer, memory, 0) != VK_SUCCESS)
			return tcu::TestStatus::fail("Bind buffer memory failed! (requested memory size: " + de::toString(size) + ")");
	}

	vk.freeMemory(vkDevice, memory, (const VkAllocationCallbacks*)DE_NULL);
	vk.destroyBuffer(vkDevice, testBuffer, (const VkAllocationCallbacks*)DE_NULL);

	return tcu::TestStatus::pass("Buffer test");
}

tcu::TestStatus BufferTestInstance::iterate (void)
{
	const VkDeviceSize testSizes[] =
	{
		0,
		1181,
		15991,
		16384
	};
	tcu::TestStatus	testStatus					= tcu::TestStatus::pass("Buffer test");

	for (int i = 0; i < DE_LENGTH_OF_ARRAY(testSizes); i++)
	{
		if ((testStatus = bufferCreateAndAllocTest(testSizes[i])).getCode() != QP_TEST_RESULT_PASS)
			return testStatus;
	}

	if (m_testCase.usage & (VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT))
	{
		const VkPhysicalDevice		vkPhysicalDevice	= m_context.getPhysicalDevice();
		const InstanceInterface&	vkInstance			= m_context.getInstanceInterface();
		VkPhysicalDeviceProperties	props;

		vkInstance.getPhysicalDeviceProperties(vkPhysicalDevice, &props);

		testStatus = bufferCreateAndAllocTest(props.limits.maxTexelBufferElements);
	}

	return testStatus;
}

} // anonymous

 tcu::TestCaseGroup* createBufferTests (tcu::TestContext& testCtx)
{
	const VkBufferUsageFlags bufferUsageModes[] =
	{
		VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
		VK_BUFFER_USAGE_TRANSFER_DST_BIT,
		VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT,
		VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT,
		VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
		VK_BUFFER_USAGE_STORAGE_BUFFER_BIT,
		VK_BUFFER_USAGE_INDEX_BUFFER_BIT,
		VK_BUFFER_USAGE_VERTEX_BUFFER_BIT,
		VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT
	};

	const VkBufferCreateFlags bufferCreateFlags[] =
	{
		VK_BUFFER_CREATE_SPARSE_BINDING_BIT,
		VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT,
		VK_BUFFER_CREATE_SPARSE_ALIASED_BIT
	};

	de::MovePtr<tcu::TestCaseGroup>	buffersTests	(new tcu::TestCaseGroup(testCtx, "buffer", "Buffer Tests"));

	deUint32	numberOfBufferUsageFlags			= DE_LENGTH_OF_ARRAY(bufferUsageModes);
	deUint32	numberOfBufferCreateFlags			= DE_LENGTH_OF_ARRAY(bufferCreateFlags);
	deUint32	maximumValueOfBufferUsageFlags		= (1 << (numberOfBufferUsageFlags - 1)) - 1;
	deUint32	maximumValueOfBufferCreateFlags		= (1 << (numberOfBufferCreateFlags)) - 1;

	for (deUint32 combinedBufferCreateFlags = 0; combinedBufferCreateFlags < maximumValueOfBufferCreateFlags; combinedBufferCreateFlags++)
	{
		for (deUint32 combinedBufferUsageFlags = 0; combinedBufferUsageFlags < maximumValueOfBufferUsageFlags; combinedBufferUsageFlags++)
		{
			BufferCaseParameters	testParams =
			{
				combinedBufferUsageFlags,
				combinedBufferCreateFlags,
				VK_SHARING_MODE_EXCLUSIVE
			};
			std::ostringstream	testName;
			std::ostringstream	testDescription;
			testName << "createBuffer_" << combinedBufferUsageFlags << "_" << combinedBufferCreateFlags;
			testDescription << "vkCreateBuffer test " << combinedBufferUsageFlags << " " << combinedBufferCreateFlags;
			buffersTests->addChild(new BuffersTestCase(testCtx, testName.str(), testDescription.str(), testParams));
		}
	}

	return buffersTests.release();
}

} // api
} // vk
<commit_msg>Buffer size of zero is not valid - replace test with a size of 1 byte<commit_after>/*------------------------------------------------------------------------
 *  Vulkan Conformance Tests
 * ------------------------
 *
 * Copyright (c) 2015 The Khronos Group Inc.
 * Copyright (c) 2015 Samsung Electronics Co., Ltd.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and/or associated documentation files (the
 * "Materials"), to deal in the Materials without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Materials, and to
 * permit persons to whom the Materials are furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice(s) and this permission notice shall be included
 * in all copies or substantial portions of the Materials.
 *
 * The Materials are Confidential Information as defined by the
 * Khronos Membership Agreement until designated non-confidential by Khronos,
 * at which point this condition clause shall be removed.
 *
 * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
 *
 *//*!
 * \file
 * \brief Vulkan Buffers Tests
 *//*--------------------------------------------------------------------*/

#include "vktApiBufferTests.hpp"

#include "deStringUtil.hpp"
#include "gluVarType.hpp"
#include "tcuTestLog.hpp"
#include "vkPrograms.hpp"
#include "vktTestCase.hpp"

namespace vkt
{

using namespace vk;

namespace api
{

namespace
{

struct BufferCaseParameters
{
	VkBufferUsageFlags	usage;
	VkBufferCreateFlags	flags;
	VkSharingMode		sharingMode;
};

class BufferTestInstance : public TestInstance
{
public:
								BufferTestInstance			(Context&				ctx,
															 BufferCaseParameters	testCase)
									: TestInstance	(ctx)
									, m_testCase	(testCase)
								{}
	virtual tcu::TestStatus		iterate						(void);
	tcu::TestStatus				bufferCreateAndAllocTest	(VkDeviceSize		size);

private:
	BufferCaseParameters		m_testCase;
};

class BuffersTestCase : public TestCase
{
public:
							BuffersTestCase		(tcu::TestContext&		testCtx,
												 const std::string&		name,
												 const std::string&		description,
												 BufferCaseParameters	testCase)
								: TestCase(testCtx, name, description)
								, m_testCase(testCase)
							{}

	virtual					~BuffersTestCase	(void) {}
	virtual TestInstance*	createInstance		(Context&				ctx) const
							{
								tcu::TestLog& log	= m_testCtx.getLog();
								log << tcu::TestLog::Message << getBufferUsageFlagsStr(m_testCase.usage) << tcu::TestLog::EndMessage;
								return new BufferTestInstance(ctx, m_testCase);
							}

private:
	BufferCaseParameters		m_testCase;
};

 tcu::TestStatus BufferTestInstance::bufferCreateAndAllocTest (VkDeviceSize size)
{
	const VkDevice			vkDevice	= m_context.getDevice();
	const DeviceInterface&	vk			= m_context.getDeviceInterface();
	VkBuffer				testBuffer;
	VkMemoryRequirements	memReqs;
	VkDeviceMemory			memory;

	// Create buffer
	{
		const deUint32					queueFamilyIndex	= m_context.getUniversalQueueFamilyIndex();
		const VkBufferCreateInfo		bufferParams		=
		{
			VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
			DE_NULL,
			m_testCase.flags,
			size,
			m_testCase.usage,
			m_testCase.sharingMode,
			1u,										//	deUint32			queueFamilyCount;
			&queueFamilyIndex,
		};

		if (vk.createBuffer(vkDevice, &bufferParams, (const VkAllocationCallbacks*)DE_NULL, &testBuffer) != VK_SUCCESS)
			return tcu::TestStatus::fail("Buffer creation failed! (requested memory size: " + de::toString(size) + ")");

		vk.getBufferMemoryRequirements(vkDevice, testBuffer, &memReqs);

		if (size > memReqs.size)
		{
			std::ostringstream errorMsg;
			errorMsg << "Requied memory size (" << memReqs.size << " bytes) smaller than the buffer's size (" << size << " bytes)!";
			return tcu::TestStatus::fail(errorMsg.str());
		}
	}

	// Allocate and bind memory
	{
		const VkMemoryAllocateInfo memAlloc =
		{
			VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
			NULL,
			memReqs.size,
			0										//	deUint32		memoryTypeIndex
		};

		if (vk.allocateMemory(vkDevice, &memAlloc, (const VkAllocationCallbacks*)DE_NULL, &memory) != VK_SUCCESS)
			return tcu::TestStatus::fail("Alloc memory failed! (requested memory size: " + de::toString(size) + ")");

		if (vk.bindBufferMemory(vkDevice, testBuffer, memory, 0) != VK_SUCCESS)
			return tcu::TestStatus::fail("Bind buffer memory failed! (requested memory size: " + de::toString(size) + ")");
	}

	vk.freeMemory(vkDevice, memory, (const VkAllocationCallbacks*)DE_NULL);
	vk.destroyBuffer(vkDevice, testBuffer, (const VkAllocationCallbacks*)DE_NULL);

	return tcu::TestStatus::pass("Buffer test");
}

tcu::TestStatus BufferTestInstance::iterate (void)
{
	const VkDeviceSize testSizes[] =
	{
		1,
		1181,
		15991,
		16384
	};
	tcu::TestStatus	testStatus					= tcu::TestStatus::pass("Buffer test");

	for (int i = 0; i < DE_LENGTH_OF_ARRAY(testSizes); i++)
	{
		if ((testStatus = bufferCreateAndAllocTest(testSizes[i])).getCode() != QP_TEST_RESULT_PASS)
			return testStatus;
	}

	if (m_testCase.usage & (VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT))
	{
		const VkPhysicalDevice		vkPhysicalDevice	= m_context.getPhysicalDevice();
		const InstanceInterface&	vkInstance			= m_context.getInstanceInterface();
		VkPhysicalDeviceProperties	props;

		vkInstance.getPhysicalDeviceProperties(vkPhysicalDevice, &props);

		testStatus = bufferCreateAndAllocTest(props.limits.maxTexelBufferElements);
	}

	return testStatus;
}

} // anonymous

 tcu::TestCaseGroup* createBufferTests (tcu::TestContext& testCtx)
{
	const VkBufferUsageFlags bufferUsageModes[] =
	{
		VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
		VK_BUFFER_USAGE_TRANSFER_DST_BIT,
		VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT,
		VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT,
		VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
		VK_BUFFER_USAGE_STORAGE_BUFFER_BIT,
		VK_BUFFER_USAGE_INDEX_BUFFER_BIT,
		VK_BUFFER_USAGE_VERTEX_BUFFER_BIT,
		VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT
	};

	const VkBufferCreateFlags bufferCreateFlags[] =
	{
		VK_BUFFER_CREATE_SPARSE_BINDING_BIT,
		VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT,
		VK_BUFFER_CREATE_SPARSE_ALIASED_BIT
	};

	de::MovePtr<tcu::TestCaseGroup>	buffersTests	(new tcu::TestCaseGroup(testCtx, "buffer", "Buffer Tests"));

	deUint32	numberOfBufferUsageFlags			= DE_LENGTH_OF_ARRAY(bufferUsageModes);
	deUint32	numberOfBufferCreateFlags			= DE_LENGTH_OF_ARRAY(bufferCreateFlags);
	deUint32	maximumValueOfBufferUsageFlags		= (1 << (numberOfBufferUsageFlags - 1)) - 1;
	deUint32	maximumValueOfBufferCreateFlags		= (1 << (numberOfBufferCreateFlags)) - 1;

	for (deUint32 combinedBufferCreateFlags = 0; combinedBufferCreateFlags < maximumValueOfBufferCreateFlags; combinedBufferCreateFlags++)
	{
		for (deUint32 combinedBufferUsageFlags = 0; combinedBufferUsageFlags < maximumValueOfBufferUsageFlags; combinedBufferUsageFlags++)
		{
			BufferCaseParameters	testParams =
			{
				combinedBufferUsageFlags,
				combinedBufferCreateFlags,
				VK_SHARING_MODE_EXCLUSIVE
			};
			std::ostringstream	testName;
			std::ostringstream	testDescription;
			testName << "createBuffer_" << combinedBufferUsageFlags << "_" << combinedBufferCreateFlags;
			testDescription << "vkCreateBuffer test " << combinedBufferUsageFlags << " " << combinedBufferCreateFlags;
			buffersTests->addChild(new BuffersTestCase(testCtx, testName.str(), testDescription.str(), testParams));
		}
	}

	return buffersTests.release();
}

} // api
} // vk
<|endoftext|>


<commit_before>#ifndef DUNE_DETAILED_SOLVERS_LINEARELLIPTIC_MODEL_THERMALBLOCK_HH
#define DUNE_DETAILED_SOLVERS_LINEARELLIPTIC_MODEL_THERMALBLOCK_HH

#include <vector>
#include <string>
#include <memory>

#include <dune/stuff/function/checkerboard.hh>
#include <dune/stuff/common/parameter/tree.hh>

#include "default.hh"

namespace Dune {
namespace DetailedSolvers {
namespace LinearElliptic {

template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim >
class ModelThermalblock;

template< class DomainFieldImp, int domainDim, class RangeFieldImp >
class ModelThermalblock< DomainFieldImp, domainDim, RangeFieldImp, 1 >
  : public ModelDefault< DomainFieldImp, domainDim, RangeFieldImp, 1 >
{
public:
  typedef ModelThermalblock< DomainFieldImp, domainDim, RangeFieldImp, 1 > ThisType;
  typedef ModelDefault< DomainFieldImp, domainDim, RangeFieldImp, 1 >      BaseType;

  typedef typename BaseType::DomainFieldType  DomainFieldType;
  static const int                            dimDomain = BaseType::dimDomain;
  typedef typename BaseType::RangeFieldType   RangeFieldType;
  static const int                            dimRange = BaseType::dimRange;

  typedef typename BaseType::FunctionType   FunctionType;
  typedef typename Stuff::FunctionCheckerboard< DomainFieldType, dimDomain, RangeFieldType, dimRange >
                                            CheckerboardFunctionType;
  typedef typename FunctionType::DomainType DomainType;

  static const std::string id()
  {
    return BaseType::BaseType::id() + ".thermalblock";
  }

  ModelThermalblock(const DomainType& _lowerLeft,
                    const DomainType& _upperRight,
                    const std::vector< size_t >& _numElements,
                    const std::vector< RangeFieldType >& _components,
                    const std::shared_ptr< const FunctionType > _force,
                    const std::shared_ptr< const FunctionType > _dirichlet,
                    const std::shared_ptr< const FunctionType > _neumann)
    : BaseType(std::make_shared< CheckerboardFunctionType >(_lowerLeft,
                                                            _upperRight,
                                                            _numElements,
                                                            _components),
               _force,
               _dirichlet,
               _neumann)
  {}

  ModelThermalblock(const std::shared_ptr< const CheckerboardFunctionType > _diffusion,
                    const std::shared_ptr< const FunctionType > _force,
                    const std::shared_ptr< const FunctionType > _dirichlet,
                    const std::shared_ptr< const FunctionType > _neumann)
    : BaseType(_diffusion, _force, _dirichlet, _neumann)
  {}

  ModelThermalblock(const ThisType& _other)
    :BaseType(_other.diffusion(),
              _other.force(),
              _other.dirichlet(),
              _other.neumann())
  {}

  ThisType& operator=(const ThisType& _other)
  {
    if (this != &_other) {
      BaseType::operator=(_other);
    }
    return this;
  } // ThisType& operator=(const ThisType& other)

  static Dune::ParameterTree createSampleDescription(const std::string subName = "")
  {
    Dune::Stuff::Common::ExtendedParameterTree description;
    description.add(Dune::Stuff::Functions< DomainFieldType, dimDomain,
                                            RangeFieldType, dimRange >::createSampleDescription("function.checkerboard"),
                    "diffusion");
    description["diffusion.name"] = "diffusion";
    description.add(Dune::Stuff::Functions< DomainFieldType, dimDomain,
                                            RangeFieldType, dimRange >::createSampleDescription("function.expression"),
                    "force");
    description["force.name"] = "force";
    description["force.expression"] = "1.0";
    description["force.order"] = "0";
    description.add(Dune::Stuff::Functions< DomainFieldType, dimDomain,
                                            RangeFieldType, dimRange >::createSampleDescription("function.expression"),
                    "neumann");
    description["neumann.name"] = "neumann";
    description["neumann.expression"] = "0.1";
    description["neumann.order"] = "0";
    description.add(Dune::Stuff::Functions< DomainFieldType, dimDomain,
                                            RangeFieldType, dimRange >::createSampleDescription("function.expression"),
                    "dirichlet");
    description["dirichlet.name"] = "dirichlet";
    description["dirichlet.expression"] = "0.1*x[0]";
    description["dirichlet.order"] = "1";
    if (subName.empty())
      return description;
    else {
      Dune::Stuff::Common::ExtendedParameterTree extendedDescription;
      extendedDescription.add(description, subName);
      return extendedDescription;
    }
  }

  static ThisType* create(const Dune::ParameterTree& _description, const std::string _subName = id())
  {
    // get correct paramTree
    Dune::Stuff::Common::ExtendedParameterTree description;
    if (_description.hasSub(_subName))
      description = _description.sub(_subName);
    else
      description = _description;
    // create the correct diffusion
    const Dune::Stuff::Common::ExtendedParameterTree& diffusionDescription = description.sub("diffusion");
    const std::shared_ptr< const CheckerboardFunctionType >
        diffusion(CheckerboardFunctionType::create(diffusionDescription));
    return new ThisType(diffusion,
                        createFunction("force", description),
                        createFunction("dirichlet", description),
                        createFunction("neumann", description));
  } // static ThisType createFromParamTree(const Dune::ParameterTree& paramTree, const std::string subName = id())

private:
  static std::shared_ptr< const FunctionType > createFunction(const std::string& _id,
                                                               const Dune::Stuff::Common::ExtendedParameterTree& _description)
  {
    const Dune::Stuff::Common::ExtendedParameterTree functionDescription = _description.sub(_id);
    std::string type;
    // we do this instead of using get() with 'function.expression' as a default in order to prevent get() from
    // throwing a warning
    if (functionDescription.hasKey("type"))
      type = functionDescription.get< std::string >("type");
    else
      type = "function.expression";
    return std::shared_ptr< const FunctionType >(Dune::Stuff::Functions<  DomainFieldType, dimDomain,
                                                                          RangeFieldType, dimRange >::create(type,
                                                                                functionDescription));
  }
}; // class ModelThermalblock

} // namespace LinearElliptic
} // namespace DetailedSolvers
} // namespace Dune

#endif // DUNE_DETAILED_SOLVERS_LINEARELLIPTIC_MODEL_THERMALBLOCK_HH
<commit_msg>[linearelliptic.model.thermalblock] update, works again<commit_after>#ifndef DUNE_DETAILED_SOLVERS_LINEARELLIPTIC_MODEL_THERMALBLOCK_HH
#define DUNE_DETAILED_SOLVERS_LINEARELLIPTIC_MODEL_THERMALBLOCK_HH

#include <vector>
#include <string>
#include <memory>

#include <dune/stuff/function/checkerboard.hh>
#include <dune/stuff/common/parameter/tree.hh>

#include "default.hh"

namespace Dune {
namespace DetailedSolvers {
namespace LinearElliptic {

template< class DomainFieldImp, int domainDim, class RangeFieldImp >
class ModelThermalblock< DomainFieldImp, domainDim, RangeFieldImp, 1, true >
  : public ModelDefault< DomainFieldImp, domainDim, RangeFieldImp, 1, true >
{
  typedef ModelDefault< DomainFieldImp, domainDim, RangeFieldImp, 1, true >      BaseType;
public:
  typedef ModelThermalblock< DomainFieldImp, domainDim, RangeFieldImp, 1, true > ThisType;

  typedef typename BaseType::DomainFieldType  DomainFieldType;
  static const int                            dimDomain = BaseType::dimDomain;
  typedef typename BaseType::RangeFieldType   RangeFieldType;
  static const int                            dimRange = BaseType::dimRange;

  typedef typename BaseType::ForceType      ForceType;
  typedef typename BaseType::DirichletType  DirichletType;
  typedef typename BaseType::NeumannType    NeumannType;
  typedef typename Stuff::FunctionCheckerboard< DomainFieldType, dimDomain, RangeFieldType, dimRange >
                                            CheckerboardFunctionType;

  typedef typename CheckerboardFunctionType::DomainType   DomainType;

  static const std::string id()
  {
    return BaseType::BaseType::id() + ".thermalblock";
  }

  ModelThermalblock(const DomainType& _lowerLeft,
                    const DomainType& _upperRight,
                    const std::vector< size_t >& _numElements,
                    const std::vector< RangeFieldType >& _components,
                    const std::shared_ptr< const ForceType > _force,
                    const std::shared_ptr< const DirichletType > _dirichlet,
                    const std::shared_ptr< const NeumannType > _neumann)
    : BaseType(std::make_shared< CheckerboardFunctionType >(_lowerLeft,
                                                            _upperRight,
                                                            _numElements,
                                                            _components),
               _force,
               _dirichlet,
               _neumann)
  {}

  ModelThermalblock(const std::shared_ptr< const CheckerboardFunctionType > _diffusion,
                    const std::shared_ptr< const ForceType > _force,
                    const std::shared_ptr< const DirichletType > _dirichlet,
                    const std::shared_ptr< const NeumannType > _neumann)
    : BaseType(_diffusion, _force, _dirichlet, _neumann)
  {}

  static Dune::ParameterTree defaultSettings(const std::string subName = "")
  {
    Dune::Stuff::Common::ExtendedParameterTree description;
    description.add(Dune::Stuff::Functions< DomainFieldType, dimDomain,
                                            RangeFieldType, dimRange >::defaultSettings("function.checkerboard"),
                    "diffusion");
    description["diffusion.name"] = "diffusion";
    description.add(Dune::Stuff::Functions< DomainFieldType, dimDomain,
                                            RangeFieldType, dimRange >::defaultSettings("function.expression"),
                    "force");
    description["force.name"] = "force";
    description["force.expression"] = "1.0";
    description["force.order"] = "0";
    description.add(Dune::Stuff::Functions< DomainFieldType, dimDomain,
                                            RangeFieldType, dimRange >::defaultSettings("function.expression"),
                    "neumann");
    description["neumann.name"] = "neumann";
    description["neumann.expression"] = "0.1";
    description["neumann.order"] = "0";
    description.add(Dune::Stuff::Functions< DomainFieldType, dimDomain,
                                            RangeFieldType, dimRange >::defaultSettings("function.expression"),
                    "dirichlet");
    description["dirichlet.name"] = "dirichlet";
    description["dirichlet.expression"] = "0.1*x[0]";
    description["dirichlet.order"] = "1";
    if (subName.empty())
      return description;
    else {
      Dune::Stuff::Common::ExtendedParameterTree extendedDescription;
      extendedDescription.add(description, subName);
      return extendedDescription;
    }
  }

  static ThisType* create(const Dune::ParameterTree& _settings, const std::string _subName = id())
  {
    // get correct paramTree
    Dune::Stuff::Common::ExtendedParameterTree settings;
    if (_settings.hasSub(_subName))
      settings = _settings.sub(_subName);
    else
      settings = _settings;
    // create the correct diffusion
    return new ThisType(std::shared_ptr< CheckerboardFunctionType >(CheckerboardFunctionType::create(settings.sub("diffusion"))),
                        BaseType::template createFunction< ForceType >("force", settings),
                        BaseType::template createFunction< DirichletType >("dirichlet", settings),
                        BaseType::template createFunction< NeumannType >("neumann", settings));
  } // static ThisType createFromParamTree(const Dune::ParameterTree& paramTree, const std::string subName = id())

private:

}; // class ModelThermalblock

} // namespace LinearElliptic
} // namespace DetailedSolvers
} // namespace Dune

#endif // DUNE_DETAILED_SOLVERS_LINEARELLIPTIC_MODEL_THERMALBLOCK_HH
<|endoftext|>


<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.

#include <nix/util/util.hpp>

#include <nix/hdf5/DimensionHDF5.hpp>
#include <nix/hdf5/DataSet.hpp>

using namespace std;

namespace nix {
namespace hdf5 {

DimensionType dimensionTypeFromStr(const string &str) {
    if (str == "set") {
        return DimensionType::Set;
    } else if (str == "range") {
        return DimensionType::Range;
    } else if (str == "sample") {
        return DimensionType::Sample;
    } else {
        throw runtime_error("Not a valid dimension name");
    }
}

std::string dimensionTypeToStr(DimensionType dim) {

    //The way this switch + string.empty() checking is
    // done here might seem a bit convoluted, but the
    // idea behind it is:
    // a) have no default case in the switch to get a
    //    compile warning in case a new element is
    //    added to the enum
    // b) still be safe and throw an exception in case
    //    not all enum cases are handled properly

    std::string dimType;

    switch (dim) {
        case DimensionType::Set:
            dimType = "set";
            break;
        case DimensionType::Range:
            dimType = "range";
            break;
        case DimensionType::Sample:
            dimType = "sample";
            break;
    }

    if (dimType.empty()) {
        throw runtime_error("Not a valid dimension type");
    }

    return dimType;

}

// Implementation of Dimension

DimensionHDF5::DimensionHDF5(Group group, size_t id)
    : group(group), dim_id(id)
{
}

DimensionHDF5::DimensionHDF5(const DimensionHDF5 &other)
    : group(other.group), dim_id(other.dim_id)
{
}

void DimensionHDF5::setType() {
    group.setAttr("dimension_type", dimensionTypeToStr(dimensionType()));
}

void DimensionHDF5::swap(DimensionHDF5 &other) {
    using std::swap;
    swap(group, other.group);
    swap(dim_id, other.dim_id);
}

bool DimensionHDF5::operator==(const DimensionHDF5 &other) const {
    return group == other.group;
}

bool DimensionHDF5::operator!=(const DimensionHDF5 &other) const {
    return !(*this == other);
}

DimensionHDF5::~DimensionHDF5() {}

//--------------------------------------------------------------
// Implementation of SampledDimension
//--------------------------------------------------------------

SampledDimensionHDF5::SampledDimensionHDF5(Group group, size_t id, double _samplingInterval)
    : DimensionHDF5(group, id)
{
    setType();
    samplingInterval(_samplingInterval);
}

SampledDimensionHDF5::SampledDimensionHDF5(const SampledDimensionHDF5 &other)
    : DimensionHDF5(other.group, other.dim_id)
{
    setType();
    samplingInterval(other.samplingInterval());
}

DimensionType SampledDimensionHDF5::dimensionType() const {
    return DimensionType::Sample;
}

boost::optional<std::string> SampledDimensionHDF5::label() const {
    boost::optional<std::string> ret;
    string label;
    bool have_attr = group.getAttr("label", label);
    if (have_attr) {
        ret = label;
    }
    return ret;
}

void SampledDimensionHDF5::label(const string &label) {
    if(label.empty()) {
        throw EmptyString("label");
    }
    else {
        group.setAttr("label", label);
        // NOTE: forceUpdatedAt() not possible since not reachable from here
    }
}

void SampledDimensionHDF5::label(const none_t t) {
    if(group.hasAttr("label")) {
        group.removeAttr("label");
    }
    // NOTE: forceUpdatedAt() not possible since not reachable from here
}

boost::optional<std::string> SampledDimensionHDF5::unit() const {
    boost::optional<std::string> ret;
    string unit;
    group.getAttr("unit", unit);
    ret = unit;
    return ret;
}

void SampledDimensionHDF5::unit(const string &unit) {
    if(unit.empty()) {
        throw EmptyString("unit");
    }
    else {
        group.setAttr("unit", unit);
        // NOTE: forceUpdatedAt() not possible since not reachable from here
    }
}

void SampledDimensionHDF5::unit(const none_t t) {
    if(group.hasAttr("unit")) {
        group.removeAttr("unit");
    }
    // NOTE: forceUpdatedAt() not possible since not reachable from here
}

double SampledDimensionHDF5::samplingInterval() const {
    double sampling_interval;

    if(group.hasAttr("sampling_interval")) {
        group.getAttr("sampling_interval", sampling_interval);
        return sampling_interval;
    } else {
        throw MissingAttr("sampling_interval");
    }
}

void SampledDimensionHDF5::samplingInterval(double sampling_interval) {
    group.setAttr("sampling_interval", sampling_interval);
}

boost::optional<double> SampledDimensionHDF5::offset() const {
    boost::optional<double> ret;
    double offset = 0;
    if(group.getAttr("offset", offset)) {
        ret = offset;
    }
    return ret;
}

void SampledDimensionHDF5::offset(double offset) {
    group.setAttr("offset", offset);
}

void SampledDimensionHDF5::offset(const none_t t) {
    if(group.hasAttr("offset")) {
        group.removeAttr("offset");
    }
}

SampledDimensionHDF5& SampledDimensionHDF5::operator=(const SampledDimensionHDF5 &other) {
    SampledDimensionHDF5 tmp(other);
    swap(tmp);
    return *this;
}

SampledDimensionHDF5::~SampledDimensionHDF5() {}

//--------------------------------------------------------------
// Implementation of SetDimensionHDF5
//--------------------------------------------------------------

SetDimensionHDF5::SetDimensionHDF5(Group group, size_t id)
    : DimensionHDF5(group, id)
{
    setType();
}

SetDimensionHDF5::SetDimensionHDF5(const SetDimensionHDF5 &other)
    : DimensionHDF5(other.group, other.dim_id)
{
    setType();
}

DimensionType SetDimensionHDF5::dimensionType() const {
    return DimensionType::Set;
}

vector<string> SetDimensionHDF5::labels() const {
    vector<string> labels;

    group.getData("labels", labels);
    return labels;
}

void SetDimensionHDF5::labels(const vector<string> &labels) {
   group.setData("labels", labels);
}

void SetDimensionHDF5::labels(const none_t t) {
    if(group.hasAttr("offset")) {
        group.removeAttr("offset");
    }
}

SetDimensionHDF5& SetDimensionHDF5::operator=(const SetDimensionHDF5 &other) {
    SetDimensionHDF5 tmp(other);
    swap(tmp);
    return *this;
}

SetDimensionHDF5::~SetDimensionHDF5() {}

//--------------------------------------------------------------
// Implementation of RangeDimensionHDF5
//--------------------------------------------------------------

RangeDimensionHDF5::RangeDimensionHDF5(Group group, size_t id, vector<double> _ticks)
    : DimensionHDF5(group, id)
{
    setType();
    ticks(_ticks);
}

RangeDimensionHDF5::RangeDimensionHDF5(const RangeDimensionHDF5 &other)
    : DimensionHDF5(other.group, other.dim_id)
{
    setType();
    ticks(other.ticks());
}

DimensionType RangeDimensionHDF5::dimensionType() const {
    return DimensionType::Range;
}

boost::optional<std::string> RangeDimensionHDF5::label() const {
    boost::optional<std::string> ret;
    string label;
    group.getAttr("label", label);
    ret = label;
    return ret;
}

void RangeDimensionHDF5::label(const string &label) {
    if(label.empty()) {
        throw EmptyString("label");
    }
    else {
        group.setAttr("label", label);
        // NOTE: forceUpdatedAt() not possible since not reachable from here
    }
}

void RangeDimensionHDF5::label(const none_t t) {
    if(group.hasAttr("label")) {
        group.removeAttr("label");
    }
    // NOTE: forceUpdatedAt() not possible since not reachable from here
}

boost::optional<std::string> RangeDimensionHDF5::unit() const {
    boost::optional<std::string> ret;
    string unit;
    group.getAttr("unit", unit);
    ret = unit;
    return ret;
}

void RangeDimensionHDF5::unit(const string &unit) {
    if(unit.empty()) {
        throw EmptyString("unit");
    }
    else {
        group.setAttr("unit", unit);
        // NOTE: forceUpdatedAt() not possible since not reachable from here
    }
}

void RangeDimensionHDF5::unit(const none_t t) {
    if(group.hasAttr("unit")) {
        group.removeAttr("unit");
    }
    // NOTE: forceUpdatedAt() not possible since not reachable from here
}

RangeDimensionHDF5& RangeDimensionHDF5::operator=(const RangeDimensionHDF5 &other) {
    RangeDimensionHDF5 tmp(other);
    swap(tmp);
    return *this;
}

vector<double> RangeDimensionHDF5::ticks() const {
    vector<double> ticks;

    if(group.hasData("ticks")) {
        group.getData("ticks", ticks);
        return ticks;
    } else {
        throw MissingAttr("ticks");
    }
}

void RangeDimensionHDF5::ticks(const vector<double> &ticks) {
    group.setData("ticks", ticks);
}

RangeDimensionHDF5::~RangeDimensionHDF5() {}

} // namespace hdf5
} // namespace nix

<commit_msg>DimensionHDF5::unit: correctly return none if attr is not set<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.

#include <nix/util/util.hpp>

#include <nix/hdf5/DimensionHDF5.hpp>
#include <nix/hdf5/DataSet.hpp>

using namespace std;

namespace nix {
namespace hdf5 {

DimensionType dimensionTypeFromStr(const string &str) {
    if (str == "set") {
        return DimensionType::Set;
    } else if (str == "range") {
        return DimensionType::Range;
    } else if (str == "sample") {
        return DimensionType::Sample;
    } else {
        throw runtime_error("Not a valid dimension name");
    }
}

std::string dimensionTypeToStr(DimensionType dim) {

    //The way this switch + string.empty() checking is
    // done here might seem a bit convoluted, but the
    // idea behind it is:
    // a) have no default case in the switch to get a
    //    compile warning in case a new element is
    //    added to the enum
    // b) still be safe and throw an exception in case
    //    not all enum cases are handled properly

    std::string dimType;

    switch (dim) {
        case DimensionType::Set:
            dimType = "set";
            break;
        case DimensionType::Range:
            dimType = "range";
            break;
        case DimensionType::Sample:
            dimType = "sample";
            break;
    }

    if (dimType.empty()) {
        throw runtime_error("Not a valid dimension type");
    }

    return dimType;

}

// Implementation of Dimension

DimensionHDF5::DimensionHDF5(Group group, size_t id)
    : group(group), dim_id(id)
{
}

DimensionHDF5::DimensionHDF5(const DimensionHDF5 &other)
    : group(other.group), dim_id(other.dim_id)
{
}

void DimensionHDF5::setType() {
    group.setAttr("dimension_type", dimensionTypeToStr(dimensionType()));
}

void DimensionHDF5::swap(DimensionHDF5 &other) {
    using std::swap;
    swap(group, other.group);
    swap(dim_id, other.dim_id);
}

bool DimensionHDF5::operator==(const DimensionHDF5 &other) const {
    return group == other.group;
}

bool DimensionHDF5::operator!=(const DimensionHDF5 &other) const {
    return !(*this == other);
}

DimensionHDF5::~DimensionHDF5() {}

//--------------------------------------------------------------
// Implementation of SampledDimension
//--------------------------------------------------------------

SampledDimensionHDF5::SampledDimensionHDF5(Group group, size_t id, double _samplingInterval)
    : DimensionHDF5(group, id)
{
    setType();
    samplingInterval(_samplingInterval);
}

SampledDimensionHDF5::SampledDimensionHDF5(const SampledDimensionHDF5 &other)
    : DimensionHDF5(other.group, other.dim_id)
{
    setType();
    samplingInterval(other.samplingInterval());
}

DimensionType SampledDimensionHDF5::dimensionType() const {
    return DimensionType::Sample;
}

boost::optional<std::string> SampledDimensionHDF5::label() const {
    boost::optional<std::string> ret;
    string label;
    bool have_attr = group.getAttr("label", label);
    if (have_attr) {
        ret = label;
    }
    return ret;
}

void SampledDimensionHDF5::label(const string &label) {
    if(label.empty()) {
        throw EmptyString("label");
    }
    else {
        group.setAttr("label", label);
        // NOTE: forceUpdatedAt() not possible since not reachable from here
    }
}

void SampledDimensionHDF5::label(const none_t t) {
    if(group.hasAttr("label")) {
        group.removeAttr("label");
    }
    // NOTE: forceUpdatedAt() not possible since not reachable from here
}

boost::optional<std::string> SampledDimensionHDF5::unit() const {
    boost::optional<std::string> ret;
    string unit;
    bool have_attr = group.getAttr("unit", unit);
    if (have_attr) {
        ret = unit;
    }
    return ret;
}

void SampledDimensionHDF5::unit(const string &unit) {
    if(unit.empty()) {
        throw EmptyString("unit");
    }
    else {
        group.setAttr("unit", unit);
        // NOTE: forceUpdatedAt() not possible since not reachable from here
    }
}

void SampledDimensionHDF5::unit(const none_t t) {
    if(group.hasAttr("unit")) {
        group.removeAttr("unit");
    }
    // NOTE: forceUpdatedAt() not possible since not reachable from here
}

double SampledDimensionHDF5::samplingInterval() const {
    double sampling_interval;

    if(group.hasAttr("sampling_interval")) {
        group.getAttr("sampling_interval", sampling_interval);
        return sampling_interval;
    } else {
        throw MissingAttr("sampling_interval");
    }
}

void SampledDimensionHDF5::samplingInterval(double sampling_interval) {
    group.setAttr("sampling_interval", sampling_interval);
}

boost::optional<double> SampledDimensionHDF5::offset() const {
    boost::optional<double> ret;
    double offset = 0;
    if(group.getAttr("offset", offset)) {
        ret = offset;
    }
    return ret;
}

void SampledDimensionHDF5::offset(double offset) {
    group.setAttr("offset", offset);
}

void SampledDimensionHDF5::offset(const none_t t) {
    if(group.hasAttr("offset")) {
        group.removeAttr("offset");
    }
}

SampledDimensionHDF5& SampledDimensionHDF5::operator=(const SampledDimensionHDF5 &other) {
    SampledDimensionHDF5 tmp(other);
    swap(tmp);
    return *this;
}

SampledDimensionHDF5::~SampledDimensionHDF5() {}

//--------------------------------------------------------------
// Implementation of SetDimensionHDF5
//--------------------------------------------------------------

SetDimensionHDF5::SetDimensionHDF5(Group group, size_t id)
    : DimensionHDF5(group, id)
{
    setType();
}

SetDimensionHDF5::SetDimensionHDF5(const SetDimensionHDF5 &other)
    : DimensionHDF5(other.group, other.dim_id)
{
    setType();
}

DimensionType SetDimensionHDF5::dimensionType() const {
    return DimensionType::Set;
}

vector<string> SetDimensionHDF5::labels() const {
    vector<string> labels;

    group.getData("labels", labels);
    return labels;
}

void SetDimensionHDF5::labels(const vector<string> &labels) {
   group.setData("labels", labels);
}

void SetDimensionHDF5::labels(const none_t t) {
    if(group.hasAttr("offset")) {
        group.removeAttr("offset");
    }
}

SetDimensionHDF5& SetDimensionHDF5::operator=(const SetDimensionHDF5 &other) {
    SetDimensionHDF5 tmp(other);
    swap(tmp);
    return *this;
}

SetDimensionHDF5::~SetDimensionHDF5() {}

//--------------------------------------------------------------
// Implementation of RangeDimensionHDF5
//--------------------------------------------------------------

RangeDimensionHDF5::RangeDimensionHDF5(Group group, size_t id, vector<double> _ticks)
    : DimensionHDF5(group, id)
{
    setType();
    ticks(_ticks);
}

RangeDimensionHDF5::RangeDimensionHDF5(const RangeDimensionHDF5 &other)
    : DimensionHDF5(other.group, other.dim_id)
{
    setType();
    ticks(other.ticks());
}

DimensionType RangeDimensionHDF5::dimensionType() const {
    return DimensionType::Range;
}

boost::optional<std::string> RangeDimensionHDF5::label() const {
    boost::optional<std::string> ret;
    string label;
    group.getAttr("label", label);
    ret = label;
    return ret;
}

void RangeDimensionHDF5::label(const string &label) {
    if(label.empty()) {
        throw EmptyString("label");
    }
    else {
        group.setAttr("label", label);
        // NOTE: forceUpdatedAt() not possible since not reachable from here
    }
}

void RangeDimensionHDF5::label(const none_t t) {
    if(group.hasAttr("label")) {
        group.removeAttr("label");
    }
    // NOTE: forceUpdatedAt() not possible since not reachable from here
}

boost::optional<std::string> RangeDimensionHDF5::unit() const {
    boost::optional<std::string> ret;
    string unit;
    group.getAttr("unit", unit);
    ret = unit;
    return ret;
}

void RangeDimensionHDF5::unit(const string &unit) {
    if(unit.empty()) {
        throw EmptyString("unit");
    }
    else {
        group.setAttr("unit", unit);
        // NOTE: forceUpdatedAt() not possible since not reachable from here
    }
}

void RangeDimensionHDF5::unit(const none_t t) {
    if(group.hasAttr("unit")) {
        group.removeAttr("unit");
    }
    // NOTE: forceUpdatedAt() not possible since not reachable from here
}

RangeDimensionHDF5& RangeDimensionHDF5::operator=(const RangeDimensionHDF5 &other) {
    RangeDimensionHDF5 tmp(other);
    swap(tmp);
    return *this;
}

vector<double> RangeDimensionHDF5::ticks() const {
    vector<double> ticks;

    if(group.hasData("ticks")) {
        group.getData("ticks", ticks);
        return ticks;
    } else {
        throw MissingAttr("ticks");
    }
}

void RangeDimensionHDF5::ticks(const vector<double> &ticks) {
    group.setData("ticks", ticks);
}

RangeDimensionHDF5::~RangeDimensionHDF5() {}

} // namespace hdf5
} // namespace nix

<|endoftext|>