<commit_before>#include "StdAfx.h"
#include "Progress.h"

CDuiProgress::CDuiProgress(HWND hWnd, CDuiObject* pDuiObject)
	: CControlBaseFont(hWnd, pDuiObject)
{
	m_bRunTime = false;
	m_nMaxProgress = 100;
	m_nCount = 0;
	m_nTimerCount = 3;

	SetBitmapCount(2);

	m_pImageBackGround = NULL;
	m_sizeBackGround = CSize(0, 0);
	m_pImageForeGround = NULL;
	m_sizeForeGround = CSize(0, 0);
	m_nHeadLength = 0;

	m_clrText = Color(254, 128, 128, 128);
	m_uAlignment = Align_Center;
	m_uVAlignment = VAlign_Middle;
	m_bShowText = FALSE;

	m_nProgress = 0;
	SetProgress(0);
}

CDuiProgress::CDuiProgress(HWND hWnd, CDuiObject* pDuiObject, UINT uControlID, CRect rc, int nProgress/* = 0*/,
					 BOOL bIsVisible/* = TRUE*/, BOOL bIsDisable/* = FALSE*/)
	: CControlBaseFont(hWnd, pDuiObject, uControlID, rc, TEXT(""), bIsVisible, bIsDisable)
{
	m_bRunTime = false;
	m_nMaxProgress = 100;
	m_nCount = 0;
	m_nTimerCount = 3;

	SetBitmapCount(2);

	m_pImageBackGround = NULL;
	m_sizeBackGround = CSize(0, 0);
	m_pImageForeGround = NULL;
	m_sizeForeGround = CSize(0, 0);
	m_nHeadLength = 0;

	m_clrText = Color(254, 128, 128, 128);
	m_uAlignment = Align_Center;
	m_uVAlignment = VAlign_Middle;
	m_bShowText = FALSE;

	m_nProgress = 0;
	SetProgress(nProgress);
}

CDuiProgress::~CDuiProgress(void)
{
	if(m_pImageBackGround != NULL)
	{
		delete m_pImageBackGround;
		m_pImageBackGround = NULL;
	}
	if(m_pImageForeGround != NULL)
	{
		delete m_pImageForeGround;
		m_pImageForeGround = NULL;
	}
}

// ͼƬԵʵ
DUI_IMAGE_ATTRIBUTE_IMPLEMENT(CDuiProgress, BackGround, 1)
DUI_IMAGE_ATTRIBUTE_IMPLEMENT(CDuiProgress, ForeGround, 1)

int CDuiProgress::SetProgress(int nProgress)
{
	if(GetDisable())
	{
		return m_nProgress;
	}

	if(nProgress > m_nMaxProgress)
	{
		// ֵֵ,ԶΪֵ
		nProgress = m_nMaxProgress;
	}

	if(nProgress >= 0 && nProgress <= m_nMaxProgress && m_nProgress != nProgress)
	{
		m_nProgress = nProgress;
		if(GetVisible())
		{
			UpdateControl(true);
		}
	}
	return m_nProgress;
}

// ǷԶ
BOOL CDuiProgress::SetRun(BOOL bRun, int nIndex/* = -1*/)
{
	if(GetDisable())
	{
		return m_bRunTime;
	}

	BOOL bOldRunTime = m_bRunTime;
	int nOldProgress = m_nProgress;
	m_bRunTime = bRun;

	if(nIndex >= 0 && nIndex <= m_nMaxProgress)
	{
		m_nProgress = nIndex;
	}

	if(GetVisible() && ((bOldRunTime != m_bRunTime) || (nOldProgress != m_nProgress)))
	{
		UpdateControl(true);
	}

	return m_bRunTime;
}

// XMLԶ
HRESULT CDuiProgress::OnAttributeRun(const CString& strValue, BOOL bLoading)
{
	if (strValue.IsEmpty()) return E_FAIL;

	BOOL bRun = (strValue == _T("true"));
	SetRun(bRun);

	return bLoading?S_FALSE:S_OK;
}

BOOL CDuiProgress::OnControlTimer()
{
	if(!m_bRunTime || !m_bIsVisible)
	{
		return FALSE;
	}

	if(++m_nCount >= m_nTimerCount)
	{
		m_nCount = 0;
		if(++m_nProgress >= m_nMaxProgress)
		{
			m_nProgress = 0;
		}

		if(GetVisible())
		{
			UpdateControl(true);
		}
		return true;
	}

	return false;
}

void CDuiProgress::DrawControl(CDC &dc, CRect rcUpdate)
{
	int nWidth = m_rc.Width();
	int nHeight = m_rc.Height();

	if(!m_bUpdate)
	{
		UpdateMemDC(dc, nWidth, nHeight);

		m_memDC.BitBlt(0, 0, nWidth, nHeight, &dc, m_rc.left ,m_rc.top, SRCCOPY);

		Graphics graphics(m_memDC);

		if(m_pImageForeGround != NULL)	// ʹñǰͼƬ
		{
			if(m_pImageBackGround != NULL)	//
			{
				DrawImageFrameMID(graphics, m_pImageBackGround, CRect(0, 0, nWidth, nHeight),
					0, 0, m_sizeBackGround.cx, m_sizeBackGround.cy,
					m_nHeadLength, 0, m_nHeadLength, 0);
			}

			if(m_nProgress != 0)	// ǰ
			{
				DrawImageFrameMID(graphics, m_pImageForeGround, CRect(0, 0, nWidth * m_nProgress / 100, nHeight),
					0, 0, m_sizeForeGround.cx, m_sizeForeGround.cy,
					m_nHeadLength, 0, m_nHeadLength, 0);
			}
		}else
		if(m_pImage != NULL)	// ʹõͼƬ
		{
			DrawImageFrame(graphics, m_pImage, CRect(0, 0, nWidth, nHeight),
				0, 0, m_sizeImage.cx, m_sizeImage.cy, 2);

			if(m_nProgress != 0)
			{
				DrawImageFrame(graphics, m_pImage, CRect(0, 0, nWidth * m_nProgress / 100, nHeight),
					m_sizeImage.cx, 0, m_sizeImage.cx, m_sizeImage.cy, 2);
			}
		}

		//
		if(m_bShowText)
		{
			BSTR bsFont = m_strFont.AllocSysString();
			FontFamily fontFamily(bsFont);
			Font font(&fontFamily, (REAL)m_nFontWidth, m_fontStyle, UnitPixel);
			::SysFreeString(bsFont);

			SolidBrush solidBrush(m_clrText);
			graphics.SetTextRenderingHint( TextRenderingHintClearTypeGridFit );
			// ˮƽʹֱ뷽ʽ
			DUI_STRING_ALIGN_DEFINE();
			strFormat.SetFormatFlags( StringFormatFlagsNoClip | StringFormatFlagsMeasureTrailingSpaces);

			CString strText;
			strText.Format(L"%s%d%s", m_strTitle, m_nProgress, (m_nMaxProgress == 100) ? L"%" : L"");
			BSTR bsTitle = strText.AllocSysString();
			RectF rect((Gdiplus::REAL)(0), (Gdiplus::REAL)0, (Gdiplus::REAL)nWidth, (Gdiplus::REAL)nHeight);
			graphics.DrawString(bsTitle, (INT)wcslen(bsTitle), &font, rect, &strFormat, &solidBrush);
			::SysFreeString(bsTitle);
		}
	}

	dc.BitBlt(m_rc.left,m_rc.top, m_rc.Width(), m_rc.Height(), &m_memDC, 0, 0, SRCCOPY);
}<commit_msg>progress控件可以设置进度最大值，不一定是100。<commit_after>#include "StdAfx.h"
#include "Progress.h"

CDuiProgress::CDuiProgress(HWND hWnd, CDuiObject* pDuiObject)
	: CControlBaseFont(hWnd, pDuiObject)
{
	m_bRunTime = false;
	m_nMaxProgress = 100;
	m_nCount = 0;
	m_nTimerCount = 3;

	SetBitmapCount(2);

	m_pImageBackGround = NULL;
	m_sizeBackGround = CSize(0, 0);
	m_pImageForeGround = NULL;
	m_sizeForeGround = CSize(0, 0);
	m_nHeadLength = 0;

	m_clrText = Color(254, 128, 128, 128);
	m_uAlignment = Align_Center;
	m_uVAlignment = VAlign_Middle;
	m_bShowText = FALSE;

	m_nProgress = 0;
	SetProgress(0);
}

CDuiProgress::CDuiProgress(HWND hWnd, CDuiObject* pDuiObject, UINT uControlID, CRect rc, int nProgress/* = 0*/,
					 BOOL bIsVisible/* = TRUE*/, BOOL bIsDisable/* = FALSE*/)
	: CControlBaseFont(hWnd, pDuiObject, uControlID, rc, TEXT(""), bIsVisible, bIsDisable)
{
	m_bRunTime = false;
	m_nMaxProgress = 100;
	m_nCount = 0;
	m_nTimerCount = 3;

	SetBitmapCount(2);

	m_pImageBackGround = NULL;
	m_sizeBackGround = CSize(0, 0);
	m_pImageForeGround = NULL;
	m_sizeForeGround = CSize(0, 0);
	m_nHeadLength = 0;

	m_clrText = Color(254, 128, 128, 128);
	m_uAlignment = Align_Center;
	m_uVAlignment = VAlign_Middle;
	m_bShowText = FALSE;

	m_nProgress = 0;
	SetProgress(nProgress);
}

CDuiProgress::~CDuiProgress(void)
{
	if(m_pImageBackGround != NULL)
	{
		delete m_pImageBackGround;
		m_pImageBackGround = NULL;
	}
	if(m_pImageForeGround != NULL)
	{
		delete m_pImageForeGround;
		m_pImageForeGround = NULL;
	}
}

// ͼƬԵʵ
DUI_IMAGE_ATTRIBUTE_IMPLEMENT(CDuiProgress, BackGround, 1)
DUI_IMAGE_ATTRIBUTE_IMPLEMENT(CDuiProgress, ForeGround, 1)

int CDuiProgress::SetProgress(int nProgress)
{
	if(GetDisable())
	{
		return m_nProgress;
	}

	if(nProgress > m_nMaxProgress)
	{
		// ֵֵ,ԶΪֵ
		nProgress = m_nMaxProgress;
	}

	if(nProgress >= 0 && nProgress <= m_nMaxProgress && m_nProgress != nProgress)
	{
		m_nProgress = nProgress;
		if(GetVisible())
		{
			UpdateControl(true);
		}
	}
	return m_nProgress;
}

// ǷԶ
BOOL CDuiProgress::SetRun(BOOL bRun, int nIndex/* = -1*/)
{
	if(GetDisable())
	{
		return m_bRunTime;
	}

	BOOL bOldRunTime = m_bRunTime;
	int nOldProgress = m_nProgress;
	m_bRunTime = bRun;

	if(nIndex >= 0 && nIndex <= m_nMaxProgress)
	{
		m_nProgress = nIndex;
	}

	if(GetVisible() && ((bOldRunTime != m_bRunTime) || (nOldProgress != m_nProgress)))
	{
		UpdateControl(true);
	}

	return m_bRunTime;
}

// XMLԶ
HRESULT CDuiProgress::OnAttributeRun(const CString& strValue, BOOL bLoading)
{
	if (strValue.IsEmpty()) return E_FAIL;

	BOOL bRun = (strValue == _T("true"));
	SetRun(bRun);

	return bLoading?S_FALSE:S_OK;
}

BOOL CDuiProgress::OnControlTimer()
{
	if(!m_bRunTime || !m_bIsVisible)
	{
		return FALSE;
	}

	if(++m_nCount >= m_nTimerCount)
	{
		m_nCount = 0;
		if(++m_nProgress >= m_nMaxProgress)
		{
			m_nProgress = 0;
		}

		if(GetVisible())
		{
			UpdateControl(true);
		}
		return true;
	}

	return false;
}

void CDuiProgress::DrawControl(CDC &dc, CRect rcUpdate)
{
	int nWidth = m_rc.Width();
	int nHeight = m_rc.Height();

	if(!m_bUpdate)
	{
		UpdateMemDC(dc, nWidth, nHeight);

		m_memDC.BitBlt(0, 0, nWidth, nHeight, &dc, m_rc.left ,m_rc.top, SRCCOPY);

		Graphics graphics(m_memDC);

		if(m_pImageForeGround != NULL)	// ʹñǰͼƬ
		{
			if(m_pImageBackGround != NULL)	//
			{
				DrawImageFrameMID(graphics, m_pImageBackGround, CRect(0, 0, nWidth, nHeight),
					0, 0, m_sizeBackGround.cx, m_sizeBackGround.cy,
					m_nHeadLength, 0, m_nHeadLength, 0);
			}

			if(m_nProgress != 0)	// ǰ
			{
				DrawImageFrameMID(graphics, m_pImageForeGround, CRect(0, 0, nWidth * m_nProgress / m_nMaxProgress, nHeight),
					0, 0, m_sizeForeGround.cx, m_sizeForeGround.cy,
					m_nHeadLength, 0, m_nHeadLength, 0);
			}
		}else
		if(m_pImage != NULL)	// ʹõͼƬ
		{
			DrawImageFrame(graphics, m_pImage, CRect(0, 0, nWidth, nHeight),
				0, 0, m_sizeImage.cx, m_sizeImage.cy, 2);

			if(m_nProgress != 0)
			{
				DrawImageFrame(graphics, m_pImage, CRect(0, 0, nWidth * m_nProgress / m_nMaxProgress, nHeight),
					m_sizeImage.cx, 0, m_sizeImage.cx, m_sizeImage.cy, 2);
			}
		}

		//
		if(m_bShowText)
		{
			BSTR bsFont = m_strFont.AllocSysString();
			FontFamily fontFamily(bsFont);
			Font font(&fontFamily, (REAL)m_nFontWidth, m_fontStyle, UnitPixel);
			::SysFreeString(bsFont);

			SolidBrush solidBrush(m_clrText);
			graphics.SetTextRenderingHint( TextRenderingHintClearTypeGridFit );
			// ˮƽʹֱ뷽ʽ
			DUI_STRING_ALIGN_DEFINE();
			strFormat.SetFormatFlags( StringFormatFlagsNoClip | StringFormatFlagsMeasureTrailingSpaces);

			CString strText;
			// ֵֻΪ100²Żʾٷֺ
			strText.Format(L"%s%d%s", m_strTitle, m_nProgress, (m_nMaxProgress == 100) ? L"%" : L"");
			BSTR bsTitle = strText.AllocSysString();
			RectF rect((Gdiplus::REAL)(0), (Gdiplus::REAL)0, (Gdiplus::REAL)nWidth, (Gdiplus::REAL)nHeight);
			graphics.DrawString(bsTitle, (INT)wcslen(bsTitle), &font, rect, &strFormat, &solidBrush);
			::SysFreeString(bsTitle);
		}
	}

	dc.BitBlt(m_rc.left,m_rc.top, m_rc.Width(), m_rc.Height(), &m_memDC, 0, 0, SRCCOPY);
}<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2017 SLIBIO. All Rights Reserved.
 *
 *  This file is part of the SLib.io project.
 *
 *  This Source Code Form is subject to the terms of the Mozilla Public
 *  License, v. 2.0. If a copy of the MPL was not distributed with this
 *  file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <slib/core.h>

using namespace slib;

int main(int argc, const char * argv[])
{

	// List Example
	{
		int i;
		List<String> list = {"a", "b", "c", "de", "a", "b"};

		Println("Original List");
		i = 0;
		for (auto& item : list) {
			Println("[%d]=%s", i++, item);
		}

		Println("Member Access");
		Println("[3]=%s", list[3]);

		// Insert some values into the list
		for (i = 0; i < 5; i++) {
			list.add(String::format("t%d", i));
		}
		Println("List after insertion");
		i = 0;
		for (auto& item : list) {
			Println("[%d]=%s", i++, item);
		}

		// Remove some values from the list
		list.removeRange(7, 3);
		list.removeAt(3);
		list.removeValues("b");
		Println("List after removal");
		i = 0;
		for (auto& item : list) {
			Println("[%d]=%s", i++, item);
		}

	}

	// Map Example
	{

		HashMap<String, int> map = {{"a", 1}, {"b", 2}, {"c", 3}, {"ab", 11}, {"cd", 34}};

		Println("HashMap");
		for (auto& item : map) {
			Println("[%s]=%d", item.key, item.value);
		}

		Println("Member Access");
		Println("[ab]=%s", map["ab"]);

		// Insert some values into the map
		Println("HashMap after insertion");
		map.put("ab", 12);
		map.put("aaa", 111);
		map.put("abc", 123);
		map.put("baa", 211);
		map.put("bac", 213);
		for (auto& item : map) {
			Println("[%s]=%d", item.key, item.value);
		}

		// Remove some values from the map
		map.remove("ab");
		map.remove("cd");
		Println("HashMap after removal");
		for (auto& item : map) {
			Println("[%s]=%d", item.key, item.value);
		}

		// Convert to TreeMap
		Map<String, int> tree;
		tree.putAll(map);
		Println("Map");
		for (auto& item : tree) {
			Println("[%s]=%d", item.key, item.value);
		}

	}

	return 0;
}
<commit_msg>example: minor change<commit_after>/*
 *  Copyright (c) 2017 SLIBIO. All Rights Reserved.
 *
 *  This file is part of the SLib.io project.
 *
 *  This Source Code Form is subject to the terms of the Mozilla Public
 *  License, v. 2.0. If a copy of the MPL was not distributed with this
 *  file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <slib/core.h>

using namespace slib;

int main(int argc, const char * argv[])
{

	// List Example
	{
		int i;
		List<String> list = {"a", "b", "c", "de", "a", "b"};

		Println("List Original (Count: %d)", list.getCount());
		i = 0;
		for (auto& item : list) {
			Println("[%d]=%s", i++, item);
		}

		Println("Member Access");
		Println("[3]=%s", list[3]);

		// Insert some values into the list
		for (i = 0; i < 5; i++) {
			list.add(String::format("t%d", i));
		}
		Println("List after insertion (Count: %d)", list.getCount());
		i = 0;
		for (auto& item : list) {
			Println("[%d]=%s", i++, item);
		}

		// Remove some values from the list
		list.removeRange(7, 3);
		list.removeAt(3);
		list.removeValues("b");
		Println("List after removal (Count: %d)", list.getCount());
		i = 0;
		for (auto& item : list) {
			Println("[%d]=%s", i++, item);
		}

	}

	// Map Example
	{

		HashMap<String, int> map = {{"a", 1}, {"b", 2}, {"c", 3}, {"ab", 11}, {"cd", 34}};

		Println("HashMap Original (Count: %d)", map.getCount());
		for (auto& item : map) {
			Println("[%s]=%d", item.key, item.value);
		}

		Println("Member Access");
		Println("[ab]=%s", map["ab"]);

		// Insert some values into the map
		map.put("ab", 12);
		map.put("aaa", 111);
		map.put("abc", 123);
		map.put("baa", 211);
		map.put("bac", 213);
		Println("HashMap after insertion (Count: %d)", map.getCount());
		for (auto& item : map) {
			Println("[%s]=%d", item.key, item.value);
		}

		// Remove some values from the map
		map.remove("ab");
		map.remove("cd");
		Println("HashMap after removal (Count: %d)", map.getCount());
		for (auto& item : map) {
			Println("[%s]=%d", item.key, item.value);
		}

		// Convert to Ordered Map
		Map<String, int> tree;
		tree.putAll(map);
		Println("Ordered Map (Count: %d)", tree.getCount());
		for (auto& item : tree) {
			Println("[%s]=%d", item.key, item.value);
		}

	}

	return 0;
}
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
// This file is part of the BWEM Library.
// BWEM is free software, licensed under the MIT/X11 License.
// A copy of the license is provided with the library in the LICENSE file.
// Copyright (c) 2015, 2016, Igor Dimitrijevic
//
//////////////////////////////////////////////////////////////////////////

#include "cp.h"
#include "mapImpl.h"
#include "neutral.h"

using namespace BWAPI;
using namespace BWAPI::UnitTypes::Enum;
namespace { auto & bw = Broodwar; }

using namespace std;

namespace BWEM {

using namespace detail;
using namespace BWAPI_ext;

//////////////////////////////////////////////////////////////////////////////////////////////
//                                                                                //
//                                  class ChokePoint
//                                                                                //
//////////////////////////////////////////////////////////////////////////////////////////////

ChokePoint::ChokePoint(detail::Graph * pGraph, index idx, const Area * area1, const Area * area2, const deque<WalkPosition> & Geometry, Neutral * pBlockingNeutral)
: m_pGraph(pGraph), m_index(idx), m_Areas(area1, area2), m_Geometry(Geometry),
	m_pBlockingNeutral(pBlockingNeutral), m_blocked(pBlockingNeutral != nullptr), m_pseudo(pBlockingNeutral != nullptr)
{
	bwem_assert(!Geometry.empty());

	// Ensures that in the case where several neutrals are stacked, m_pBlockingNeutral points to the bottom one:
	if (m_pBlockingNeutral) m_pBlockingNeutral = GetMap()->GetTile(m_pBlockingNeutral->TopLeft()).GetNeutral();

	m_nodes[end1] = Geometry.front();
	m_nodes[end2] = Geometry.back();

	int i = Geometry.size() / 2;
	while ((i > 0)                      && (GetMap()->GetMiniTile(Geometry[i-1]).Altitude() > GetMap()->GetMiniTile(Geometry[i]).Altitude())) --i;
	while ((i < (int)Geometry.size()-1) && (GetMap()->GetMiniTile(Geometry[i+1]).Altitude() > GetMap()->GetMiniTile(Geometry[i]).Altitude())) ++i;
	m_nodes[middle] = Geometry[i];

	for (int n = 0 ; n < node_count ; ++n)
		for (const Area * pArea : {area1, area2})
		{
			WalkPosition & nodeInArea = (pArea == m_Areas.first) ? m_nodesInArea[n].first : m_nodesInArea[n].second;
			nodeInArea = GetMap()->BreadthFirstSearch(m_nodes[n],
				[pArea, this](const MiniTile & miniTile, WalkPosition w)	// findCond
					{ return (miniTile.AreaId() == pArea->Id()) && !GetMap()->GetTile(TilePosition(w), check_t::no_check).GetNeutral(); },
				[pArea, this](const MiniTile & miniTile, WalkPosition)		// visitCond
					{ return (miniTile.AreaId() == pArea->Id()) || (Blocked() && (miniTile.Blocked())); }
				);
		}
}

ChokePoint::ChokePoint(const ChokePoint & Other)
	: m_pGraph(Other.m_pGraph), m_index(0), m_pseudo(false)
{
	bwem_assert(false);
}

Map * ChokePoint::GetMap() const
{
	return m_pGraph->GetMap();
}

const BWAPI::WalkPosition & ChokePoint::PosInArea(node n, const Area * pArea) const
{
	bwem_assert((pArea == m_Areas.first) || (pArea == m_Areas.second));
	return (pArea == m_Areas.first) ? m_nodesInArea[n].first : m_nodesInArea[n].second;
}

int ChokePoint::DistanceFrom(const ChokePoint * cp) const
{
	return GetGraph()->Distance(this, cp);
}

const CPPath & ChokePoint::GetPathTo(const ChokePoint * cp) const
{
	return GetGraph()->GetPath(this, cp);
}

// Assumes pBlocking->RemoveFromTiles() has been called
void ChokePoint::OnBlockingNeutralDestroyed(const Neutral * pBlocking)
{
	bwem_assert(pBlocking && pBlocking->Blocking());

	if (m_pBlockingNeutral == pBlocking)
	{
		// Ensures that in the case where several neutrals are stacked, m_pBlockingNeutral points to the bottom one:
		m_pBlockingNeutral = GetMap()->GetTile(m_pBlockingNeutral->TopLeft()).GetNeutral();

		if (!m_pBlockingNeutral)
			if (GetGraph()->GetMap()->AutomaticPathUpdate())
				m_blocked = false;
	}

}

} // namespace BWEM

<commit_msg>Applied 'Electric Circuit' bugfix.<commit_after>//////////////////////////////////////////////////////////////////////////
//
// This file is part of the BWEM Library.
// BWEM is free software, licensed under the MIT/X11 License.
// A copy of the license is provided with the library in the LICENSE file.
// Copyright (c) 2015, 2016, Igor Dimitrijevic
//
//////////////////////////////////////////////////////////////////////////

#include "cp.h"
#include "mapImpl.h"
#include "neutral.h"

using namespace BWAPI;
using namespace BWAPI::UnitTypes::Enum;
namespace { auto & bw = Broodwar; }

using namespace std;

namespace BWEM {

using namespace detail;
using namespace BWAPI_ext;

//////////////////////////////////////////////////////////////////////////////////////////////
//                                                                                //
//                                  class ChokePoint
//                                                                                //
//////////////////////////////////////////////////////////////////////////////////////////////

ChokePoint::ChokePoint(detail::Graph * pGraph, index idx, const Area * area1, const Area * area2, const deque<WalkPosition> & Geometry, Neutral * pBlockingNeutral)
: m_pGraph(pGraph), m_index(idx), m_Areas(area1, area2), m_Geometry(Geometry),
	m_pBlockingNeutral(pBlockingNeutral), m_blocked(pBlockingNeutral != nullptr), m_pseudo(pBlockingNeutral != nullptr)
{
	bwem_assert(!Geometry.empty());

	// Ensures that in the case where several neutrals are stacked, m_pBlockingNeutral points to the bottom one:
	if (m_pBlockingNeutral) m_pBlockingNeutral = GetMap()->GetTile(m_pBlockingNeutral->TopLeft()).GetNeutral();

	m_nodes[end1] = Geometry.front();
	m_nodes[end2] = Geometry.back();

	int i = Geometry.size() / 2;
	while ((i > 0)                      && (GetMap()->GetMiniTile(Geometry[i-1]).Altitude() > GetMap()->GetMiniTile(Geometry[i]).Altitude())) --i;
	while ((i < (int)Geometry.size()-1) && (GetMap()->GetMiniTile(Geometry[i+1]).Altitude() > GetMap()->GetMiniTile(Geometry[i]).Altitude())) ++i;
	m_nodes[middle] = Geometry[i];

	for (int n = 0 ; n < node_count ; ++n)
		for (const Area * pArea : {area1, area2})
		{
			WalkPosition & nodeInArea = (pArea == m_Areas.first) ? m_nodesInArea[n].first : m_nodesInArea[n].second;
			nodeInArea = GetMap()->BreadthFirstSearch(m_nodes[n],
				[pArea, this](const MiniTile & miniTile, WalkPosition w)	// findCond
					{ return (miniTile.AreaId() == pArea->Id()) && !GetMap()->GetTile(TilePosition(w), check_t::no_check).GetNeutral(); },
                [pArea, this](const MiniTile & miniTile, WalkPosition w)    // visitCond
                    { return (miniTile.AreaId() == pArea->Id()) || (Blocked() && (miniTile.Blocked() || GetMap()->GetTile(TilePosition(w), check_t::no_check).GetNeutral())); }
				);
		}
}

ChokePoint::ChokePoint(const ChokePoint & Other)
	: m_pGraph(Other.m_pGraph), m_index(0), m_pseudo(false)
{
	bwem_assert(false);
}

Map * ChokePoint::GetMap() const
{
	return m_pGraph->GetMap();
}

const BWAPI::WalkPosition & ChokePoint::PosInArea(node n, const Area * pArea) const
{
	bwem_assert((pArea == m_Areas.first) || (pArea == m_Areas.second));
	return (pArea == m_Areas.first) ? m_nodesInArea[n].first : m_nodesInArea[n].second;
}

int ChokePoint::DistanceFrom(const ChokePoint * cp) const
{
	return GetGraph()->Distance(this, cp);
}

const CPPath & ChokePoint::GetPathTo(const ChokePoint * cp) const
{
	return GetGraph()->GetPath(this, cp);
}

// Assumes pBlocking->RemoveFromTiles() has been called
void ChokePoint::OnBlockingNeutralDestroyed(const Neutral * pBlocking)
{
	bwem_assert(pBlocking && pBlocking->Blocking());

	if (m_pBlockingNeutral == pBlocking)
	{
		// Ensures that in the case where several neutrals are stacked, m_pBlockingNeutral points to the bottom one:
		m_pBlockingNeutral = GetMap()->GetTile(m_pBlockingNeutral->TopLeft()).GetNeutral();

		if (!m_pBlockingNeutral)
			if (GetGraph()->GetMap()->AutomaticPathUpdate())
				m_blocked = false;
	}

}

} // namespace BWEM

<|endoftext|>


<commit_before>#pragma once
#include <map>
namespace Doremi
{
    namespace Core
    {
        /**
        The audio component contains the handle to the soundchannel and a handle to the sound
        */
        // If you add someone,
        enum class AudioCompEnum : int32_t
        {
            Jump,
            Death,
            DamageTaken,
            DebugSound,

            Num_Sounds,
        };
        struct AudioComponent
        {
            // std::map<AudioCompEnum, int> m_enumToSoundID;

            int32_t m_enumToSoundID[(int32_t)(AudioCompEnum::Num_Sounds)]; // +1]; //Todo maybe bugs out
            // int mySoundID = sounds[(int)AudioCompEnum::Jump];
            AudioComponent()
            {
                for(int32_t i = 0; i < (int32_t)AudioCompEnum::Num_Sounds; i++)
                {
                    m_enumToSoundID[i] = (int32_t)AudioCompEnum::DebugSound;
                }
            }
        };
    }
}<commit_msg>All sounds in audio component are initialized as-1<commit_after>#pragma once
#include <map>
namespace Doremi
{
    namespace Core
    {
        /**
        The audio component contains the handle to the soundchannel and a handle to the sound
        */
        // If you add someone,
        enum class AudioCompEnum : int32_t
        {
            Jump,
            Death,
            DamageTaken,
            DebugSound,

            Num_Sounds,
        };
        struct AudioComponent
        {
            // std::map<AudioCompEnum, int> m_enumToSoundID;

            int32_t m_enumToSoundID[(int32_t)(AudioCompEnum::Num_Sounds)]; // +1]; //Todo maybe bugs out
            // int mySoundID = sounds[(int)AudioCompEnum::Jump];
            AudioComponent()
            {
                for(int32_t i = 0; i < (int32_t)AudioCompEnum::Num_Sounds; i++)
                {
                    m_enumToSoundID[i] = -1;
                }
            }
        };
    }
}<|endoftext|>


<commit_before>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2017-2019 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <modules/base/processors/randomspheregenerator.h>
#include <inviwo/core/util/indexmapper.h>

#include <inviwo/core/interaction/events/pickingevent.h>
#include <inviwo/core/interaction/events/mouseevent.h>
#include <inviwo/core/interaction/events/touchevent.h>
#include <inviwo/core/interaction/events/wheelevent.h>
#include <inviwo/core/datastructures/geometry/mesh.h>
#include <inviwo/core/datastructures/buffer/bufferramprecision.h>
#include <inviwo/core/datastructures/buffer/buffer.h>
#include <inviwo/core/algorithm/boundingbox.h>

#include <numeric>

namespace inviwo {

// The Class Identifier has to be globally unique. Use a reverse DNS naming scheme
const ProcessorInfo RandomSphereGenerator::processorInfo_{
    "org.inviwo.RandomSphereGenerator",  // Class identifier
    "Random Sphere Generator",           // Display name
    "Mesh Creation",                     // Category
    CodeState::Stable,                   // Code state
    Tags::CPU,                           // Tags
};
const ProcessorInfo RandomSphereGenerator::getProcessorInfo() const { return processorInfo_; }

RandomSphereGenerator::RandomSphereGenerator()
    : Processor()
    , meshOut_("mesh")
    , seed_("seed", "Seed", 0, 0, std::mt19937::max())
    , reseed_("reseed_", "Seed")
    , scale_("scale", "Scale", 12.0f, 0.001f, 100.0f, 0.1f)
    , size_("size", "Size", 1.0f, 0.001f, 10.0f, 0.1f)
    , gridDim_("gridDim", "Grid Dimension", ivec3(12, 12, 12), ivec3(1), ivec3(128))
    , jigglePos_("jigglePos", "Jiggle Positions", true)
    , enablePicking_("enablePicking", "Enable Picking", false)
    , camera_("camera", "Camera", util::boundingBox(meshOut_))
    , spherePicking_(
          this, gridDim_.get().x * gridDim_.get().y * gridDim_.get().z, [&](PickingEvent* p) {
              handlePicking(p, [&](vec3 delta) {
                  if (positionBuffer_) {
                      auto& pos = positionBuffer_->getDataContainer();
                      pos[p->getPickedId()] += delta;
                      positionBuffer_->getOwner()->invalidateAllOther(positionBuffer_.get());
                  }
              });
          }) {
    addPort(meshOut_);

    addProperty(scale_);
    addProperty(size_);
    addProperty(gridDim_);
    addProperty(jigglePos_);

    addProperty(seed_);
    addProperty(reseed_);

    addProperty(enablePicking_);
    addProperty(camera_);
    camera_.setInvalidationLevel(InvalidationLevel::Valid);
    camera_.setCollapsed(true);

    seed_.setSemantics(PropertySemantics::Text);

    reseed_.onChange([&]() {
        seed_.set(static_cast<glm::i64>(rand(0.0f, static_cast<float>(seed_.getMaxValue()))));
        rand_.seed(static_cast<std::mt19937::result_type>(seed_.get()));
    });
}

void RandomSphereGenerator::process() {
    rand_.seed(static_cast<std::mt19937::result_type>(seed_.get()));

    const vec3 bboxMin(-scale_.get());
    const vec3 extent(scale_.get() * 2.0f);
    const vec3 delta(extent / vec3(gridDim_.get()));

    auto randPos = [&]() { return randVec3(-0.5f, 0.5f); };
    auto randColor = [&]() { return vec4(randVec3(0.5, 1.0), 1); };
    auto randRadius = [&]() { return size_.get() * rand(0.1f, 1.0f); };

    const bool dirty = seed_.isModified() || size_.isModified() || scale_.isModified() ||
                       enablePicking_.isModified();

    if (gridDim_.isModified() || dirty || !positionBuffer_) {
        const auto dim = gridDim_.get();
        const int numSpheres = dim.x * dim.y * dim.z;
        spherePicking_.resize(numSpheres);

        auto mesh = std::make_shared<Mesh>(DrawType::Points, ConnectivityType::None);

        auto vertexRAM = std::make_shared<BufferRAMPrecision<vec3>>(numSpheres);
        auto colorRAM = std::make_shared<BufferRAMPrecision<vec4>>(numSpheres);
        auto radiiRAM = std::make_shared<BufferRAMPrecision<float>>(numSpheres);

        // keep a reference to vertex position buffer for picking
        positionBuffer_ = vertexRAM;
        radiiBuffer_ = radiiRAM;

        mesh->addBuffer(Mesh::BufferInfo(BufferType::PositionAttrib),
                        std::make_shared<Buffer<vec3>>(vertexRAM));
        mesh->addBuffer(Mesh::BufferInfo(BufferType::ColorAttrib),
                        std::make_shared<Buffer<vec4>>(colorRAM));
        mesh->addBuffer(Mesh::BufferInfo(BufferType::RadiiAttrib),
                        std::make_shared<Buffer<float>>(radiiRAM));
        if (enablePicking_.get()) {
            auto pickingRAM = std::make_shared<BufferRAMPrecision<uint32_t>>(numSpheres);
            auto& data = pickingRAM->getDataContainer();
            // fill in picking IDs
            std::iota(data.begin(), data.end(),
                      static_cast<uint32_t>(spherePicking_.getPickingId(0)));

            mesh->addBuffer(Mesh::BufferInfo(BufferType::PickingAttrib),
                            std::make_shared<Buffer<uint32_t>>(pickingRAM));
        }

        auto& vertices = vertexRAM->getDataContainer();
        auto& colors = colorRAM->getDataContainer();
        auto& radii = radiiRAM->getDataContainer();

        util::IndexMapper<3, int> indexmapper(dim);
        if (jigglePos_.get()) {
            for (int i = 0; i < numSpheres; i++) {
                vertices[i] = (vec3(indexmapper(i)) + randPos()) * delta + bboxMin;
                colors[i] = randColor();
                radii[i] = randRadius();
            }
        } else {
            for (int i = 0; i < numSpheres; i++) {
                vertices[i] = vec3(indexmapper(i)) * delta + bboxMin;
                colors[i] = randColor();
                radii[i] = randRadius();
            }
        }
        meshOut_.setData(mesh);
    }
}

float RandomSphereGenerator::rand(const float min, const float max) const {
    return min + dis_(rand_) * (max - min);
}

vec3 RandomSphereGenerator::randVec3(const float min, const float max) const {
    float x = rand(min, max);
    float y = rand(min, max);
    float z = rand(min, max);
    return vec3(x, y, z);
}

vec3 RandomSphereGenerator::randVec3(const vec3& min, const vec3& max) const {
    float x = rand(min.x, max.x);
    float y = rand(min.y, max.y);
    float z = rand(min.z, max.z);
    return vec3(x, y, z);
}

void RandomSphereGenerator::handlePicking(PickingEvent* p, std::function<void(vec3)> callback) {
    if (enablePicking_) {
        if (p->getState() == PickingState::Updated &&
            p->getEvent()->hash() == MouseEvent::chash()) {
            auto me = p->getEventAs<MouseEvent>();
            if ((me->buttonState() & MouseButton::Left) && me->state() == MouseState::Move) {
                auto delta = getDelta(camera_, p);
                callback(delta);
                invalidate(InvalidationLevel::InvalidOutput);
                p->markAsUsed();
            }
        } else if (p->getState() == PickingState::Updated &&
                   p->getEvent()->hash() == TouchEvent::chash()) {

            auto te = p->getEventAs<TouchEvent>();
            if (!te->touchPoints().empty() && te->touchPoints()[0].state() == TouchState::Updated) {
                auto delta = getDelta(camera_, p);
                callback(delta);
                invalidate(InvalidationLevel::InvalidOutput);
                p->markAsUsed();
            }
        }
        else if (p->getState() == PickingState::Updated &&
            p->getEvent()->hash() == WheelEvent::chash()) {
            auto we = p->getEventAs<WheelEvent>();
            LogInfo("wheel event: " << we->delta().y);

            if (radiiBuffer_) {
                auto& radii = radiiBuffer_->getDataContainer();

                radii[p->getPickedId()] *= 1.0f - 0.05f * static_cast<float>(-we->delta().y);

                radiiBuffer_->getOwner()->invalidateAllOther(radiiBuffer_.get());
            }

            invalidate(InvalidationLevel::InvalidOutput);
            p->markAsUsed();
        }
    }
}

vec3 RandomSphereGenerator::getDelta(const Camera& camera, PickingEvent* p) {
    auto currNDC = p->getNDC();
    auto prevNDC = p->getPreviousNDC();

    // Use depth of initial press as reference to move in the image plane.
    auto refDepth = p->getPressedDepth();
    currNDC.z = refDepth;
    prevNDC.z = refDepth;

    auto corrWorld = camera.getWorldPosFromNormalizedDeviceCoords(static_cast<vec3>(currNDC));
    auto prevWorld = camera.getWorldPosFromNormalizedDeviceCoords(static_cast<vec3>(prevNDC));
    return (corrWorld - prevWorld);
}

}  // namespace inviwo
<commit_msg>Base: removed debug output<commit_after>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2017-2019 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <modules/base/processors/randomspheregenerator.h>
#include <inviwo/core/util/indexmapper.h>

#include <inviwo/core/interaction/events/pickingevent.h>
#include <inviwo/core/interaction/events/mouseevent.h>
#include <inviwo/core/interaction/events/touchevent.h>
#include <inviwo/core/interaction/events/wheelevent.h>
#include <inviwo/core/datastructures/geometry/mesh.h>
#include <inviwo/core/datastructures/buffer/bufferramprecision.h>
#include <inviwo/core/datastructures/buffer/buffer.h>
#include <inviwo/core/algorithm/boundingbox.h>

#include <numeric>

namespace inviwo {

// The Class Identifier has to be globally unique. Use a reverse DNS naming scheme
const ProcessorInfo RandomSphereGenerator::processorInfo_{
    "org.inviwo.RandomSphereGenerator",  // Class identifier
    "Random Sphere Generator",           // Display name
    "Mesh Creation",                     // Category
    CodeState::Stable,                   // Code state
    Tags::CPU,                           // Tags
};
const ProcessorInfo RandomSphereGenerator::getProcessorInfo() const { return processorInfo_; }

RandomSphereGenerator::RandomSphereGenerator()
    : Processor()
    , meshOut_("mesh")
    , seed_("seed", "Seed", 0, 0, std::mt19937::max())
    , reseed_("reseed_", "Seed")
    , scale_("scale", "Scale", 12.0f, 0.001f, 100.0f, 0.1f)
    , size_("size", "Size", 1.0f, 0.001f, 10.0f, 0.1f)
    , gridDim_("gridDim", "Grid Dimension", ivec3(12, 12, 12), ivec3(1), ivec3(128))
    , jigglePos_("jigglePos", "Jiggle Positions", true)
    , enablePicking_("enablePicking", "Enable Picking", false)
    , camera_("camera", "Camera", util::boundingBox(meshOut_))
    , spherePicking_(
          this, gridDim_.get().x * gridDim_.get().y * gridDim_.get().z, [&](PickingEvent* p) {
              handlePicking(p, [&](vec3 delta) {
                  if (positionBuffer_) {
                      auto& pos = positionBuffer_->getDataContainer();
                      pos[p->getPickedId()] += delta;
                      positionBuffer_->getOwner()->invalidateAllOther(positionBuffer_.get());
                  }
              });
          }) {
    addPort(meshOut_);

    addProperty(scale_);
    addProperty(size_);
    addProperty(gridDim_);
    addProperty(jigglePos_);

    addProperty(seed_);
    addProperty(reseed_);

    addProperty(enablePicking_);
    addProperty(camera_);
    camera_.setInvalidationLevel(InvalidationLevel::Valid);
    camera_.setCollapsed(true);

    seed_.setSemantics(PropertySemantics::Text);

    reseed_.onChange([&]() {
        seed_.set(static_cast<glm::i64>(rand(0.0f, static_cast<float>(seed_.getMaxValue()))));
        rand_.seed(static_cast<std::mt19937::result_type>(seed_.get()));
    });
}

void RandomSphereGenerator::process() {
    rand_.seed(static_cast<std::mt19937::result_type>(seed_.get()));

    const vec3 bboxMin(-scale_.get());
    const vec3 extent(scale_.get() * 2.0f);
    const vec3 delta(extent / vec3(gridDim_.get()));

    auto randPos = [&]() { return randVec3(-0.5f, 0.5f); };
    auto randColor = [&]() { return vec4(randVec3(0.5, 1.0), 1); };
    auto randRadius = [&]() { return size_.get() * rand(0.1f, 1.0f); };

    const bool dirty = seed_.isModified() || size_.isModified() || scale_.isModified() ||
                       enablePicking_.isModified();

    if (gridDim_.isModified() || dirty || !positionBuffer_) {
        const auto dim = gridDim_.get();
        const int numSpheres = dim.x * dim.y * dim.z;
        spherePicking_.resize(numSpheres);

        auto mesh = std::make_shared<Mesh>(DrawType::Points, ConnectivityType::None);

        auto vertexRAM = std::make_shared<BufferRAMPrecision<vec3>>(numSpheres);
        auto colorRAM = std::make_shared<BufferRAMPrecision<vec4>>(numSpheres);
        auto radiiRAM = std::make_shared<BufferRAMPrecision<float>>(numSpheres);

        // keep a reference to vertex position buffer for picking
        positionBuffer_ = vertexRAM;
        radiiBuffer_ = radiiRAM;

        mesh->addBuffer(Mesh::BufferInfo(BufferType::PositionAttrib),
                        std::make_shared<Buffer<vec3>>(vertexRAM));
        mesh->addBuffer(Mesh::BufferInfo(BufferType::ColorAttrib),
                        std::make_shared<Buffer<vec4>>(colorRAM));
        mesh->addBuffer(Mesh::BufferInfo(BufferType::RadiiAttrib),
                        std::make_shared<Buffer<float>>(radiiRAM));
        if (enablePicking_.get()) {
            auto pickingRAM = std::make_shared<BufferRAMPrecision<uint32_t>>(numSpheres);
            auto& data = pickingRAM->getDataContainer();
            // fill in picking IDs
            std::iota(data.begin(), data.end(),
                      static_cast<uint32_t>(spherePicking_.getPickingId(0)));

            mesh->addBuffer(Mesh::BufferInfo(BufferType::PickingAttrib),
                            std::make_shared<Buffer<uint32_t>>(pickingRAM));
        }

        auto& vertices = vertexRAM->getDataContainer();
        auto& colors = colorRAM->getDataContainer();
        auto& radii = radiiRAM->getDataContainer();

        util::IndexMapper<3, int> indexmapper(dim);
        if (jigglePos_.get()) {
            for (int i = 0; i < numSpheres; i++) {
                vertices[i] = (vec3(indexmapper(i)) + randPos()) * delta + bboxMin;
                colors[i] = randColor();
                radii[i] = randRadius();
            }
        } else {
            for (int i = 0; i < numSpheres; i++) {
                vertices[i] = vec3(indexmapper(i)) * delta + bboxMin;
                colors[i] = randColor();
                radii[i] = randRadius();
            }
        }
        meshOut_.setData(mesh);
    }
}

float RandomSphereGenerator::rand(const float min, const float max) const {
    return min + dis_(rand_) * (max - min);
}

vec3 RandomSphereGenerator::randVec3(const float min, const float max) const {
    float x = rand(min, max);
    float y = rand(min, max);
    float z = rand(min, max);
    return vec3(x, y, z);
}

vec3 RandomSphereGenerator::randVec3(const vec3& min, const vec3& max) const {
    float x = rand(min.x, max.x);
    float y = rand(min.y, max.y);
    float z = rand(min.z, max.z);
    return vec3(x, y, z);
}

void RandomSphereGenerator::handlePicking(PickingEvent* p, std::function<void(vec3)> callback) {
    if (enablePicking_) {
        if (p->getState() == PickingState::Updated &&
            p->getEvent()->hash() == MouseEvent::chash()) {
            auto me = p->getEventAs<MouseEvent>();
            if ((me->buttonState() & MouseButton::Left) && me->state() == MouseState::Move) {
                auto delta = getDelta(camera_, p);
                callback(delta);
                invalidate(InvalidationLevel::InvalidOutput);
                p->markAsUsed();
            }
        } else if (p->getState() == PickingState::Updated &&
                   p->getEvent()->hash() == TouchEvent::chash()) {

            auto te = p->getEventAs<TouchEvent>();
            if (!te->touchPoints().empty() && te->touchPoints()[0].state() == TouchState::Updated) {
                auto delta = getDelta(camera_, p);
                callback(delta);
                invalidate(InvalidationLevel::InvalidOutput);
                p->markAsUsed();
            }
        }
        else if (p->getState() == PickingState::Updated &&
            p->getEvent()->hash() == WheelEvent::chash()) {
            auto we = p->getEventAs<WheelEvent>();
            if (radiiBuffer_) {
                auto& radii = radiiBuffer_->getDataContainer();

                radii[p->getPickedId()] *= 1.0f - 0.05f * static_cast<float>(-we->delta().y);

                radiiBuffer_->getOwner()->invalidateAllOther(radiiBuffer_.get());
            }

            invalidate(InvalidationLevel::InvalidOutput);
            p->markAsUsed();
        }
    }
}

vec3 RandomSphereGenerator::getDelta(const Camera& camera, PickingEvent* p) {
    auto currNDC = p->getNDC();
    auto prevNDC = p->getPreviousNDC();

    // Use depth of initial press as reference to move in the image plane.
    auto refDepth = p->getPressedDepth();
    currNDC.z = refDepth;
    prevNDC.z = refDepth;

    auto corrWorld = camera.getWorldPosFromNormalizedDeviceCoords(static_cast<vec3>(currNDC));
    auto prevWorld = camera.getWorldPosFromNormalizedDeviceCoords(static_cast<vec3>(prevNDC));
    return (corrWorld - prevWorld);
}

}  // namespace inviwo
<|endoftext|>


<commit_before>// inverse.cpp: example program comparing float vs posit using Gauss-Jordan algorithm
//
// Copyright (C) 2017-2020 Stillwater Supercomputing, Inc.
//
// This file is part of the HPRBLAS project, which is released under an MIT Open Source license.

#include <chrono>
//
// enable posit arithmetic exceptions
#define POSIT_THROW_ARITHMETIC_EXCEPTION 1
#include <universal/blas/blas.hpp>
#include <universal/functions/isrepresentable.hpp>

template<size_t nbits, size_t es, size_t capacity = 10>
void ComparePositDecompositions(sw::unum::blas::matrix< sw::unum::posit<nbits, es> >& A, sw::unum::blas::vector< sw::unum::posit<nbits, es> >& x, sw::unum::blas::vector< sw::unum::posit<nbits, es> >& b) {
	using namespace std;
	using namespace sw::unum;
	using namespace sw::unum::blas;
	assert(num_rows(A) == num_cols(A));

	{
		using namespace std::chrono;
		steady_clock::time_point t1 = steady_clock::now();
		auto Ainv = inv(A);
		steady_clock::time_point t2 = steady_clock::now();
		duration<double> time_span = duration_cast<duration<double>>(t2 - t1);
		double elapsed = time_span.count();
		std::cout << "Gauss-Jordan took " << elapsed << " seconds." << std::endl;
		std::cout << "Performance " << (uint32_t)(N*N*N / (1000 * elapsed)) << " KOPS/s" << std::endl;

		x = Ainv * b;
		cout << "Inverse\n" << Ainv << endl;
		cout << "Solution\n" << x << endl;
		cout << "RHS\n" << b << endl;
	}

	std::cout << std::endl;
}

template<size_t nbits, size_t es>
void GaussianEliminationTest() {
	using namespace std;
	using namespace sw::unum;
	using namespace sw::unum::blas;
	using Scalar = sw::unum::posit<nbits, es>;
	using Vector = sw::unum::blas::vector<Scalar>;
	using Matrix = sw::unum::blas::matrix<Scalar>;
	cout << "Using " << dynamic_range<nbits, es>() << endl;

	// repeat set up for posits
	cout << "Posit inputs\n";
	Matrix U = {     // define the upper triangular matrix
		{ 1.0, 2.0, 3.0, 4.0, 5.0 },
		{ 0.0, 1.0, 2.0, 3.0, 4.0 },
		{ 0.0, 0.0, 1.0, 2.0, 3.0 },
		{ 0.0, 0.0, 0.0, 1.0, 2.0 },
		{ 0.0, 0.0, 0.0, 0.0, 1.0 },
	};
	Matrix L = {     // define the lower triangular matrix
		{ 1.0, 0.0, 0.0, 0.0, 0.0 },
		{ 2.0, 1.0, 0.0, 0.0, 0.0 },
		{ 3.0, 2.0, 1.0, 0.0, 0.0 },
		{ 4.0, 3.0, 2.0, 1.0, 0.0 },
		{ 5.0, 4.0, 3.0, 2.0, 1.0 },
	};
	auto A = L * U;   // construct the A matrix to solve
	cout << "L\n" << L << endl;
	cout << "U\n" << U << endl;
	cout << "A\n" << A << endl;
	// define a difficult solution
	Scalar epsplus = Scalar(1) + numeric_limits<Scalar>::epsilon();
	Vector x = {
		epsplus,
		epsplus,
		epsplus,
		epsplus,
		epsplus
	};
	auto b = fmv(A, x);   // construct the right hand side
	cout << "b" << b << endl;
	cout << endl << ">>>>>>>>>>>>>>>>" << endl;
	cout << "LinearSolve fused-dot product" << endl;
	ComparePositDecompositions(A, x, b);
}

int main(int argc, char** argv)
try {
	using namespace std;
	using namespace sw::unum;
	using namespace sw::unum::blas;

	using Scalar = float;
	using Matrix = sw::unum::blas::matrix<Scalar>;
	using Vector = sw::unum::blas::vector<Scalar>;

	Matrix A = {
		{  2, -1,  0,  0,  0 },
		{ -1,  2, -1,  0,  0 },
		{  0, -1,  2, -1,  0 },
		{  0,  0, -1,  2, -1 },
		{  0,  0,  0, -1,  2 }
	};

	auto Ainv = inv(A);
	cout << Ainv << endl;
	cout << Ainv * A << endl;

	// A = L + D + U decomposition
	auto D = diag(diag(A));
	auto L = tril(A) - D;
	auto U = triu(A) - D;

	auto I = eye<Scalar>(num_cols(A));
	L += I;
	auto Linv = inv(L);
	cout << Linv << endl;
	cout << Linv * L << endl << L * Linv << endl;
	return EXIT_SUCCESS;
}
catch (char const* msg) {
	std::cerr << msg << std::endl;
	return EXIT_FAILURE;
}
catch (const posit_arithmetic_exception& err) {
	std::cerr << "Uncaught posit arithmetic exception: " << err.what() << std::endl;
	return EXIT_FAILURE;
}
catch (const quire_exception& err) {
	std::cerr << "Uncaught quire exception: " << err.what() << std::endl;
	return EXIT_FAILURE;
}
catch (const posit_internal_exception& err) {
	std::cerr << "Uncaught posit internal exception: " << err.what() << std::endl;
	return EXIT_FAILURE;
}
catch (std::runtime_error& err) {
	std::cerr << err.what() << std::endl;
	return EXIT_FAILURE;
}
catch (...) {
	std::cerr << "Caught unknown exception" << std::endl;
	return EXIT_FAILURE;
}
<commit_msg>float vs posit comparison for Gauss-Jordan<commit_after>// inverse.cpp: example program comparing float vs posit using Gauss-Jordan algorithm
//
// Copyright (C) 2017-2020 Stillwater Supercomputing, Inc.
//
// This file is part of the HPRBLAS project, which is released under an MIT Open Source license.

#include <chrono>
//
// enable posit arithmetic exceptions
#define POSIT_THROW_ARITHMETIC_EXCEPTION 1
// enable fast posit<32,2>
#define POSIT_FAST_POSIT_32_2 1
#include <universal/posit/posit>
#include <universal/blas/blas.hpp>
#include <universal/blas/generators.hpp>
#include <universal/functions/isrepresentable.hpp>

template<typename Matrix, typename Vector>
void BenchmarkGaussJordan(const Matrix& A, Vector& x, const Vector& b) {
	using namespace std;
	using namespace sw::unum;
	using namespace sw::unum::blas;
	assert(num_rows(A) == num_cols(A));
	size_t N = num_cols(A);
	{
		using namespace std::chrono;
		steady_clock::time_point t1 = steady_clock::now();
		auto Ainv = inv(A);
		steady_clock::time_point t2 = steady_clock::now();
		duration<double> time_span = duration_cast<duration<double>>(t2 - t1);
		double elapsed = time_span.count();
		std::cout << "Gauss-Jordan took " << elapsed << " seconds." << std::endl;
		std::cout << "Performance " << (uint32_t)(N*N*N / (1000000.0 * elapsed)) << " MOPS/s" << std::endl;

		x = Ainv * b;
		cout << "Inverse\n" << Ainv << endl;
		cout << "Solution\n" << x << endl;
		cout << "RHS\n" << b << endl;
	}

	std::cout << std::endl;
}

void Test1() {
	using namespace std;
	using namespace sw::unum;
	using namespace sw::unum::blas;

	using Scalar = float;
	using Matrix = sw::unum::blas::matrix<Scalar>;
	using Vector = sw::unum::blas::vector<Scalar>;

	Matrix A = {
		{  2, -1,  0,  0,  0 },
		{ -1,  2, -1,  0,  0 },
		{  0, -1,  2, -1,  0 },
		{  0,  0, -1,  2, -1 },
		{  0,  0,  0, -1,  2 }
	};

	auto Ainv = inv(A);
	cout << Ainv << endl;
	cout << Ainv * A << endl;

	// A = L + D + U decomposition
	auto D = diag(diag(A));
	auto L = tril(A) - D;
	auto U = triu(A) - D;

	auto I = eye<Scalar>(num_cols(A));
	L += I;
	auto Linv = inv(L);
	cout << Linv << endl;
	cout << Linv * L << endl << L * Linv << endl;
}

int main(int argc, char** argv)
try {
	using namespace std;
	using namespace sw::unum;
	using namespace sw::unum::blas;

	{
		using Scalar = float;
		using Matrix = sw::unum::blas::matrix<Scalar>;
		using Vector = sw::unum::blas::vector<Scalar>;

		constexpr size_t N = 5;
		Matrix A;
		ftcs_fd1D(A, N, N);
		cout << "Finite Difference Matrix\n" << A << endl;

		Vector x(N);
		x = Scalar(1);
		auto b = A * x;

		BenchmarkGaussJordan(A, x, b);

		// visual feedback
		auto Ainv = inv(A);
		cout << Ainv << endl;
		cout << Ainv * A << endl;
	}

	{
		using Scalar = sw::unum::posit<32,2>;
		using Matrix = sw::unum::blas::matrix<Scalar>;
		using Vector = sw::unum::blas::vector<Scalar>;

		constexpr size_t N = 5;
		Matrix A;
		ftcs_fd1D(A, N, N);
		cout << "Finite Difference Matrix\n" << A << endl;

		Vector x(N);
		x = Scalar(1);
		auto b = A * x;

		BenchmarkGaussJordan(A, x, b);

		// visual feedback
		auto Ainv = inv(A);
		cout << Ainv << endl;
		cout << Ainv * A << endl;
	}

	return EXIT_SUCCESS;
}
catch (char const* msg) {
	std::cerr << msg << std::endl;
	return EXIT_FAILURE;
}
catch (const posit_arithmetic_exception& err) {
	std::cerr << "Uncaught posit arithmetic exception: " << err.what() << std::endl;
	return EXIT_FAILURE;
}
catch (const quire_exception& err) {
	std::cerr << "Uncaught quire exception: " << err.what() << std::endl;
	return EXIT_FAILURE;
}
catch (const posit_internal_exception& err) {
	std::cerr << "Uncaught posit internal exception: " << err.what() << std::endl;
	return EXIT_FAILURE;
}
catch (std::runtime_error& err) {
	std::cerr << err.what() << std::endl;
	return EXIT_FAILURE;
}
catch (...) {
	std::cerr << "Caught unknown exception" << std::endl;
	return EXIT_FAILURE;
}
<|endoftext|>


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

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

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

#include <irtkImage.h>
#include <nr.h>

#include <sys/types.h>

#ifdef WIN32
#include <time.h>
#else
#include <sys/time.h>
#endif

#include <map>

char *output_name = NULL, **input_names = NULL;
char *mask_name = NULL;

long ran2Seed;
long ran2initialSeed;

// first short is the label, second short is the number of images voting
// for that label.
typedef map<short, short> countMap;

map<short, short>::iterator iter;

short getMostPopular(countMap cMap){
  short maxCount = 0, mostPopLabel = -1;

  if (cMap.size() == 0){
    // No votes to count, treat as background.
    return 0;
  }

  for (iter = cMap.begin(); iter != cMap.end(); ++iter){

    if (iter->second > maxCount){
      maxCount     = iter->second;
      mostPopLabel = iter->first;
    }
  }

  return mostPopLabel;
}

bool isEquivocal(countMap cMap){
  short maxCount = 0;
  short numberWithMax = 0;

  if (cMap.size() == 0){
    // No votes to count, treat as background.
    return false;
  }

  for (iter = cMap.begin(); iter != cMap.end(); ++iter){
    if (iter->second > maxCount){
      maxCount     = iter->second;
    }
  }

  for (iter = cMap.begin(); iter != cMap.end(); ++iter){
    if (iter->second ==  maxCount){
      ++numberWithMax;
    }
  }

  if (numberWithMax > 1){
    return true;
  } else {
    return false;
  }

}

short decideOnTie(countMap cMap){
  short maxCount = 0;
  short numberWithMax = 0;
  int index, count;
  short temp;
  double val;

  if (cMap.size() == 0){
    // No votes to count, treat as background.
    return false;
  }

  for (iter = cMap.begin(); iter != cMap.end(); ++iter){
    if (iter->second > maxCount){
      maxCount     = iter->second;
    }
  }

  for (iter = cMap.begin(); iter != cMap.end(); ++iter){
    if (iter->second ==  maxCount){
      ++numberWithMax;
    }
  }

  short *tiedLabels = new short[numberWithMax];

  count = 0;
  for (iter = cMap.begin(); iter != cMap.end(); ++iter){
    if (iter->second ==  maxCount){
      tiedLabels[count] = iter->first;
      ++count;
    }
  }

  val =  ran2(&ran2Seed);

  index = (int) round(val * (count - 1));

  temp = tiedLabels[index];

  delete tiedLabels;

  return temp;
}

void usage()
{
  cerr << " " << endl;
  cerr << " Usage: combineLabels [output] [N] [input1] .. [inputN] <-options>" << endl;
  cerr << " " << endl;
  cerr << " Combine [N] label images into a consensus labelling using the vote rule." << endl;
  cerr << " Labels for voxels where the vote is tied for are decided randomly." << endl;
  cerr << " " << endl;
  cerr << " The images [input1] .. [inputN] are assumed to contain labellings on the" << endl;
  cerr << " same voxel grid.  For each voxel, the modal label from the images is used " << endl;
  cerr << " to generate a label in the output image." << endl;
  cerr << " " << endl;
  cerr << " Options:" << endl;
  cerr << " -u [filename]     Write out a volume showing the unanimous voxels." << endl;
  cerr << " -pad [value]      Padding value, default = -1." << endl;
  cerr << " " << endl;
  exit(1);
}

int main(int argc, char **argv)
{
  int numberOfClassifiers, i, v, ok, voxels, contendedVoxelCount, contendedVoxelIndex, equivocalCount;
  irtkGreyPixel *pIn, *pIn_0, *pOut;
  irtkGreyImage input, output;
  irtkGreyImage *input_0;
  irtkByteImage mask;
  irtkBytePixel *pMask;
  int writeMask = false;
  int pad = -1;

  // Check command line
  if (argc < 4){
    usage();
  }

  output_name = argv[1];
  argc--;
  argv++;

  numberOfClassifiers = atoi(argv[1]);
  argc--;
  argv++;

  input_names = new char *[numberOfClassifiers];
  for (i = 0; i < numberOfClassifiers; i++){
    input_names[i] = argv[1];
    argc--;
    argv++;
  }

  while (argc > 1){
    ok = false;
    if ((ok == false) && (strcmp(argv[1], "-u") == 0)){
      argc--;      argv++;
      mask_name = argv[1];
      writeMask = true;
      argc--;      argv++;
      ok = true;
    }
    if ((ok == false) && (strcmp(argv[1], "-pad") == 0)){
      argc--;      argv++;
      pad = atoi(argv[1]);
      argc--;      argv++;
      ok = true;
    }

    if (ok == false){
      cerr << "Can not parse argument " << argv[1] << endl;
      usage();
    }
  }

  // Mask has a value of 1 for all uncontended voxels.
  mask.Read(input_names[0]);
  voxels = mask.GetNumberOfVoxels();

  // Reset mask so that all voxels are marked as unanimous.
  pMask = mask.GetPointerToVoxels();
  for (i = 0; i < voxels; ++i){
    *pMask = 1;
    ++pMask;
  }

  input_0 = new irtkGreyImage(input_names[0]);

  for (i = 1; i < numberOfClassifiers; ++i){

    input.Read(input_names[i]);

    pIn   = input.GetPointerToVoxels();
    pIn_0 = input_0->GetPointerToVoxels();
    pMask = mask.GetPointerToVoxels();

      for (v = 0; v < voxels; ++v){

        if (*pIn != *pIn_0 && (*pIn > pad || *pIn_0 > pad) ){
          *pMask = 0;
        }
        ++pIn;
        ++pIn_0;
        ++pMask;
      }
  }

  // Do we need to write out the `unanimask'?
  if (writeMask == true && mask_name != NULL){
    mask.Write(mask_name);
  }

  // free some memory.
  delete input_0;

  contendedVoxelCount = 0;
  pMask = mask.GetPointerToVoxels();

  for (i = 0; i < voxels; ++i){
    if (*pMask == 0){
      ++contendedVoxelCount;
    }
    ++pMask;
  }

  cout << "Number of contended voxels = " << contendedVoxelCount << " = ";
  cout << 100.0 * contendedVoxelCount / ((double) voxels) << "%" << endl;

  countMap *counts = new countMap[contendedVoxelCount];

  for (i = 0; i < numberOfClassifiers; ++i){

    input.Read(input_names[i]);

    pIn = input.GetPointerToVoxels();
    pMask = mask.GetPointerToVoxels();

    contendedVoxelIndex = 0;
    for (v = 0; v < voxels; ++v){

      //Is the current voxel contended?
      if (*pMask == 0){
        if (*pIn > pad){
          ++counts[contendedVoxelIndex][*pIn];
        }
        ++contendedVoxelIndex;
      }
      ++pIn;
      ++pMask;
    }
  }

  // Initialise output image using first input image, all inputs assumed
  // same size etc..
  output.Read(input_names[0]);
  pOut  = output.GetPointerToVoxels();
  pMask = mask.GetPointerToVoxels();

  contendedVoxelIndex = 0;
  for (v = 0; v < voxels; ++v){

    //Is the current voxel contentded?
    if (*pMask == 0){
      *pOut = getMostPopular(counts[contendedVoxelIndex]);
      ++contendedVoxelIndex;
    }

    ++pOut;
    ++pMask;
  }

  // Get ready for random stuff.
  time_t tv;
  tv = time(NULL);

  ran2Seed = tv;
  ran2initialSeed = -1 * ran2Seed;
  (void) ran2(&ran2initialSeed);

  contendedVoxelIndex = 0;
  equivocalCount = 0;

  pOut  = output.GetPointerToVoxels();
  pMask = mask.GetPointerToVoxels();
  for (v = 0; v < voxels; ++v){

    //Is the current voxel contended?
    if (*pMask == 0){
      if (isEquivocal(counts[contendedVoxelIndex])){
        ++equivocalCount;
        *pOut = decideOnTie(counts[contendedVoxelIndex]);
      }
      ++contendedVoxelIndex;
    }
    ++pOut;
    ++pMask;
  }

  cout << "Number of equivocal voxels = " << equivocalCount << " = ";
  cout << 100.0 * equivocalCount / ((double) voxels) << "%" << endl;

  output.Write(output_name);

  delete [] counts;
}
<commit_msg>Fixed bug in random choice when deciding on a tied voxel.<commit_after>/*=========================================================================

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

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

#include <irtkImage.h>
#include <nr.h>

#include <sys/types.h>

#ifdef WIN32
#include <time.h>
#else
#include <sys/time.h>
#endif

#include <map>

char *output_name = NULL, **input_names = NULL;
char *mask_name = NULL;

long ran2Seed;
long ran2initialSeed;

// first short is the label, second short is the number of images voting
// for that label.
typedef map<short, short> countMap;

map<short, short>::iterator iter;

short getMostPopular(countMap cMap){
  short maxCount = 0, mostPopLabel = -1;

  if (cMap.size() == 0){
    // No votes to count, treat as background.
    return 0;
  }

  for (iter = cMap.begin(); iter != cMap.end(); ++iter){

    if (iter->second > maxCount){
      maxCount     = iter->second;
      mostPopLabel = iter->first;
    }
  }

  return mostPopLabel;
}

bool isEquivocal(countMap cMap){
  short maxCount = 0;
  short numberWithMax = 0;

  if (cMap.size() == 0){
    // No votes to count, treat as background.
    return false;
  }

  for (iter = cMap.begin(); iter != cMap.end(); ++iter){
    if (iter->second > maxCount){
      maxCount     = iter->second;
    }
  }

  for (iter = cMap.begin(); iter != cMap.end(); ++iter){
    if (iter->second ==  maxCount){
      ++numberWithMax;
    }
  }

  if (numberWithMax > 1){
    return true;
  } else {
    return false;
  }

}

short decideOnTie(countMap cMap){
  short maxCount = 0;
  short numberWithMax = 0;
  int index, count;
  short temp;
  double val;

  if (cMap.size() == 0){
    // No votes to count, treat as background.
    return false;
  }

  for (iter = cMap.begin(); iter != cMap.end(); ++iter){
    if (iter->second > maxCount){
      maxCount     = iter->second;
    }
  }

  for (iter = cMap.begin(); iter != cMap.end(); ++iter){
    if (iter->second ==  maxCount){
      ++numberWithMax;
    }
  }

  short *tiedLabels = new short[numberWithMax];

  count = 0;
  for (iter = cMap.begin(); iter != cMap.end(); ++iter){
    if (iter->second ==  maxCount){
      tiedLabels[count] = iter->first;
      ++count;
    }
  }

  index = (int) floor( ran2(&ran2Seed) * count );

  temp = tiedLabels[index];
  delete tiedLabels;

  return temp;
}

void usage()
{
  cerr << " " << endl;
  cerr << " Usage: combineLabels [output] [N] [input1] .. [inputN] <-options>" << endl;
  cerr << " " << endl;
  cerr << " Combine [N] label images into a consensus labelling using the vote rule." << endl;
  cerr << " Labels for voxels where the vote is tied for are decided randomly." << endl;
  cerr << " " << endl;
  cerr << " The images [input1] .. [inputN] are assumed to contain labellings on the" << endl;
  cerr << " same voxel grid.  For each voxel, the modal label from the images is used " << endl;
  cerr << " to generate a label in the output image." << endl;
  cerr << " " << endl;
  cerr << " Options:" << endl;
  cerr << " -u [filename]     Write out a volume showing the unanimous voxels." << endl;
  cerr << " -pad [value]      Padding value, default = -1." << endl;
  cerr << " " << endl;
  exit(1);
}

int main(int argc, char **argv)
{
  int numberOfClassifiers, i, v, ok, voxels, contendedVoxelCount, contendedVoxelIndex, equivocalCount;
  irtkGreyPixel *pIn, *pIn_0, *pOut;
  irtkGreyImage input, output;
  irtkGreyImage *input_0;
  irtkByteImage mask;
  irtkBytePixel *pMask;
  int writeMask = false;
  int pad = -1;

  // Check command line
  if (argc < 4){
    usage();
  }

  output_name = argv[1];
  argc--;
  argv++;

  numberOfClassifiers = atoi(argv[1]);
  argc--;
  argv++;

  input_names = new char *[numberOfClassifiers];
  for (i = 0; i < numberOfClassifiers; i++){
    input_names[i] = argv[1];
    argc--;
    argv++;
  }

  while (argc > 1){
    ok = false;
    if ((ok == false) && (strcmp(argv[1], "-u") == 0)){
      argc--;      argv++;
      mask_name = argv[1];
      writeMask = true;
      argc--;      argv++;
      ok = true;
    }
    if ((ok == false) && (strcmp(argv[1], "-pad") == 0)){
      argc--;      argv++;
      pad = atoi(argv[1]);
      argc--;      argv++;
      ok = true;
    }

    if (ok == false){
      cerr << "Can not parse argument " << argv[1] << endl;
      usage();
    }
  }

  // Mask has a value of 1 for all uncontended voxels.
  mask.Read(input_names[0]);
  voxels = mask.GetNumberOfVoxels();

  // Reset mask so that all voxels are marked as unanimous.
  pMask = mask.GetPointerToVoxels();
  for (i = 0; i < voxels; ++i){
    *pMask = 1;
    ++pMask;
  }

  input_0 = new irtkGreyImage(input_names[0]);

  for (i = 1; i < numberOfClassifiers; ++i){

    input.Read(input_names[i]);

    pIn   = input.GetPointerToVoxels();
    pIn_0 = input_0->GetPointerToVoxels();
    pMask = mask.GetPointerToVoxels();

      for (v = 0; v < voxels; ++v){

        if (*pIn != *pIn_0 && (*pIn > pad || *pIn_0 > pad) ){
          *pMask = 0;
        }
        ++pIn;
        ++pIn_0;
        ++pMask;
      }
  }

  // Do we need to write out the `unanimask'?
  if (writeMask == true && mask_name != NULL){
    mask.Write(mask_name);
  }

  // free some memory.
  delete input_0;

  contendedVoxelCount = 0;
  pMask = mask.GetPointerToVoxels();

  for (i = 0; i < voxels; ++i){
    if (*pMask == 0){
      ++contendedVoxelCount;
    }
    ++pMask;
  }

  cout << "Number of contended voxels = " << contendedVoxelCount << " = ";
  cout << 100.0 * contendedVoxelCount / ((double) voxels) << "%" << endl;

  countMap *counts = new countMap[contendedVoxelCount];

  for (i = 0; i < numberOfClassifiers; ++i){

    input.Read(input_names[i]);

    pIn = input.GetPointerToVoxels();
    pMask = mask.GetPointerToVoxels();

    contendedVoxelIndex = 0;
    for (v = 0; v < voxels; ++v){

      //Is the current voxel contended?
      if (*pMask == 0){
        if (*pIn > pad){
          ++counts[contendedVoxelIndex][*pIn];
        }
        ++contendedVoxelIndex;
      }
      ++pIn;
      ++pMask;
    }
  }

  // Initialise output image using first input image, all inputs assumed
  // same size etc..
  output.Read(input_names[0]);
  pOut  = output.GetPointerToVoxels();
  pMask = mask.GetPointerToVoxels();

  contendedVoxelIndex = 0;
  for (v = 0; v < voxels; ++v){

    //Is the current voxel contentded?
    if (*pMask == 0){
      *pOut = getMostPopular(counts[contendedVoxelIndex]);
      ++contendedVoxelIndex;
    }

    ++pOut;
    ++pMask;
  }

  // Get ready for random stuff.
  time_t tv;
  tv = time(NULL);

  ran2Seed = tv;
  ran2initialSeed = -1 * ran2Seed;
  (void) ran2(&ran2initialSeed);

  contendedVoxelIndex = 0;
  equivocalCount = 0;

  pOut  = output.GetPointerToVoxels();
  pMask = mask.GetPointerToVoxels();
  for (v = 0; v < voxels; ++v){

    //Is the current voxel contended?
    if (*pMask == 0){
      if (isEquivocal(counts[contendedVoxelIndex])){
        ++equivocalCount;
        *pOut = decideOnTie(counts[contendedVoxelIndex]);
      }
      ++contendedVoxelIndex;
    }
    ++pOut;
    ++pMask;
  }

  cout << "Number of equivocal voxels = " << equivocalCount << " = ";
  cout << 100.0 * equivocalCount / ((double) voxels) << "%" << endl;

  output.Write(output_name);

  delete [] counts;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fumorph.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 05:35:55 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SD_FU_MORPH_HXX
#define SD_FU_MORPH_HXX

#ifndef SD_FU_POOR_HXX
#include "fupoor.hxx"
#endif

#include <math.h>

/*************************************************************************
|*
\************************************************************************/
class List;
class PolyPolygon3D;
class Polygon3D;
class Vector3D;

namespace sd {

class FuMorph
    : public FuPoor
{
public:
    TYPEINFO();

    FuMorph (
        ViewShell* pViewSh,
        ::sd::Window* pWin,
        ::sd::View* pView,
        SdDrawDocument* pDoc,
        SfxRequest& rReq);
    virtual ~FuMorph (void) {}

private:
    void ImpInsertPolygons(List& rPolyPolyList3D, BOOL bAttributeFade,
        const SdrObject* pObj1, const SdrObject* pObj2);
    PolyPolygon3D* ImpCreateMorphedPolygon(
        const PolyPolygon3D& rPolyPolyStart,
        const PolyPolygon3D& rPolyPolyEnd,
        const double fMorphingFactor);
    BOOL ImpMorphPolygons(
        const PolyPolygon3D& rPolyPoly1, const PolyPolygon3D& rPolyPoly2,
        const USHORT nSteps, List& rPolyPolyList3D);
    void ImpAddPolys(PolyPolygon3D& rSmaller, const PolyPolygon3D& rBigger);
    void ImpEqualizePolyPointCount(Polygon3D& rSmall, const Polygon3D& rBig);
    sal_uInt16 ImpGetNearestIndex(const Polygon3D& rPoly, const Vector3D& rPos);
};

} // end of namespace sd

#endif
<commit_msg>INTEGRATION: CWS impressfunctions (1.3.38); FILE MERGED 2005/10/28 10:56:50 cl 1.3.38.1: #125341# reworked FuPoor classes to use refcounting<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fumorph.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-12-14 17:13:27 $
 *
 *  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 SD_FU_MORPH_HXX
#define SD_FU_MORPH_HXX

#ifndef SD_FU_POOR_HXX
#include "fupoor.hxx"
#endif

#include <math.h>

/*************************************************************************
|*
\************************************************************************/
class List;
class PolyPolygon3D;
class Polygon3D;
class Vector3D;

namespace sd {

class FuMorph
    : public FuPoor
{
public:
    TYPEINFO();

    static FunctionReference Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq );
    virtual void DoExecute( SfxRequest& rReq );

private:
    FuMorph (
        ViewShell* pViewSh,
        ::sd::Window* pWin,
        ::sd::View* pView,
        SdDrawDocument* pDoc,
        SfxRequest& rReq);

    void ImpInsertPolygons(List& rPolyPolyList3D, BOOL bAttributeFade,
        const SdrObject* pObj1, const SdrObject* pObj2);
    PolyPolygon3D* ImpCreateMorphedPolygon(
        const PolyPolygon3D& rPolyPolyStart,
        const PolyPolygon3D& rPolyPolyEnd,
        const double fMorphingFactor);
    BOOL ImpMorphPolygons(
        const PolyPolygon3D& rPolyPoly1, const PolyPolygon3D& rPolyPoly2,
        const USHORT nSteps, List& rPolyPolyList3D);
    void ImpAddPolys(PolyPolygon3D& rSmaller, const PolyPolygon3D& rBigger);
    void ImpEqualizePolyPointCount(Polygon3D& rSmall, const Polygon3D& rBig);
    sal_uInt16 ImpGetNearestIndex(const Polygon3D& rPoly, const Vector3D& rPos);
};

} // end of namespace sd

#endif
<|endoftext|>


<commit_before>//===-- InstLoops.cpp ---------------------------------------- ---*- C++ -*--=//
// Pass to instrument loops
//
// At every backedge, insert a counter for that backedge and a call function
//===----------------------------------------------------------------------===//

#include "llvm/Reoptimizer/InstLoops.h"
#include "llvm/Support/CFG.h"
#include "llvm/Constants.h"
#include "llvm/iMemory.h"
#include "llvm/GlobalVariable.h"
#include "llvm/DerivedTypes.h"
#include "llvm/iOther.h"
#include "llvm/iOperators.h"
#include "llvm/iTerminators.h"
#include "llvm/iPHINode.h"
#include "llvm/Module.h"
#include "llvm/Function.h"
#include "llvm/Pass.h"

//this is used to color vertices
//during DFS

enum Color{
  WHITE,
  GREY,
  BLACK
};

struct InstLoops : public FunctionPass {
  bool runOnFunction(Function &F);
};

static RegisterOpt<InstLoops> X("instloops", "Instrument backedges for profiling");

// createProfilePathsPass - Create a new pass to add path profiling
//
Pass *createInstLoopsPass() {
  return new InstLoops();
}

//helper function to get back edges: it is called by
//the "getBackEdges" function below
void getBackEdgesVisit(BasicBlock *u,
                       std::map<BasicBlock *, Color > &color,
                       std::map<BasicBlock *, int > &d,
                       int &time, Value *threshold) {

  color[u]=GREY;
  time++;
  d[u]=time;

  for(BasicBlock::succ_iterator vl = succ_begin(u),
	ve = succ_end(u); vl != ve; ++vl){

    BasicBlock *BB = *vl;

    if(color[BB]!=GREY && color[BB]!=BLACK){
      getBackEdgesVisit(BB, color, d, time, threshold);
    }

    //now checking for d and f vals
    if(color[BB]==GREY){
      //so v is ancestor of u if time of u > time of v
      if(d[u] >= d[BB]){
        //insert a new basic block: modify terminator accordingly!
        BasicBlock *newBB = new BasicBlock("", u->getParent());
        BranchInst *ti = cast<BranchInst>(u->getTerminator());
        unsigned char index = 1;
        if(ti->getSuccessor(0) == BB){
          index = 0;
        }
        assert(ti->getNumSuccessors() > index && "Not enough successors!");
        ti->setSuccessor(index, newBB);

        //insert global variable of type int
        Constant *initializer = Constant::getNullValue(Type::IntTy);
        GlobalVariable *countVar = new GlobalVariable(Type::IntTy, false, true,
                                                      initializer,
                                                      "loopCounter",
                                                      u->getParent()->getParent());

        //load the variable
        Instruction *ldInst = new LoadInst(countVar,"");

        //increment
        Instruction *addIn =
          BinaryOperator::create(Instruction::Add, ldInst,
                                 ConstantSInt::get(Type::IntTy,1), "");

        //store
        Instruction *stInst = new StoreInst(addIn, countVar);

        Instruction *etr = new LoadInst(threshold, "threshold");
        Instruction *cmpInst = new SetCondInst(Instruction::SetLE, etr,
                                               addIn, "");

        BasicBlock *callTrigger = new BasicBlock("", u->getParent());
        //branch to calltrigger, or *vl
        Instruction *newBr = new BranchInst(callTrigger, BB, cmpInst);

        BasicBlock::InstListType &lt = newBB->getInstList();

        lt.push_back(ldInst);
        lt.push_back(addIn);
        lt.push_back(stInst);
        lt.push_back(etr);
        lt.push_back(cmpInst);
        lt.push_back(newBr);

        //Now add instructions to the triggerCall BB
        //now create a call function
        //call llvm_first_trigger(int *x);
        std::vector<const Type*> inCountArgs;
        inCountArgs.push_back(PointerType::get(Type::IntTy));

        const FunctionType *cFty = FunctionType::get(Type::VoidTy, inCountArgs,
                                                     false);
        Function *inCountMth =
          u->getParent()->getParent()->getOrInsertFunction("llvm_first_trigger", cFty);

        assert(inCountMth && "Initialize method could not be inserted!");

        std::vector<Value *> iniArgs;
        iniArgs.push_back(countVar);
        Instruction *call = new CallInst(inCountMth, iniArgs, "");
        callTrigger->getInstList().push_back(call);
        callTrigger->getInstList().push_back(new BranchInst(BB));

        //now iterate over *vl, and set its Phi nodes right
        for(BasicBlock::iterator BB2Inst = BB->begin(), BBend = BB->end();
            BB2Inst != BBend; ++BB2Inst){

          if(PHINode *phiInst=dyn_cast<PHINode>(&*BB2Inst)){
            int bbIndex = phiInst->getBasicBlockIndex(u);
            if(bbIndex>=0){
              phiInst->setIncomingBlock(bbIndex, newBB);

              Value *val = phiInst->getIncomingValue((unsigned int)bbIndex);
              phiInst->addIncoming(val, callTrigger);
            }
          }
        }
      }
    }
  }
  color[u]=BLACK;//done with visiting the node and its neighbors
}

//getting the backedges in a graph
//Its a variation of DFS to get the backedges in the graph
//We get back edges by associating a time
//and a color with each vertex.
//The time of a vertex is the time when it was first visited
//The color of a vertex is initially WHITE,
//Changes to GREY when it is first visited,
//and changes to BLACK when ALL its neighbors
//have been visited
//So we have a back edge when we meet a successor of
//a node with smaller time, and GREY color
void getBackEdges(Function &F, Value *threshold){
  std::map<BasicBlock *, Color > color;
  std::map<BasicBlock *, int> d;
  int time=0;
  getBackEdgesVisit(F.begin(), color, d, time, threshold);
}

//Per function pass for inserting counters and call function
bool InstLoops::runOnFunction(Function &F){

  static GlobalVariable *threshold = NULL;
  static bool insertedThreshold = false;

   if(!insertedThreshold){
    threshold = new GlobalVariable(Type::IntTy, false, false, 0,
                                                   "reopt_threshold");

    F.getParent()->getGlobalList().push_back(threshold);
    insertedThreshold = true;
  }

  if(F.getName() == "main"){
    //intialize threshold
    std::vector<const Type*> initialize_args;
    initialize_args.push_back(PointerType::get(Type::IntTy));

    const FunctionType *Fty = FunctionType::get(Type::VoidTy, initialize_args,
                                                false);
    Function *initialMeth = F.getParent()->getOrInsertFunction("reoptimizerInitialize", Fty);
    assert(initialMeth && "Initialize method could not be inserted!");

    std::vector<Value *> trargs;
    trargs.push_back(threshold);

    new CallInst(initialMeth, trargs, "", F.begin()->begin());
  }

  assert(threshold && "GlobalVariable threshold not defined!");

  if(F.isExternal()) {
    return false;
  }

  getBackEdges(F, threshold);

  return true;
}
<commit_msg>Fix typeo<commit_after>//===-- InstLoops.cpp ---------------------------------------- ---*- C++ -*--=//
// Pass to instrument loops
//
// At every backedge, insert a counter for that backedge and a call function
//===----------------------------------------------------------------------===//

#include "llvm/Reoptimizer/InstLoops.h"
#include "llvm/Support/CFG.h"
#include "llvm/Constants.h"
#include "llvm/iMemory.h"
#include "llvm/GlobalVariable.h"
#include "llvm/DerivedTypes.h"
#include "llvm/iOther.h"
#include "llvm/iOperators.h"
#include "llvm/iTerminators.h"
#include "llvm/iPHINode.h"
#include "llvm/Module.h"
#include "llvm/Function.h"
#include "llvm/Pass.h"

//this is used to color vertices
//during DFS

enum Color{
  WHITE,
  GREY,
  BLACK
};

struct InstLoops : public FunctionPass {
  bool runOnFunction(Function &F);
};

static RegisterOpt<InstLoops> X("instloops", "Instrument backedges for profiling");

// createInstLoopsPass - Create a new pass to add path profiling
//
Pass *createInstLoopsPass() {
  return new InstLoops();
}

//helper function to get back edges: it is called by
//the "getBackEdges" function below
void getBackEdgesVisit(BasicBlock *u,
                       std::map<BasicBlock *, Color > &color,
                       std::map<BasicBlock *, int > &d,
                       int &time, Value *threshold) {

  color[u]=GREY;
  time++;
  d[u]=time;

  for(BasicBlock::succ_iterator vl = succ_begin(u),
	ve = succ_end(u); vl != ve; ++vl){

    BasicBlock *BB = *vl;

    if(color[BB]!=GREY && color[BB]!=BLACK){
      getBackEdgesVisit(BB, color, d, time, threshold);
    }

    //now checking for d and f vals
    if(color[BB]==GREY){
      //so v is ancestor of u if time of u > time of v
      if(d[u] >= d[BB]){
        //insert a new basic block: modify terminator accordingly!
        BasicBlock *newBB = new BasicBlock("", u->getParent());
        BranchInst *ti = cast<BranchInst>(u->getTerminator());
        unsigned char index = 1;
        if(ti->getSuccessor(0) == BB){
          index = 0;
        }
        assert(ti->getNumSuccessors() > index && "Not enough successors!");
        ti->setSuccessor(index, newBB);

        //insert global variable of type int
        Constant *initializer = Constant::getNullValue(Type::IntTy);
        GlobalVariable *countVar = new GlobalVariable(Type::IntTy, false, true,
                                                      initializer,
                                                      "loopCounter",
                                                      u->getParent()->getParent());

        //load the variable
        Instruction *ldInst = new LoadInst(countVar,"");

        //increment
        Instruction *addIn =
          BinaryOperator::create(Instruction::Add, ldInst,
                                 ConstantSInt::get(Type::IntTy,1), "");

        //store
        Instruction *stInst = new StoreInst(addIn, countVar);

        Instruction *etr = new LoadInst(threshold, "threshold");
        Instruction *cmpInst = new SetCondInst(Instruction::SetLE, etr,
                                               addIn, "");

        BasicBlock *callTrigger = new BasicBlock("", u->getParent());
        //branch to calltrigger, or *vl
        Instruction *newBr = new BranchInst(callTrigger, BB, cmpInst);

        BasicBlock::InstListType &lt = newBB->getInstList();

        lt.push_back(ldInst);
        lt.push_back(addIn);
        lt.push_back(stInst);
        lt.push_back(etr);
        lt.push_back(cmpInst);
        lt.push_back(newBr);

        //Now add instructions to the triggerCall BB
        //now create a call function
        //call llvm_first_trigger(int *x);
        std::vector<const Type*> inCountArgs;
        inCountArgs.push_back(PointerType::get(Type::IntTy));

        const FunctionType *cFty = FunctionType::get(Type::VoidTy, inCountArgs,
                                                     false);
        Function *inCountMth =
          u->getParent()->getParent()->getOrInsertFunction("llvm_first_trigger", cFty);

        assert(inCountMth && "Initialize method could not be inserted!");

        std::vector<Value *> iniArgs;
        iniArgs.push_back(countVar);
        Instruction *call = new CallInst(inCountMth, iniArgs, "");
        callTrigger->getInstList().push_back(call);
        callTrigger->getInstList().push_back(new BranchInst(BB));

        //now iterate over *vl, and set its Phi nodes right
        for(BasicBlock::iterator BB2Inst = BB->begin(), BBend = BB->end();
            BB2Inst != BBend; ++BB2Inst){

          if(PHINode *phiInst=dyn_cast<PHINode>(&*BB2Inst)){
            int bbIndex = phiInst->getBasicBlockIndex(u);
            if(bbIndex>=0){
              phiInst->setIncomingBlock(bbIndex, newBB);

              Value *val = phiInst->getIncomingValue((unsigned int)bbIndex);
              phiInst->addIncoming(val, callTrigger);
            }
          }
        }
      }
    }
  }
  color[u]=BLACK;//done with visiting the node and its neighbors
}

//getting the backedges in a graph
//Its a variation of DFS to get the backedges in the graph
//We get back edges by associating a time
//and a color with each vertex.
//The time of a vertex is the time when it was first visited
//The color of a vertex is initially WHITE,
//Changes to GREY when it is first visited,
//and changes to BLACK when ALL its neighbors
//have been visited
//So we have a back edge when we meet a successor of
//a node with smaller time, and GREY color
void getBackEdges(Function &F, Value *threshold){
  std::map<BasicBlock *, Color > color;
  std::map<BasicBlock *, int> d;
  int time=0;
  getBackEdgesVisit(F.begin(), color, d, time, threshold);
}

//Per function pass for inserting counters and call function
bool InstLoops::runOnFunction(Function &F){

  static GlobalVariable *threshold = NULL;
  static bool insertedThreshold = false;

   if(!insertedThreshold){
    threshold = new GlobalVariable(Type::IntTy, false, false, 0,
                                                   "reopt_threshold");

    F.getParent()->getGlobalList().push_back(threshold);
    insertedThreshold = true;
  }

  if(F.getName() == "main"){
    //intialize threshold
    std::vector<const Type*> initialize_args;
    initialize_args.push_back(PointerType::get(Type::IntTy));

    const FunctionType *Fty = FunctionType::get(Type::VoidTy, initialize_args,
                                                false);
    Function *initialMeth = F.getParent()->getOrInsertFunction("reoptimizerInitialize", Fty);
    assert(initialMeth && "Initialize method could not be inserted!");

    std::vector<Value *> trargs;
    trargs.push_back(threshold);

    new CallInst(initialMeth, trargs, "", F.begin()->begin());
  }

  assert(threshold && "GlobalVariable threshold not defined!");

  if(F.isExternal()) {
    return false;
  }

  getBackEdges(F, threshold);

  return true;
}
<|endoftext|>