<commit_before>#include "includes/SWidgets/SWebView.hpp"
#include "includes/SWidgets/STabWidget.hpp"
#include "includes/SMainWindow.hpp"

#include <QMessageBox>
#include <QVBoxLayout>

SWebView::SWebView(QWidget * parent, STabWidget *parentTab, QUrl url) :
	QWebEngineView(parent),
	m_parent(parent),
	m_parentTab(parentTab)
{
    connect(this->page(), &QWebEnginePage::fullScreenRequested, this, &SWebView::setFullScreen);

    load(url);
}

SWebView::~SWebView()
{
	// Empty
}

void SWebView::changeParent(QWidget * parent, STabWidget *parentTab)
{
	setParent(parent);
	m_parent = parent;
	m_parentTab = parentTab;
}

void SWebView::contextMenuEvent(QContextMenuEvent *event)
{
	// Get the action of current context menu
	QMenu *contextMenu{ page()->createStandardContextMenu() };

	// If the user right click on a link, we add the "open in new tab" action
	if (!page()->contextMenuData().linkUrl().isEmpty()) {
		contextMenu->insertAction(page()->action(QWebEnginePage::OpenLinkInThisWindow), page()->action(QWebEnginePage::OpenLinkInNewTab));
	}

	// Execute the context menu
	contextMenu->exec(event->globalPos());
}

SWebView * SWebView::createWindow(QWebEnginePage::WebWindowType type)
{
	// If we want to create a complet browser window
	if (type == QWebEnginePage::WebBrowserWindow) {
		SWebView *newView{ new SWebView(nullptr) };
		SMainWindow *newWindow{ new SMainWindow(nullptr, newView) };
		return newView;
	} // If we want to create a simple window with juste the web view
	else if (type == QWebEnginePage::WebDialog) {
		SWebView *newView{ new SWebView(nullptr) };
		newView->show();
		return newView;
	} // If we want to create a new tab, but no focused
	else if (type == QWebEnginePage::WebBrowserBackgroundTab) {
		SWebView *view{ new SWebView(nullptr, m_parentTab) };
		m_parentTab->createWebTab(tr("Nouvel onglet"), view);
		m_parentTab->createPlusTab();
		m_parentTab->removeTab(m_parentTab->count() - 3);
		return view;
	} // If we want to create a new tab
	else if (type == QWebEnginePage::WebBrowserTab) {
		SWebView *view{ new SWebView(nullptr, m_parentTab) };
		m_parentTab->createWebTab(tr("Nouvel onglet"), view);
		m_parentTab->createPlusTab();
		m_parentTab->removeTab(m_parentTab->count() - 3);
		m_parentTab->setCurrentIndex(m_parentTab->count() - 2);
		return view;
	}

	return nullptr;
}

void SWebView::setFullScreen(QWebEngineFullScreenRequest request)
{
	// If it's not in full screen
    if(!m_fullScreen) {
        setParent(nullptr);
        showFullScreen();
        m_parent->layout()->removeWidget(this);
        m_fullScreen = true;
    } // If it's already in full screen
    else {
        setParent(m_parent);
        show();
        m_parent->layout()->addWidget(this);
        m_fullScreen = false;
    }

    request.accept();
}
<commit_msg>Enable close request by some web site<commit_after>#include "includes/SWidgets/SWebView.hpp"
#include "includes/SWidgets/STabWidget.hpp"
#include "includes/SMainWindow.hpp"

#include <QMessageBox>
#include <QVBoxLayout>

SWebView::SWebView(QWidget * parent, STabWidget *parentTab, QUrl url) :
	QWebEngineView(parent),
	m_parent(parent),
	m_parentTab(parentTab)
{
    connect(this->page(), &QWebEnginePage::fullScreenRequested, this, &SWebView::setFullScreen);

	if (parentTab == nullptr)
		connect(this->page(), &QWebEnginePage::windowCloseRequested, this, &SWebView::close);

    load(url);
}

SWebView::~SWebView()
{
	// Empty
}

void SWebView::changeParent(QWidget * parent, STabWidget *parentTab)
{
	setParent(parent);
	m_parent = parent;
	m_parentTab = parentTab;
}

void SWebView::contextMenuEvent(QContextMenuEvent *event)
{
	// Get the action of current context menu
	QMenu *contextMenu{ page()->createStandardContextMenu() };

	// If the user right click on a link, we add the "open in new tab" action
	if (!page()->contextMenuData().linkUrl().isEmpty()) {
		contextMenu->insertAction(page()->action(QWebEnginePage::OpenLinkInThisWindow), page()->action(QWebEnginePage::OpenLinkInNewTab));
	}

	// Execute the context menu
	contextMenu->exec(event->globalPos());
}

SWebView * SWebView::createWindow(QWebEnginePage::WebWindowType type)
{
	// If we want to create a complet browser window
	if (type == QWebEnginePage::WebBrowserWindow) {
		SWebView *newView{ new SWebView(nullptr) };
		SMainWindow *newWindow{ new SMainWindow(nullptr, newView) };
		return newView;
	} // If we want to create a simple window with juste the web view
	else if (type == QWebEnginePage::WebDialog) {
		SWebView *newView{ new SWebView(nullptr) };
		newView->show();
		return newView;
	} // If we want to create a new tab, but no focused
	else if (type == QWebEnginePage::WebBrowserBackgroundTab) {
		SWebView *view{ new SWebView(nullptr, m_parentTab) };
		m_parentTab->createWebTab(tr("Nouvel onglet"), view);
		m_parentTab->createPlusTab();
		m_parentTab->removeTab(m_parentTab->count() - 3);
		return view;
	} // If we want to create a new tab
	else if (type == QWebEnginePage::WebBrowserTab) {
		SWebView *view{ new SWebView(nullptr, m_parentTab) };
		m_parentTab->createWebTab(tr("Nouvel onglet"), view);
		m_parentTab->createPlusTab();
		m_parentTab->removeTab(m_parentTab->count() - 3);
		m_parentTab->setCurrentIndex(m_parentTab->count() - 2);
		return view;
	}

	return nullptr;
}

void SWebView::setFullScreen(QWebEngineFullScreenRequest request)
{
	// If it's not in full screen
    if(!m_fullScreen) {
        setParent(nullptr);
        showFullScreen();
        m_parent->layout()->removeWidget(this);
        m_fullScreen = true;
    } // If it's already in full screen
    else {
        setParent(m_parent);
        show();
        m_parent->layout()->addWidget(this);
        m_fullScreen = false;
    }

    request.accept();
}
<|endoftext|>


<commit_before>#include "SequenceRowEditor.h"
#include "SequenceRow.h"
#include "Sequence.h"
#include "Song.h"
#include "EditorState.h"
#include "Renderer.h"
#include "Color.h"

SequenceRowEditor::SequenceRowEditor(EditorState& editorState, Song& song)
	: ColumnEditor(editorState, editorState.sequenceEditor, SequenceRow::maxTracks, 2), mSong(song)
{
	mTrackEditorState.currentRow.addListener(this);
	mTrackEditorState.currentColumn.addListener(this);
	mTrackEditorState.currentTrack.addListener(this);
}

SequenceRowEditor::~SequenceRowEditor()
{
}

void SequenceRowEditor::insertRow(bool allTracks, int flags)
{
	mSong.getSequence().insertRow(mTrackEditorState.currentRow, allTracks);

	if (mSong.getSequenceLength() < Song::maxSequenceRows)
		mSong.setSequenceLength(mSong.getSequenceLength() + 1);

	mTrackEditorState.currentRow.notify();
}

void SequenceRowEditor::deleteRow(bool allTracks, int flags)
{
	mSong.getSequence().deleteRow(mTrackEditorState.currentRow, allTracks);

	if (mSong.getSequenceLength() > 1)
		mSong.setSequenceLength(mSong.getSequenceLength() - 1);

	if (mTrackEditorState.currentRow >= mSong.getSequenceLength())
	{
		mTrackEditorState.currentRow = mSong.getSequenceLength() - 1;
	}

	mTrackEditorState.currentRow.notify();
}

void SequenceRowEditor::emptyRow(bool allTracks, int flags)
{
	//mSong.getSequence().emptyRow(mEditorState.currentRow);
}

bool SequenceRowEditor::onEvent(SDL_Event& event)
{
	switch (event.type)
	{
		case SDL_KEYDOWN:

			switch (event.key.keysym.sym)
			{
				case SDLK_DOWN:
					scrollView(1, false);

					return true;
					break;

				case SDLK_UP:
					scrollView(-1, false);

					return true;
					break;

				case SDLK_LEFT:
					changeColumn(-1);
					return true;

				case SDLK_RIGHT:
					changeColumn(1);
					return true;

				case SDLK_HOME:
					mTrackEditorState.currentRow = 0;

					return true;
					break;

				case SDLK_END:
					mTrackEditorState.currentRow = mSong.getSequenceLength() - 1;

					return true;
					break;

				case SDLK_BACKSPACE:
					if (mTrackEditorState.currentRow == 0)
						break;
					scrollView(-1, false);
					deleteRow(false, 0);
					return true;
					break;

				case SDLK_DELETE:
					deleteRow(false, 0);
					return true;
					break;

				case SDLK_INSERT:
					insertRow(false, 0);
					return true;
					break;

				case SDLK_RETURN:
					/*if (mTrackEditorState.currentRow == mSong.getSequenceLength() - 1)
						break;*/
					insertRow(false, 0);

					scrollView(1, false);
					return true;
					break;

				default:
				{
					if (event.key.keysym.mod & KMOD_CTRL)
					{
						if (event.key.keysym.sym == SDLK_d)
						{
							duplicateRow();
							return true;
						}

						break;
					}

					if (!mEditorState.editMode)
						break;

					SequenceRow& sequenceRow = mSong.getSequence().getRow(mTrackEditorState.currentRow);

					int hex = getHexFromKey(event.key.keysym);
					if (hex != -1)
					{
						int& pattern = sequenceRow.pattern[mTrackEditorState.currentTrack];

						if (mTrackEditorState.currentColumn == 0)
						{
							pattern = (pattern & 0x0f) | (hex << 4);
						}
						else
						{
							pattern = (pattern & 0xf0) | hex;
						}

						scrollView(1, false);

						return true;
					}
				}
					break;

			}
			break;

#ifdef SDL_GameControllerFromInstanceID
			case SDL_CONTROLLERBUTTONDOWN:
			{
				bool aPressed = SDL_GameControllerGetButton(SDL_GameControllerFromInstanceID(event.cbutton.which), SDL_CONTROLLER_BUTTON_A);
				SequenceRow& sequenceRow = mSong.getSequence().getRow(mTrackEditorState.currentRow);

				switch (event.cbutton.button)
				{
					case SDL_CONTROLLER_BUTTON_DPAD_LEFT:
					case SDL_CONTROLLER_BUTTON_DPAD_RIGHT:
						if (!aPressed)
						{
							changeColumn(event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_LEFT ? -1 : 1);
						}
						else
						{
							int& pattern = sequenceRow.pattern[mTrackEditorState.currentTrack];

							pattern = std::min(Song::maxPatterns - 1, std::max(0, pattern + (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_LEFT ? -1 : 1)));

							// We need to signal the listeners that the sequence has changed (i.e. tell PatternEditor to redraw)
							// Otherwise this is automatically caused by scrollView() when typing in numbers
							mTrackEditorState.currentRow.notify();
						}

						break;

					case SDL_CONTROLLER_BUTTON_DPAD_UP:
					case SDL_CONTROLLER_BUTTON_DPAD_DOWN:
						if (!aPressed)
						{
							scrollView(event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_UP ? -1 : 1);
						}
						else
						{
							int& pattern = sequenceRow.pattern[mTrackEditorState.currentTrack];

							pattern = std::min(Song::maxPatterns - 1, std::max(0, pattern + (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_DOWN ? -16 : 16)));

							// We need to signal the listeners that the sequence has changed (i.e. tell PatternEditor to redraw)
							// Otherwise this is automatically caused by scrollView() when typing in numbers
							mTrackEditorState.currentRow.notify();
						}

						break;
				}
				break;
			}
#endif
	}
	return false;
}

void SequenceRowEditor::onDraw(Renderer& renderer, const SDL_Rect& area)
{
	setDirty(false);

	renderer.renderBackground(area);

	int rowNumberWidth = 2 * 8 + 2;
	int trackWidth = 8 * 2;
	int rowHeight = 8;

	int countVisible = area.h / 8;
	int firstVisible = mTrackEditorState.currentRow - countVisible / 2;
	int lastVisible = mTrackEditorState.currentRow + countVisible / 2;

	int centerY = (area.h / 2) & ~7;

	if (firstVisible < 0)
		firstVisible = 0;

	if (lastVisible >= mSong.getSequenceLength())
		lastVisible = mSong.getSequenceLength() - 1;

	if (hasFocus())
	{
		int columnWidth = 8;

		int columnX = 8 * mTrackEditorState.currentColumn;

		SDL_Rect textArea = {mTrackEditorState.currentTrack * trackWidth + area.x + rowNumberWidth + columnX, area.y + centerY, columnWidth, rowHeight};
		renderer.renderRect(textArea, Color::getColor(mEditorState.editMode ? Color::ColorType::EditCursor : Color::ColorType::NonEditCursor));
	}

	for (int row = firstVisible ; row <= lastVisible ; ++row)
	{
		SDL_Rect textArea = {area.x, (row - mTrackEditorState.currentRow) * rowHeight + area.y + centerY, trackWidth, rowHeight};
		Color color = Color::getColor(Color::ColorType::RowCounter);

		if (row == mTrackEditorState.currentRow)
			color = Color(0,0,0);

		renderer.renderTextV(textArea, color, "%02d", row);
	}

	for (int row = firstVisible ; row <= lastVisible ; ++row)
	{
		SequenceRow& sequenceRow = mSong.getSequence().getRow(row);
		for (int track = 0 ; track < SequenceRow::maxTracks ; ++track)
		{
			SDL_Rect textArea = {track * trackWidth + area.x + rowNumberWidth, (row - mTrackEditorState.currentRow) * rowHeight + area.y + centerY, trackWidth, rowHeight};

			Color color;

			if (row == mTrackEditorState.currentRow)
				color = Color(0,0,0);

			renderer.renderTextV(textArea, color, "%02x", sequenceRow.pattern[track]);
		}
	}
}

void SequenceRowEditor::duplicateRow()
{
	if (mTrackEditorState.currentRow >= Sequence::maxRows && mSong.getSequenceLength() < Song::maxSequenceRows)
		return;

	mSong.getSequence().insertRow(mTrackEditorState.currentRow, true);

	SequenceRow& destination = mSong.getSequence().getRow(mTrackEditorState.currentRow);
	SequenceRow& source = mSong.getSequence().getRow(mTrackEditorState.currentRow + 1);

	for (int track = 0 ; track < SequenceRow::maxTracks ; ++track)
	{
		destination.pattern[track] = source.pattern[track];
	}

	mSong.setSequenceLength(mSong.getSequenceLength() + 1);

	mTrackEditorState.currentRow.notify();

	showMessage(MessageInfo, "Duplicated sequence row");
}
<commit_msg>Sequence editor did not use margins from theme file<commit_after>#include "SequenceRowEditor.h"
#include "SequenceRow.h"
#include "Sequence.h"
#include "Song.h"
#include "EditorState.h"
#include "Renderer.h"
#include "Color.h"

SequenceRowEditor::SequenceRowEditor(EditorState& editorState, Song& song)
	: ColumnEditor(editorState, editorState.sequenceEditor, SequenceRow::maxTracks, 2), mSong(song)
{
	mTrackEditorState.currentRow.addListener(this);
	mTrackEditorState.currentColumn.addListener(this);
	mTrackEditorState.currentTrack.addListener(this);
}

SequenceRowEditor::~SequenceRowEditor()
{
}

void SequenceRowEditor::insertRow(bool allTracks, int flags)
{
	mSong.getSequence().insertRow(mTrackEditorState.currentRow, allTracks);

	if (mSong.getSequenceLength() < Song::maxSequenceRows)
		mSong.setSequenceLength(mSong.getSequenceLength() + 1);

	mTrackEditorState.currentRow.notify();
}

void SequenceRowEditor::deleteRow(bool allTracks, int flags)
{
	mSong.getSequence().deleteRow(mTrackEditorState.currentRow, allTracks);

	if (mSong.getSequenceLength() > 1)
		mSong.setSequenceLength(mSong.getSequenceLength() - 1);

	if (mTrackEditorState.currentRow >= mSong.getSequenceLength())
	{
		mTrackEditorState.currentRow = mSong.getSequenceLength() - 1;
	}

	mTrackEditorState.currentRow.notify();
}

void SequenceRowEditor::emptyRow(bool allTracks, int flags)
{
	//mSong.getSequence().emptyRow(mEditorState.currentRow);
}

bool SequenceRowEditor::onEvent(SDL_Event& event)
{
	switch (event.type)
	{
		case SDL_KEYDOWN:

			switch (event.key.keysym.sym)
			{
				case SDLK_DOWN:
					scrollView(1, false);

					return true;
					break;

				case SDLK_UP:
					scrollView(-1, false);

					return true;
					break;

				case SDLK_LEFT:
					changeColumn(-1);
					return true;

				case SDLK_RIGHT:
					changeColumn(1);
					return true;

				case SDLK_HOME:
					mTrackEditorState.currentRow = 0;

					return true;
					break;

				case SDLK_END:
					mTrackEditorState.currentRow = mSong.getSequenceLength() - 1;

					return true;
					break;

				case SDLK_BACKSPACE:
					if (mTrackEditorState.currentRow == 0)
						break;
					scrollView(-1, false);
					deleteRow(false, 0);
					return true;
					break;

				case SDLK_DELETE:
					deleteRow(false, 0);
					return true;
					break;

				case SDLK_INSERT:
					insertRow(false, 0);
					return true;
					break;

				case SDLK_RETURN:
					/*if (mTrackEditorState.currentRow == mSong.getSequenceLength() - 1)
						break;*/
					insertRow(false, 0);

					scrollView(1, false);
					return true;
					break;

				default:
				{
					if (event.key.keysym.mod & KMOD_CTRL)
					{
						if (event.key.keysym.sym == SDLK_d)
						{
							duplicateRow();
							return true;
						}

						break;
					}

					if (!mEditorState.editMode)
						break;

					SequenceRow& sequenceRow = mSong.getSequence().getRow(mTrackEditorState.currentRow);

					int hex = getHexFromKey(event.key.keysym);
					if (hex != -1)
					{
						int& pattern = sequenceRow.pattern[mTrackEditorState.currentTrack];

						if (mTrackEditorState.currentColumn == 0)
						{
							pattern = (pattern & 0x0f) | (hex << 4);
						}
						else
						{
							pattern = (pattern & 0xf0) | hex;
						}

						scrollView(1, false);

						return true;
					}
				}
					break;

			}
			break;

#ifdef SDL_GameControllerFromInstanceID
			case SDL_CONTROLLERBUTTONDOWN:
			{
				bool aPressed = SDL_GameControllerGetButton(SDL_GameControllerFromInstanceID(event.cbutton.which), SDL_CONTROLLER_BUTTON_A);
				SequenceRow& sequenceRow = mSong.getSequence().getRow(mTrackEditorState.currentRow);

				switch (event.cbutton.button)
				{
					case SDL_CONTROLLER_BUTTON_DPAD_LEFT:
					case SDL_CONTROLLER_BUTTON_DPAD_RIGHT:
						if (!aPressed)
						{
							changeColumn(event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_LEFT ? -1 : 1);
						}
						else
						{
							int& pattern = sequenceRow.pattern[mTrackEditorState.currentTrack];

							pattern = std::min(Song::maxPatterns - 1, std::max(0, pattern + (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_LEFT ? -1 : 1)));

							// We need to signal the listeners that the sequence has changed (i.e. tell PatternEditor to redraw)
							// Otherwise this is automatically caused by scrollView() when typing in numbers
							mTrackEditorState.currentRow.notify();
						}

						break;

					case SDL_CONTROLLER_BUTTON_DPAD_UP:
					case SDL_CONTROLLER_BUTTON_DPAD_DOWN:
						if (!aPressed)
						{
							scrollView(event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_UP ? -1 : 1);
						}
						else
						{
							int& pattern = sequenceRow.pattern[mTrackEditorState.currentTrack];

							pattern = std::min(Song::maxPatterns - 1, std::max(0, pattern + (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_DOWN ? -16 : 16)));

							// We need to signal the listeners that the sequence has changed (i.e. tell PatternEditor to redraw)
							// Otherwise this is automatically caused by scrollView() when typing in numbers
							mTrackEditorState.currentRow.notify();
						}

						break;
				}
				break;
			}
#endif
	}
	return false;
}

void SequenceRowEditor::onDraw(Renderer& renderer, const SDL_Rect& area)
{
	setDirty(false);

	renderer.renderBackground(area);

	int rowNumberWidth = 2 * renderer.getFontWidth() + mRowNumberMargin;
	int trackWidth = 2 * renderer.getFontWidth() + mTrackMargin;
	int rowHeight = renderer.getFontHeight();

	int countVisible = area.h / 8;
	int firstVisible = mTrackEditorState.currentRow - countVisible / 2;
	int lastVisible = mTrackEditorState.currentRow + countVisible / 2;

	int centerY = (area.h / 2) & ~7;

	if (firstVisible < 0)
		firstVisible = 0;

	if (lastVisible >= mSong.getSequenceLength())
		lastVisible = mSong.getSequenceLength() - 1;

	if (hasFocus())
	{
		int columnWidth = 8;

		int columnX = 8 * mTrackEditorState.currentColumn;

		SDL_Rect textArea = {mTrackEditorState.currentTrack * trackWidth + area.x + rowNumberWidth + columnX, area.y + centerY, columnWidth, rowHeight};
		renderer.renderRect(textArea, Color::getColor(mEditorState.editMode ? Color::ColorType::EditCursor : Color::ColorType::NonEditCursor));
	}

	for (int row = firstVisible ; row <= lastVisible ; ++row)
	{
		SDL_Rect textArea = {area.x, (row - mTrackEditorState.currentRow) * rowHeight + area.y + centerY, trackWidth, rowHeight};
		Color color = Color::getColor(Color::ColorType::RowCounter);

		if (row == mTrackEditorState.currentRow)
			color = Color(0,0,0);

		renderer.renderTextV(textArea, color, "%02d", row);
	}

	for (int row = firstVisible ; row <= lastVisible ; ++row)
	{
		SequenceRow& sequenceRow = mSong.getSequence().getRow(row);
		for (int track = 0 ; track < SequenceRow::maxTracks ; ++track)
		{
			SDL_Rect textArea = {track * trackWidth + area.x + rowNumberWidth, (row - mTrackEditorState.currentRow) * rowHeight + area.y + centerY, trackWidth, rowHeight};

			Color color;

			if (row == mTrackEditorState.currentRow)
				color = Color(0,0,0);

			renderer.renderTextV(textArea, color, "%02x", sequenceRow.pattern[track]);
		}
	}
}

void SequenceRowEditor::duplicateRow()
{
	if (mTrackEditorState.currentRow >= Sequence::maxRows && mSong.getSequenceLength() < Song::maxSequenceRows)
		return;

	mSong.getSequence().insertRow(mTrackEditorState.currentRow, true);

	SequenceRow& destination = mSong.getSequence().getRow(mTrackEditorState.currentRow);
	SequenceRow& source = mSong.getSequence().getRow(mTrackEditorState.currentRow + 1);

	for (int track = 0 ; track < SequenceRow::maxTracks ; ++track)
	{
		destination.pattern[track] = source.pattern[track];
	}

	mSong.setSequenceLength(mSong.getSequenceLength() + 1);

	mTrackEditorState.currentRow.notify();

	showMessage(MessageInfo, "Duplicated sequence row");
}
<|endoftext|>


<commit_before>#include "clock.h"
#include <iomanip>
#include <sstream>

using namespace std;

namespace date_independent
{

clock& clock::plus(int minutes)
{
    minute_ += minutes;
    if (minute_ > 60) {
        hour_ += (minute_/60);
        hour_ %= 24;
        minute_ %= 60;
    }
    return *this;
}

clock& clock::minus(int minutes)
{
    minute_ -= minutes;
    while (minute_ < 0) {
        --hour_;
        minute_ += 60;
    }
    while (hour_ < 0) {
        hour_ += 24;
    }
    return *this;
}

clock::operator string() const
{
    ostringstream str;
    str << setw(2) << setfill('0') << hour_ << ':' << setw(2) << setfill('0') << minute_;
    return str.str();
}

clock::clock(int hour, int minute)
    : hour_(hour),
    minute_(minute)
{
}

clock clock::at(int hour, int minute /*= 0*/)
{
    return clock(hour, minute);
}

bool clock::operator==(const clock& rhs) const
{
    return hour_ == rhs.hour_
        && minute_ == rhs.minute_;
}

}
<commit_msg>Refactor: Extract Named Constant<commit_after>#include "clock.h"
#include <iomanip>
#include <sstream>

using namespace std;

namespace
{

const int minutes_per_hour = 60;
const int hours_per_day = 24;

}

namespace date_independent
{

clock& clock::plus(int minutes)
{
    minute_ += minutes;
    if (minute_ > minutes_per_hour) {
        hour_ += (minute_/minutes_per_hour);
        hour_ %= hours_per_day;
        minute_ %= minutes_per_hour;
    }
    return *this;
}

clock& clock::minus(int minutes)
{
    minute_ -= minutes;
    while (minute_ < 0) {
        --hour_;
        minute_ += minutes_per_hour;
    }
    while (hour_ < 0) {
        hour_ += hours_per_day;
    }
    return *this;
}

clock::operator string() const
{
    ostringstream str;
    str << setw(2) << setfill('0') << hour_ << ':' << setw(2) << setfill('0') << minute_;
    return str.str();
}

clock::clock(int hour, int minute)
    : hour_(hour),
    minute_(minute)
{
}

clock clock::at(int hour, int minute /*= 0*/)
{
    return clock(hour, minute);
}

bool clock::operator==(const clock& rhs) const
{
    return hour_ == rhs.hour_
        && minute_ == rhs.minute_;
}

}
<|endoftext|>


<commit_before>// -*- C++ -*-
//----------------------------------------------------------------------
//
//                          William S. Klug
//                           Luigi Perotti
//                University of California Los Angeles
//                   (C) 2004 All Rights Reserved
//
//----------------------------------------------------------------------
//
// $Log$
// Revision 1.2  2005/06/27 04:04:36  klug
// *** empty log message ***
//
// Revision 1.1  2005/05/23 18:05:35  klug
// Initial checkin.
//
//----------------------------------------------------------------------

#include "KMCprotein.h"

namespace voom {

  // KMC protein algorithm
  void KMCprotein::solve(uint ComputeNeighInterval, double Rsearch)
  {
    stringstream OutputFileStream;
    OutputFileStream << "MC_uAVG_" << 0 << ".dat";
    string OutputFileName = OutputFileStream.str();
    ofstream ofsE;
    if ( _Tsched == STEPWISE )
    {
      ofsE.open(OutputFileName.c_str());
      if (!ofsE) { std::cout << "Cannot open output file " << OutputFileStream << std::endl;
	exit(0); }
    }

    _body->compute(true, false, false);
    _fSaved = _body->energy();
    std::cout << "Initial energy = " << _fSaved << std::endl;

    double fBest = _fSaved;
    double fWorst = _fSaved;

    // Temperature
    _T1 = _T01;
    _T2 = _T02;

    // sched == EXPONENTIAL
    double alpha = pow( _FinalTratio, 1.0/_nSteps );

    // sched == LINEAR
    double alpha1 = _T01/_nSteps;
    double alpha2 = _T02/_nSteps;

    // Print initial configuration
    _printProtein->printMaster(0, 1);

    // Begin simulated annealing
    unsigned accepted = 0, step = 1, pt = 0, j = 0;
    unsigned int StepPerInterval = 0, Interval = 0;
    vector<DeformationNode<3>::Point > OriginalLocations;
    unsigned int adjust = 0;
    ProteinPotential * Mat = _body->getPotential();
    // std::uniform_real_distribution<double> RealDistribution(0.0, 1.0); // does not include 1.0
    for(pt = 0; pt < _proteinsSize; pt++)
    {
      OriginalLocations.push_back((_proteins[pt]->getHost())->point());
    }

    StepPerInterval = _nSteps/_NT;
    for(step = 1; step <= _nSteps; step++)
    {
      // Compute particles rates in isolation
      this->computeRates();
      // Compute Rmax
      this->computeRmax();

      if (_method == 0) { // Klug MC
	for (int i = 0; i < _proteinsSize; i++) {
	  // p = _randGenerator(RealDistribution);
	  double p = double(rand())/double(RAND_MAX);
	  if (p < _rates[i]) { // accept move
	    _proteins[i]->setHost(_tempHosts[i]);
	    accepted++;
	  }
	} // loop over all proteins
      } // method 0
      else if (_method == 1) { // KMC adapting Jaime Mariam idea for parallel KMC
	for (int i = 0; i < _proteinsSize; i++) {
	  double r_i = _rates[i]/_rmax;
	  // p = _randGenerator(RealDistribution);
	  double p = double(rand())/double(RAND_MAX);
	  if (p < r_i || r_i > 1.0-1.0e-16) { // accept move
	    _proteins[i]->setHost(_tempHosts[i]);
	    accepted++;
	  }
	} // loop over all proteins
      } // method 1
      // Update time - correct only for method 1
      double xi = double(rand())/double(RAND_MAX);
      double DeltaTime = -log(xi)/_rmax; // Needed to print following warning
      _time += DeltaTime;
      if ( DeltaTime > 100) { // 100 is an arbitrary number to trigger a warning in the output file - just for debugging
	cout << "DeltaTime = " << DeltaTime << " ; xi = " << xi <<  " ; rmax = " << _rmax << endl;
      }
      _approxTime += 1.0/_rmax;

      // Compute body energy
      _body->compute(true, false, false);
      _fSaved = _body->energy();

      if( _fSaved < fBest ) { fBest  = _fSaved; }
      if( _fSaved > fWorst) { fWorst = _fSaved; }

      if ( _Tsched == STEPWISE) {
	// Print uAvgSq at each step
	ofsE << _time << " " <<  this->ComputeUavgSquare(OriginalLocations) << std::endl;
      }

      // Print values of interest (energy, acceptance, Ravg)
      std::cout << "MTS iteration = " << step        << std::endl
		<< "accepted      = " << accepted    << std::endl
		<< "_fSaved       = " << _fSaved     << std::endl
		<< "fBest         = " << fBest       << std::endl
		<< "fWorst        = " << fWorst      << std::endl
		<< "Temperature   = " << _T1         << std::endl
		<< "time          = " << _time       << std::endl
		<< "approxTime    = " << _approxTime << std::endl;

      // Print current configuration
      if (step%_printEvery == 0) {
	_printProtein->printMaster(int(step/_printEvery), 0);
      }

      // Recompute Neighbors
      if (step%ComputeNeighInterval == 0) {
	_body->recomputeNeighbors(Rsearch);
      }

      // Lower temperature for next MC iteration
      switch( _Tsched )
      {
      case CONSTANT:
	_T1 = _T01; // it is useless to set it again to T01
	_T2 = _T02; // it is useless to set it again to T02
	break;
      case LINEAR:
	_T1 -= alpha1;
	_T2 -= alpha2;
	break;
      case FAST:
	_T1 = _T01/(1+step);
	_T2 = _T02/(1+step);
	break;
      case EXPONENTIAL:
	_T1 *= alpha;
	_T2 *= alpha;
	break;
      case STEPWISE:
	if (step >= StepPerInterval*(Interval+1))
	{
	  _T1 += (_T02-_T01)/double(_NT-1);
	  Interval++;
	  ofsE.close();
	  OutputFileStream.str(string());
	  OutputFileStream << "MC_uAVG_" << Interval << ".dat";
	  OutputFileName = OutputFileStream.str();
	  ofsE.open(OutputFileName.c_str());
	  if (!ofsE) {
	    std::cout << "Cannot open output file " << OutputFileStream << std::endl;
	    exit(0);
	  }
	  // Prepare for computing average u square at next temperature
	  for(pt = 0; pt < _proteinsSize; pt++)
	  {
	    OriginalLocations[pt] = (_proteins[pt]->getHost())->point();
	  }
	  // Reset time to zero
	  _time = 0.0;
	  _approxTime = 0.0;
	}
	break;
      } // switch

    } // End of simulating annealing loop

    if (_Tsched == STEPWISE) {
      ofsE.close();
    }

    std::cout << "KMCprotein annealing done :) " << std::endl;
  }

// --------------------------------------------------------------
// Compute a new random trial state based on chosen distribution
// --------------------------------------------------------------
  void KMCprotein::computeRates()
  {
    for (int i = 0; i < _proteinsSize; i++)
    {
      ProteinNode * A = _proteins[i];
      DeformationNode<3> * hostA = A->getHost();

      vector<DeformationNode<3> *> NewHosts = _possibleHosts[hostA];
      // std::uniform_int_distribution<int> IntDistribution(0, NewHosts.size()-1);
      // uint j = IntDistribution(generator);
      uint j = rand()%NewHosts.size();
      A->setHost(NewHosts[j]);
      _tempHosts[i] = NewHosts[j]; // If this move is later kept, need to remember where protein went

      // Compute body energy
      _body->compute(true, false, false);
      _rates[i] = exp( ( _fSaved - _body->energy())/_T1 );
      A->setHost(hostA); // return protein in position at the beginning of time step
    }

  } // computeRates

  double KMCprotein::ComputeUavgSquare(vector<DeformationNode<3>::Point > & OriginalLocations)
  {
    double uSQavg = 0.0;

    for(uint pt = 0; pt < _proteinsSize; pt++) {
      DeformationNode<3>::Point b = (_proteins[pt]->getHost())->point();
      uSQavg += pow(tvmet::norm2(OriginalLocations[pt]-b), 2.0);
    }

    uSQavg = uSQavg/double(_proteinsSize);

    return uSQavg;
  }

}  // namespace voom

<commit_msg>Same initial configuration for every KMC melting simulation<commit_after>// -*- C++ -*-
//----------------------------------------------------------------------
//
//                          William S. Klug
//                           Luigi Perotti
//                University of California Los Angeles
//                   (C) 2004 All Rights Reserved
//
//----------------------------------------------------------------------
//
// $Log$
// Revision 1.2  2005/06/27 04:04:36  klug
// *** empty log message ***
//
// Revision 1.1  2005/05/23 18:05:35  klug
// Initial checkin.
//
//----------------------------------------------------------------------

#include "KMCprotein.h"

namespace voom {

  // KMC protein algorithm
  void KMCprotein::solve(uint ComputeNeighInterval, double Rsearch)
  {
    stringstream OutputFileStream;
    OutputFileStream << "MC_uAVG_" << 0 << ".dat";
    string OutputFileName = OutputFileStream.str();
    ofstream ofsE;
    if ( _Tsched == STEPWISE )
    {
      ofsE.open(OutputFileName.c_str());
      if (!ofsE) { std::cout << "Cannot open output file " << OutputFileStream << std::endl;
	exit(0); }
    }

    _body->compute(true, false, false);
    _fSaved = _body->energy();
    std::cout << "Initial energy = " << _fSaved << std::endl;

    double fBest = _fSaved;
    double fWorst = _fSaved;

    // Temperature
    _T1 = _T01;
    _T2 = _T02;

    // sched == EXPONENTIAL
    double alpha = pow( _FinalTratio, 1.0/_nSteps );

    // sched == LINEAR
    double alpha1 = _T01/_nSteps;
    double alpha2 = _T02/_nSteps;

    // Print initial configuration
    _printProtein->printMaster(0, 1);

    // Begin simulated annealing
    unsigned accepted = 0, step = 1, pt = 0, j = 0;
    unsigned int StepPerInterval = 0, Interval = 0;
    vector<DeformationNode<3>::Point > OriginalLocations;
    vector<DeformationNode<3>* > OriginalHost;
    unsigned int adjust = 0;
    ProteinPotential * Mat = _body->getPotential();
    // std::uniform_real_distribution<double> RealDistribution(0.0, 1.0); // does not include 1.0
    for(pt = 0; pt < _proteinsSize; pt++)
    {
      OriginalLocations.push_back((_proteins[pt]->getHost())->point());
      OriginalHost.push_back( _proteins[pt]->getHost() );
    }

    StepPerInterval = _nSteps/_NT;
    for(step = 1; step <= _nSteps; step++)
    {
      // Compute particles rates in isolation
      this->computeRates();
      // Compute Rmax
      this->computeRmax();

      if (_method == 0) { // Klug MC
	for (int i = 0; i < _proteinsSize; i++) {
	  // p = _randGenerator(RealDistribution);
	  double p = double(rand())/double(RAND_MAX);
	  if (p < _rates[i]) { // accept move
	    _proteins[i]->setHost(_tempHosts[i]);
	    accepted++;
	  }
	} // loop over all proteins
      } // method 0
      else if (_method == 1) { // KMC adapting Jaime Mariam idea for parallel KMC
	for (int i = 0; i < _proteinsSize; i++) {
	  double r_i = _rates[i]/_rmax;
	  // p = _randGenerator(RealDistribution);
	  double p = double(rand())/double(RAND_MAX);
	  if (p < r_i || r_i > 1.0-1.0e-16) { // accept move
	    _proteins[i]->setHost(_tempHosts[i]);
	    accepted++;
	  }
	} // loop over all proteins
      } // method 1
      // Update time - correct only for method 1
      double xi = double(rand())/double(RAND_MAX);
      double DeltaTime = -log(xi)/_rmax; // Needed to print following warning
      _time += DeltaTime;
      if ( DeltaTime > 100) { // 100 is an arbitrary number to trigger a warning in the output file - just for debugging
	cout << "DeltaTime = " << DeltaTime << " ; xi = " << xi <<  " ; rmax = " << _rmax << endl;
      }
      _approxTime += 1.0/_rmax;

      // Compute body energy
      _body->compute(true, false, false);
      _fSaved = _body->energy();

      if( _fSaved < fBest ) { fBest  = _fSaved; }
      if( _fSaved > fWorst) { fWorst = _fSaved; }

      if ( _Tsched == STEPWISE) {
	// Print uAvgSq at each step
	ofsE << _time << " " <<  this->ComputeUavgSquare(OriginalLocations) << std::endl;
      }

      // Print values of interest (energy, acceptance, Ravg)
      std::cout << "MTS iteration = " << step        << std::endl
		<< "accepted      = " << accepted    << std::endl
		<< "_fSaved       = " << _fSaved     << std::endl
		<< "fBest         = " << fBest       << std::endl
		<< "fWorst        = " << fWorst      << std::endl
		<< "Temperature   = " << _T1         << std::endl
		<< "time          = " << _time       << std::endl
		<< "approxTime    = " << _approxTime << std::endl;

      // Print current configuration
      if (step%_printEvery == 0) {
	_printProtein->printMaster(int(step/_printEvery), 0);
      }

      // Recompute Neighbors
      if (step%ComputeNeighInterval == 0) {
	_body->recomputeNeighbors(Rsearch);
      }

      // Lower temperature for next MC iteration
      switch( _Tsched )
      {
      case CONSTANT:
	_T1 = _T01; // it is useless to set it again to T01
	_T2 = _T02; // it is useless to set it again to T02
	break;
      case LINEAR:
	_T1 -= alpha1;
	_T2 -= alpha2;
	break;
      case FAST:
	_T1 = _T01/(1+step);
	_T2 = _T02/(1+step);
	break;
      case EXPONENTIAL:
	_T1 *= alpha;
	_T2 *= alpha;
	break;
      case STEPWISE:
	if (step >= StepPerInterval*(Interval+1))
	{
	  _T1 += (_T02-_T01)/double(_NT-1);
	  Interval++;
	  ofsE.close();
	  OutputFileStream.str(string());
	  OutputFileStream << "MC_uAVG_" << Interval << ".dat";
	  OutputFileName = OutputFileStream.str();
	  ofsE.open(OutputFileName.c_str());
	  if (!ofsE) {
	    std::cout << "Cannot open output file " << OutputFileStream << std::endl;
	    exit(0);
	  }
	  // Prepare for computing average u square at next temperature or reset proteins to original location
	  for(pt = 0; pt < _proteinsSize; pt++)
	  {
	    // If we do not want to change the original locations then
	    _proteins[pt]->setHost(OriginalHost[pt]);
	    // Otherwise ...
	    // OriginalLocations[pt] = (_proteins[pt]->getHost())->point();
	  }
	  // Reset time to zero
	  _time = 0.0;
	  _approxTime = 0.0;
	}
	break;
      } // switch

    } // End of simulating annealing loop

    if (_Tsched == STEPWISE) {
      ofsE.close();
    }

    std::cout << "KMCprotein annealing done :) " << std::endl;
  }

// --------------------------------------------------------------
// Compute a new random trial state based on chosen distribution
// --------------------------------------------------------------
  void KMCprotein::computeRates()
  {
    for (int i = 0; i < _proteinsSize; i++)
    {
      ProteinNode * A = _proteins[i];
      DeformationNode<3> * hostA = A->getHost();

      vector<DeformationNode<3> *> NewHosts = _possibleHosts[hostA];
      // std::uniform_int_distribution<int> IntDistribution(0, NewHosts.size()-1);
      // uint j = IntDistribution(generator);
      uint j = rand()%NewHosts.size();
      A->setHost(NewHosts[j]);
      _tempHosts[i] = NewHosts[j]; // If this move is later kept, need to remember where protein went

      // Compute body energy
      _body->compute(true, false, false);
      _rates[i] = exp( ( _fSaved - _body->energy())/_T1 );
      A->setHost(hostA); // return protein in position at the beginning of time step
    }

  } // computeRates

  double KMCprotein::ComputeUavgSquare(vector<DeformationNode<3>::Point > & OriginalLocations)
  {
    double uSQavg = 0.0;

    for(uint pt = 0; pt < _proteinsSize; pt++) {
      DeformationNode<3>::Point b = (_proteins[pt]->getHost())->point();
      uSQavg += pow(tvmet::norm2(OriginalLocations[pt]-b), 2.0);
    }

    uSQavg = uSQavg/double(_proteinsSize);

    return uSQavg;
  }

}  // namespace voom

<|endoftext|>


<commit_before>#include "BMP085.h"

namespace touch_develop {
namespace bmp085 {

  using namespace ::touch_develop::i2c;

  I2CSimple i2c(0x77);

  uint8_t _bmp085Mode;
  bmp085_calib_data _bmp085_coeffs;

  void readCoefficients() {
#if BMP085_USE_DATASHEET_VALS
      _bmp085_coeffs.ac1 = 408;
      _bmp085_coeffs.ac2 = -72;
      _bmp085_coeffs.ac3 = -14383;
      _bmp085_coeffs.ac4 = 32741;
      _bmp085_coeffs.ac5 = 32757;
      _bmp085_coeffs.ac6 = 23153;
      _bmp085_coeffs.b1  = 6190;
      _bmp085_coeffs.b2  = 4;
      _bmp085_coeffs.mb  = -32768;
      _bmp085_coeffs.mc  = -8711;
      _bmp085_coeffs.md  = 2868;
      _bmp085Mode        = 0;
#else
      _bmp085_coeffs.ac1 = i2c.readS16(BMP085_REGISTER_CAL_AC1);
      _bmp085_coeffs.ac2 = i2c.readS16(BMP085_REGISTER_CAL_AC2);
      _bmp085_coeffs.ac3 = i2c.readS16(BMP085_REGISTER_CAL_AC3);
      _bmp085_coeffs.ac4 = i2c.read16(BMP085_REGISTER_CAL_AC4);
      _bmp085_coeffs.ac5 = i2c.read16(BMP085_REGISTER_CAL_AC5);
      _bmp085_coeffs.ac6 = i2c.read16(BMP085_REGISTER_CAL_AC6);
      _bmp085_coeffs.b1 = i2c.readS16(BMP085_REGISTER_CAL_B1);
      _bmp085_coeffs.b2 = i2c.readS16(BMP085_REGISTER_CAL_B2);
      _bmp085_coeffs.mb = i2c.readS16(BMP085_REGISTER_CAL_MB);
      _bmp085_coeffs.mc = i2c.readS16(BMP085_REGISTER_CAL_MC);
      _bmp085_coeffs.md = i2c.readS16(BMP085_REGISTER_CAL_MD);
#endif
  }

  void setMode(bmp085_mode_t mode) {
      _bmp085Mode = mode;
  }

  int readRawTemperature() {
#if BMP085_USE_DATASHEET_VALS
      return 27898;
#else
      i2c.write8(BMP085_REGISTER_CONTROL, BMP085_REGISTER_READTEMPCMD);
      wait_ms(5);
      return i2c.read16(BMP085_REGISTER_TEMPDATA);
#endif
  }

  int readRawPressure() {
#if BMP085_USE_DATASHEET_VALS
      return 23843;
#else
      uint8_t  p8;
      uint16_t p16;
      int32_t  p32;

      i2c.write8(BMP085_REGISTER_CONTROL, BMP085_REGISTER_READPRESSURECMD + (_bmp085Mode << 6));

      switch(_bmp085Mode)
      {
        case BMP085_MODE_ULTRALOWPOWER:
          wait_ms(5);
          break;
        case BMP085_MODE_STANDARD:
          wait_ms(8);
          break;
        case BMP085_MODE_HIGHRES:
          wait_ms(14);
          break;
        case BMP085_MODE_ULTRAHIGHRES:
        default:
          wait_ms(26);
          break;
      }

      p16 = i2c.read16(BMP085_REGISTER_PRESSUREDATA);
      p32 = (uint32_t)p16 << 8;
      p8 = i2c.read8(BMP085_REGISTER_PRESSUREDATA+2);
      p32 += p8;
      p32 >>= (8 - _bmp085Mode);
      return p32;
#endif
  }

  int32_t computeB5(int32_t ut) {
    int32_t X1 = (ut - (int32_t)_bmp085_coeffs.ac6) * ((int32_t)_bmp085_coeffs.ac5) >> 15;
    int32_t X2 = ((int32_t)_bmp085_coeffs.mc << 11) / (X1+(int32_t)_bmp085_coeffs.md);
    return X1 + X2;
  }

  void begin(bmp085_mode_t mode)
  {
    if (i2c.read8(BMP085_REGISTER_CHIPID) != 0x55)
      uBit.panic(TD_PERIPHERAL_ERROR);

    /* Set the mode indicator */
    _bmp085Mode = mode;

    /* Coefficients need to be read once */
    readCoefficients();
  }

  float getPressure()
  {
    int32_t  ut = 0, up = 0, compp = 0;
    int32_t  x1, x2, b5, b6, x3, b3, p;
    uint32_t b4, b7;

    /* Get the raw pressure and temperature values */
    ut = readRawTemperature();
    up = readRawPressure();

    /* Temperature compensation */
    b5 = computeB5(ut);

    /* Pressure compensation */
    b6 = b5 - 4000;
    x1 = (_bmp085_coeffs.b2 * ((b6 * b6) >> 12)) >> 11;
    x2 = (_bmp085_coeffs.ac2 * b6) >> 11;
    x3 = x1 + x2;
    b3 = (((((int32_t) _bmp085_coeffs.ac1) * 4 + x3) << _bmp085Mode) + 2) >> 2;
    x1 = (_bmp085_coeffs.ac3 * b6) >> 13;
    x2 = (_bmp085_coeffs.b1 * ((b6 * b6) >> 12)) >> 16;
    x3 = ((x1 + x2) + 2) >> 2;
    b4 = (_bmp085_coeffs.ac4 * (uint32_t) (x3 + 32768)) >> 15;
    b7 = ((uint32_t) (up - b3) * (50000 >> _bmp085Mode));

    if (b7 < 0x80000000)
    {
      p = (b7 << 1) / b4;
    }
    else
    {
      p = (b7 / b4) << 1;
    }

    x1 = (p >> 8) * (p >> 8);
    x1 = (x1 * 3038) >> 16;
    x2 = (-7357 * p) >> 16;
    compp = p + ((x1 + x2 + 3791) >> 4);

    /* Assign compensated pressure value */
    return compp;
  }

  float getTemperature()
  {
    int32_t UT, X1, X2, B5;     // following ds convention
    float t;

    UT = readRawTemperature();

#if BMP085_USE_DATASHEET_VALS
      // use datasheet numbers!
      UT = 27898;
      _bmp085_coeffs.ac6 = 23153;
      _bmp085_coeffs.ac5 = 32757;
      _bmp085_coeffs.mc = -8711;
      _bmp085_coeffs.md = 2868;
#endif

    B5 = computeB5(UT);
    t = (B5+8) >> 4;
    t /= 10;

    return t;
  }

  int getIntTemperature() {
      return ((int) getTemperature());
  }
} // namespace bmp085
} // namespace touch_develop
<commit_msg>Fix warning<commit_after>#include "BMP085.h"

namespace touch_develop {
namespace bmp085 {

  using namespace ::touch_develop::i2c;

  I2CSimple i2c(0x77);

  uint8_t _bmp085Mode;
  bmp085_calib_data _bmp085_coeffs;

  void readCoefficients() {
#if BMP085_USE_DATASHEET_VALS
      _bmp085_coeffs.ac1 = 408;
      _bmp085_coeffs.ac2 = -72;
      _bmp085_coeffs.ac3 = -14383;
      _bmp085_coeffs.ac4 = 32741;
      _bmp085_coeffs.ac5 = 32757;
      _bmp085_coeffs.ac6 = 23153;
      _bmp085_coeffs.b1  = 6190;
      _bmp085_coeffs.b2  = 4;
      _bmp085_coeffs.mb  = -32768;
      _bmp085_coeffs.mc  = -8711;
      _bmp085_coeffs.md  = 2868;
      _bmp085Mode        = 0;
#else
      _bmp085_coeffs.ac1 = i2c.readS16(BMP085_REGISTER_CAL_AC1);
      _bmp085_coeffs.ac2 = i2c.readS16(BMP085_REGISTER_CAL_AC2);
      _bmp085_coeffs.ac3 = i2c.readS16(BMP085_REGISTER_CAL_AC3);
      _bmp085_coeffs.ac4 = i2c.read16(BMP085_REGISTER_CAL_AC4);
      _bmp085_coeffs.ac5 = i2c.read16(BMP085_REGISTER_CAL_AC5);
      _bmp085_coeffs.ac6 = i2c.read16(BMP085_REGISTER_CAL_AC6);
      _bmp085_coeffs.b1 = i2c.readS16(BMP085_REGISTER_CAL_B1);
      _bmp085_coeffs.b2 = i2c.readS16(BMP085_REGISTER_CAL_B2);
      _bmp085_coeffs.mb = i2c.readS16(BMP085_REGISTER_CAL_MB);
      _bmp085_coeffs.mc = i2c.readS16(BMP085_REGISTER_CAL_MC);
      _bmp085_coeffs.md = i2c.readS16(BMP085_REGISTER_CAL_MD);
#endif
  }

  void setMode(bmp085_mode_t mode) {
      _bmp085Mode = mode;
  }

  int readRawTemperature() {
#if BMP085_USE_DATASHEET_VALS
      return 27898;
#else
      i2c.write8(BMP085_REGISTER_CONTROL, BMP085_REGISTER_READTEMPCMD);
      wait_ms(5);
      return i2c.read16(BMP085_REGISTER_TEMPDATA);
#endif
  }

  int readRawPressure() {
#if BMP085_USE_DATASHEET_VALS
      return 23843;
#else
      uint8_t  p8;
      uint16_t p16;
      int32_t  p32;

      i2c.write8(BMP085_REGISTER_CONTROL, BMP085_REGISTER_READPRESSURECMD + (_bmp085Mode << 6));

      switch(_bmp085Mode)
      {
        case BMP085_MODE_ULTRALOWPOWER:
          wait_ms(5);
          break;
        case BMP085_MODE_STANDARD:
          wait_ms(8);
          break;
        case BMP085_MODE_HIGHRES:
          wait_ms(14);
          break;
        case BMP085_MODE_ULTRAHIGHRES:
        default:
          wait_ms(26);
          break;
      }

      p16 = i2c.read16(BMP085_REGISTER_PRESSUREDATA);
      p32 = (uint32_t)p16 << 8;
      p8 = i2c.read8(BMP085_REGISTER_PRESSUREDATA+2);
      p32 += p8;
      p32 >>= (8 - _bmp085Mode);
      return p32;
#endif
  }

  int32_t computeB5(int32_t ut) {
    int32_t X1 = (ut - (int32_t)_bmp085_coeffs.ac6) * ((int32_t)_bmp085_coeffs.ac5) >> 15;
    int32_t X2 = ((int32_t)_bmp085_coeffs.mc << 11) / (X1+(int32_t)_bmp085_coeffs.md);
    return X1 + X2;
  }

  void begin(bmp085_mode_t mode)
  {
    if (i2c.read8(BMP085_REGISTER_CHIPID) != 0x55)
      uBit.panic(TD_PERIPHERAL_ERROR);

    /* Set the mode indicator */
    _bmp085Mode = mode;

    /* Coefficients need to be read once */
    readCoefficients();
  }

  float getPressure()
  {
    int32_t  ut = 0, up = 0, compp = 0;
    int32_t  x1, x2, b5, b6, x3, b3, p;
    uint32_t b4, b7;

    /* Get the raw pressure and temperature values */
    ut = readRawTemperature();
    up = readRawPressure();

    /* Temperature compensation */
    b5 = computeB5(ut);

    /* Pressure compensation */
    b6 = b5 - 4000;
    x1 = (_bmp085_coeffs.b2 * ((b6 * b6) >> 12)) >> 11;
    x2 = (_bmp085_coeffs.ac2 * b6) >> 11;
    x3 = x1 + x2;
    b3 = (((((int32_t) _bmp085_coeffs.ac1) * 4 + x3) << _bmp085Mode) + 2) >> 2;
    x1 = (_bmp085_coeffs.ac3 * b6) >> 13;
    x2 = (_bmp085_coeffs.b1 * ((b6 * b6) >> 12)) >> 16;
    x3 = ((x1 + x2) + 2) >> 2;
    b4 = (_bmp085_coeffs.ac4 * (uint32_t) (x3 + 32768)) >> 15;
    b7 = ((uint32_t) (up - b3) * (50000 >> _bmp085Mode));

    if (b7 < 0x80000000)
    {
      p = (b7 << 1) / b4;
    }
    else
    {
      p = (b7 / b4) << 1;
    }

    x1 = (p >> 8) * (p >> 8);
    x1 = (x1 * 3038) >> 16;
    x2 = (-7357 * p) >> 16;
    compp = p + ((x1 + x2 + 3791) >> 4);

    /* Assign compensated pressure value */
    return compp;
  }

  float getTemperature()
  {
    int32_t UT, B5;     // following ds convention
    float t;

    UT = readRawTemperature();

#if BMP085_USE_DATASHEET_VALS
      // use datasheet numbers!
      UT = 27898;
      _bmp085_coeffs.ac6 = 23153;
      _bmp085_coeffs.ac5 = 32757;
      _bmp085_coeffs.mc = -8711;
      _bmp085_coeffs.md = 2868;
#endif

    B5 = computeB5(UT);
    t = (B5+8) >> 4;
    t /= 10;

    return t;
  }

  int getIntTemperature() {
      return ((int) getTemperature());
  }
} // namespace bmp085
} // namespace touch_develop
<|endoftext|>


<commit_before>#ifndef DISSENT_TEST_H_GUARD
#define DISSENT_TEST_H_GUARD

#define TEST_RANGE_MIN 15
#define TEST_RANGE_MAX 20

#include <qcoreapplication.h>

#include <gtest/gtest.h>

#include "Dissent.hpp"
#include "Mock.hpp"
#include "RpcTest.hpp"

#endif
<commit_msg>[Tests] bumped up the range for nodes<commit_after>#ifndef DISSENT_TEST_H_GUARD
#define DISSENT_TEST_H_GUARD

#define TEST_RANGE_MIN 15
#define TEST_RANGE_MAX 50

#include <qcoreapplication.h>

#include <gtest/gtest.h>

#include "Dissent.hpp"
#include "Mock.hpp"
#include "RpcTest.hpp"

#endif
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2016 Matthew D. Scholefield
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "Utility.hpp"
#include "Camera.hpp"
#include "SdlManager.hpp"
#include "InputManager.hpp"

Camera::Camera(const Vec2i &size)
{
	recalcFov(size.x, size.y);
	SdlManager::onResize([this](cint sx, cint sy)
	{
		resize(sx, sy);
	});
}

void Camera::resize(cint sx, cint sy)
{
	recalcFov(sx, sy);
}

void Camera::recalcFov(cint sx, cint sy)
{
	float screenSize = 4.f * tan(maxFov / 2.f);
	if (sx > sy)
	{
		fov.x = screenSize;
		fov.y = fov.x * sy / sx;
	}
	else
	{
		fov.y = screenSize;
		fov.x = fov.y * sx / sy;
	}
}

void Camera::updateControls(const InputManager& inputManager)
{
	acc = 0.f;
	rot.acc = 0.f;

	cauto check = [&inputManager](const Key key, float &data, cfloat val)
	{
		if (inputManager.isKeyPressed(key))
			data = val;
	};

	check(Key::lookLeft, rot.acc.x, -turnSpeed);
	check(Key::lookRight, rot.acc.x, +turnSpeed);
	check(Key::lookDown, rot.acc.y, -turnSpeed);
	check(Key::lookUp, rot.acc.y, +turnSpeed);

	check(Key::moveLeft, acc.x, -moveSpeed);
	check(Key::moveRight, acc.x, +moveSpeed);
	check(Key::moveUp, acc.y, -moveSpeed);
	check(Key::moveDown, acc.y, +moveSpeed);
	check(Key::moveBackwards, acc.z, -moveSpeed);
	check(Key::moveForwards, acc.z, +moveSpeed);

	const Vec2f mouseVel = {
		+mouseSpeed * inputManager.getMouseDx(),
		-mouseSpeed * inputManager.getMouseDy()
	};

	const bool hasMoved = mouseVel.abs().max() != 0.f;
	if (hasMoved)
		mouseMode = true;

	if (mouseMode)
	{
		rot.vel = mouseVel;
		if (!hasMoved)
			mouseMode = false;
	}
}

void Camera::update(cfloat dt, const InputManager &inputManager)
{
	updateControls(inputManager);
	Vec3f a = acc;
	if (a.mag() >= epsilon)
	{
		const float rotX = rot.pos.y;
		const float rotY = rot.pos.x;

		const float sx = sin(rotX), cx = cos(rotX);
		const float sy = sin(rotY), cy = cos(rotY);

		a = {
			a.x * cy + a.y * sx * sy + a.z * cx * sy,
			a.y * cx + a.z * -sx,
			a.x * -sy + a.y * cy * sx + a.z * cx * cy
		};
	}

	vel *= pow(friction, dt);
	vel += a * dt;
	pos += vel * dt;

	rot.vel *= pow(friction, dt);
	rot.vel += rot.acc * dt;
	rot.pos += rot.vel * dt;

	if (rot.pos.x > pi)
		rot.pos.x -= 2.f * pi;

	if (rot.pos.x < -pi)
		rot.pos.x += 2.f * pi;

	const float capAngle = pi / 2.f;

	if (rot.pos.y > capAngle)
		rot.pos.y = capAngle;

	if (rot.pos.y < -capAngle)
		rot.pos.y = -capAngle;
}

const Vec2f& Camera::getFov() const
{
	return fov;
}

const Vec3f& Camera::getPos() const
{
	return pos;
}

Vec2f Camera::projectPoint(const Vec3f &point, const Vec2f &canvasSize) const
{
	Vec3f d = point - pos; // Delta
	Vec3f rotated;
	{
		const float rotX = -rot.pos.y;
		const float rotY = -rot.pos.x;

		const float sx = sin(rotX), cx = cos(rotX);
		const float sy = sin(rotY), cy = cos(rotY);

		rotated = {
			d.x * cy + d.z * sy,
			d.x * sx * sy + d.y * cx - d.z * sx * cy,
			d.x * -cx * sy + d.y * sx + d.z * cx * cy
		};
	}

	if (rotated.z < 0)
		return Vec2f(std::numeric_limits<float>::quiet_NaN(),
					std::numeric_limits<float>::quiet_NaN());

	return (Vec2f(rotated.x, rotated.y) / (fov * rotated.z) + 0.5f) * canvasSize;
}

<commit_msg>Added unlimited vertical angles by changing x controls when upside down<commit_after>/*
 * Copyright (C) 2016 Matthew D. Scholefield
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "Utility.hpp"
#include "Camera.hpp"
#include "SdlManager.hpp"
#include "InputManager.hpp"

Camera::Camera(const Vec2i &size)
{
	recalcFov(size.x, size.y);
	SdlManager::onResize([this](cint sx, cint sy)
	{
		resize(sx, sy);
	});
}

void Camera::resize(cint sx, cint sy)
{
	recalcFov(sx, sy);
}

void Camera::recalcFov(cint sx, cint sy)
{
	float screenSize = 4.f * tan(maxFov / 2.f);
	if (sx > sy)
	{
		fov.x = screenSize;
		fov.y = fov.x * sy / sx;
	}
	else
	{
		fov.y = screenSize;
		fov.x = fov.y * sx / sy;
	}
}

void Camera::updateControls(const InputManager& inputManager)
{
	acc = 0.f;
	rot.acc = 0.f;

	cauto check = [&inputManager](const Key key, float &data, cfloat val)
	{
		if (inputManager.isKeyPressed(key))
			data = val;
	};

	cint xSign = std::abs(rot.pos.y) > pi/2.f ? -1 : +1;

	check(Key::lookLeft, rot.acc.x, -xSign * turnSpeed);
	check(Key::lookRight, rot.acc.x, +xSign * turnSpeed);
	check(Key::lookDown, rot.acc.y, -turnSpeed);
	check(Key::lookUp, rot.acc.y, +turnSpeed);

	check(Key::moveLeft, acc.x, -moveSpeed);
	check(Key::moveRight, acc.x, +moveSpeed);
	check(Key::moveUp, acc.y, -moveSpeed);
	check(Key::moveDown, acc.y, +moveSpeed);
	check(Key::moveBackwards, acc.z, -moveSpeed);
	check(Key::moveForwards, acc.z, +moveSpeed);

	const Vec2f mouseVel = {
		+xSign * mouseSpeed * inputManager.getMouseDx(),
		-mouseSpeed * inputManager.getMouseDy()
	};

	const bool hasMoved = mouseVel.abs().max() != 0.f;
	if (hasMoved)
		mouseMode = true;

	if (mouseMode)
	{
		rot.vel = mouseVel;
		if (!hasMoved)
			mouseMode = false;
	}
}

void Camera::update(cfloat dt, const InputManager &inputManager)
{
	updateControls(inputManager);
	Vec3f a = acc;
	if (a.mag() >= epsilon)
	{
		const float rotX = rot.pos.y;
		const float rotY = rot.pos.x;

		const float sx = sin(rotX), cx = cos(rotX);
		const float sy = sin(rotY), cy = cos(rotY);

		a = {
			a.x * cy + a.y * sx * sy + a.z * cx * sy,
			a.y * cx + a.z * -sx,
			a.x * -sy + a.y * cy * sx + a.z * cx * cy
		};
	}

	vel *= pow(friction, dt);
	vel += a * dt;
	pos += vel * dt;

	rot.vel *= pow(friction, dt);
	rot.vel += rot.acc * dt;
	rot.pos += rot.vel * dt;

	if (rot.pos.x > pi)
		rot.pos.x -= 2.f * pi;

	if (rot.pos.x < -pi)
		rot.pos.x += 2.f * pi;

	if (rot.pos.y > pi)
		rot.pos.y -= 2.f * pi;

	if (rot.pos.y < -pi)
		rot.pos.y += 2.f * pi;
}

const Vec2f& Camera::getFov() const
{
	return fov;
}

const Vec3f& Camera::getPos() const
{
	return pos;
}

Vec2f Camera::projectPoint(const Vec3f &point, const Vec2f &canvasSize) const
{
	Vec3f d = point - pos; // Delta
	Vec3f rotated;
	{
		const float rotX = -rot.pos.y;
		const float rotY = -rot.pos.x;

		const float sx = sin(rotX), cx = cos(rotX);
		const float sy = sin(rotY), cy = cos(rotY);

		rotated = {
			d.x * cy + d.z * sy,
			d.x * sx * sy + d.y * cx - d.z * sx * cy,
			d.x * -cx * sy + d.y * sx + d.z * cx * cy
		};
	}

	if (rotated.z < 0)
		return Vec2f(std::numeric_limits<float>::quiet_NaN(),
					std::numeric_limits<float>::quiet_NaN());

	return (Vec2f(rotated.x, rotated.y) / (fov * rotated.z) + 0.5f) * canvasSize;
}

<|endoftext|>


<commit_before>
#include "Globals.h"  // NOTE: MSVC stupidness requires this to be the same across all modules

#include "Piston.h"
#include "ChunkDef.h"
#include "Pickup.h"
#include "Item.h"
#include "Root.h"
#include "ClientHandle.h"
#include "World.h"
#include "BlockID.h"
#include "Server.h"
#include "Blocks/BlockHandler.h"

extern bool g_BlockPistonBreakable[];

#define AddDir( x, y, z, dir, amount ) \
	switch (dir) \
	{ \
		case 0: (y)-=(amount); break; \
		case 1: (y)+=(amount); break; \
		case 2: (z)-=(amount); break; \
		case 3: (z)+=(amount); break; \
		case 4: (x)-=(amount); break; \
		case 5: (x)+=(amount); break; \
	}

cPiston::cPiston(cWorld * a_World)
	: m_World(a_World)
{

}

unsigned short cPiston::FirstPassthroughBlock(int pistonX, int pistonY, int pistonZ, char pistonmeta)
{
	unsigned short ret;
	pistonmeta &= 7;
	if (pistonmeta >= 6)
	{
		// Just in case, it shouldn't happen but if it would, it'd case inf loop
		LOGD("cPiston::FirstPassthroughBlock - piston has invalid meta data!\n");
		return 9001;
	}
	BLOCKTYPE currBlock;
	for (ret = 0; ret < 24; ret++)  // push up to 24 blocks
	{
		AddDir( pistonX, pistonY, pistonZ, pistonmeta, 1)
		currBlock = m_World->GetBlock( pistonX, pistonY, pistonZ );
		if ((currBlock == E_BLOCK_BEDROCK) || (currBlock == E_BLOCK_OBSIDIAN) || (currBlock == E_BLOCK_PISTON_EXTENSION))
		{
			return 9001;
		}
		if (g_BlockPistonBreakable[currBlock])
		{
			return ret;
		}
	}
	return 9001;
}

void cPiston::ExtendPiston( int pistx, int pisty, int pistz )
{
	BLOCKTYPE pistonBlock;
	NIBBLETYPE pistonMeta;
	m_World->GetBlockTypeMeta(pistx, pisty, pistz, pistonBlock, pistonMeta);
	char isSticky = (char)(pistonBlock == E_BLOCK_STICKY_PISTON) * 8;
	if ( (pistonMeta & 0x8) != 0x0 )
	{
		// Piston already extended, bail out
		return;
	}

	unsigned short dist = FirstPassthroughBlock(pistx, pisty, pistz, pistonMeta);
	if (dist > 9000) return; // too many blocks

	AddDir(pistx, pisty, pistz, pistonMeta & 7, dist + 1)
	BLOCKTYPE currBlock;
	NIBBLETYPE currMeta;
	m_World->GetBlockTypeMeta(pistx, pisty, pistz, currBlock, currMeta);
	if (currBlock != E_BLOCK_AIR)
	{
		cBlockHandler * Handler = BlockHandler(currBlock);
		if (Handler->DoesDropOnUnsuitable())
		{
			Handler->DropBlock(m_World, NULL, pistx, pisty, pistz);
		}
	}
	int oldx = pistx, oldy = pisty, oldz = pistz;
	NIBBLETYPE currBlockMeta;
	for (int i = dist + 1; i > 0; i--)
	{
		AddDir(pistx, pisty, pistz, pistonMeta & 7, -1)
		m_World->GetBlockTypeMeta(pistx, pisty, pistz, currBlock, currBlockMeta);
		m_World->SetBlock( oldx, oldy, oldz, currBlock, currBlockMeta);
		oldx = pistx;
		oldy = pisty;
		oldz = pistz;
	}
	m_World->BroadcastBlockAction(pistx, pisty, pistz, 0, pistonMeta, E_BLOCK_PISTON);
	m_World->BroadcastSoundEffect("tile.piston.out", pistx * 8, pisty * 8, pistz * 8, 0.5f, 0.7f);
	m_World->FastSetBlock( pistx, pisty, pistz, pistonBlock, pistonMeta | 0x8 );

	int extx = pistx;
	int exty = pisty;
	int extz = pistz;

	AddDir(extx, exty, extz, pistonMeta & 7, 1)

	#ifdef _WIN32 // Pause for 0.1 seconds to allow client animation to run
		#include <windows.h>
	    Sleep(100);
	#else
		#include <unistd.h>
		usleep(100 * 1000); // takes microseconds
	#endif

	m_World->SetBlock(extx, exty, extz, E_BLOCK_PISTON_EXTENSION, isSticky + pistonMeta & 7);
}

void cPiston::RetractPiston( int pistx, int pisty, int pistz )
{
	BLOCKTYPE pistonBlock;
	NIBBLETYPE pistonMeta;
	m_World->GetBlockTypeMeta(pistx, pisty, pistz, pistonBlock, pistonMeta);
	if (pistonMeta <= 6)
	{
		// Already retracted, bail out
		return;
	}
	m_World->BroadcastBlockAction(pistx, pisty, pistz, 1, pistonMeta & ~(8), E_BLOCK_PISTON);
	m_World->BroadcastSoundEffect("tile.piston.in", pistx * 8, pisty * 8, pistz * 8, 0.5f, 0.7f);
	m_World->FastSetBlock(pistx, pisty, pistz, pistonBlock, pistonMeta & ~(8));

	AddDir(pistx, pisty, pistz, pistonMeta & 7, 1)
	if (m_World->GetBlock(pistx, pisty, pistz) != E_BLOCK_PISTON_EXTENSION)
	{
		LOGD("%s: Piston without an extension?", __FUNCTION__);
		return;
	}

	if (pistonBlock == E_BLOCK_STICKY_PISTON)
	{
		int tempx = pistx, tempy = pisty, tempz = pistz;
		AddDir( tempx, tempy, tempz, pistonMeta & 7, 1 )
		BLOCKTYPE tempblock;
		NIBBLETYPE tempmeta;
		m_World->GetBlockTypeMeta(tempx, tempy, tempz, tempblock, tempmeta);
		if (
			(tempblock == E_BLOCK_OBSIDIAN) ||
			(tempblock == E_BLOCK_BEDROCK) ||
			(tempblock == E_BLOCK_PISTON_EXTENSION)
		)
		{
			// These cannot be moved by the sticky piston, bail out
			return;
		}
		#ifdef _WIN32
			#include <windows.h>
			Sleep(100);
		#else
			#include <unistd.h>
			usleep(100 * 1000); // takes microseconds
		#endif

		m_World->SetBlock(pistx, pisty, pistz, tempblock, tempmeta);
		m_World->SetBlock(tempx, tempy, tempz, E_BLOCK_AIR, 0);
	}
	else
	{
		#ifdef _WIN32
			#include <windows.h>
			Sleep(100);
		#else
			#include <unistd.h>
			usleep(100 * 1000); // takes microseconds
		#endif

		m_World->SetBlock(pistx, pisty, pistz, E_BLOCK_AIR, 0);
	}
}

<commit_msg>Attempt at fixing sleep issue<commit_after>
#include "Globals.h"  // NOTE: MSVC stupidness requires this to be the same across all modules

#include "Piston.h"
#include "ChunkDef.h"
#include "Pickup.h"
#include "Item.h"
#include "Root.h"
#include "ClientHandle.h"
#include "World.h"
#include "BlockID.h"
#include "Server.h"
#include "Blocks/BlockHandler.h"

extern bool g_BlockPistonBreakable[];

#define AddDir( x, y, z, dir, amount ) \
	switch (dir) \
	{ \
		case 0: (y)-=(amount); break; \
		case 1: (y)+=(amount); break; \
		case 2: (z)-=(amount); break; \
		case 3: (z)+=(amount); break; \
		case 4: (x)-=(amount); break; \
		case 5: (x)+=(amount); break; \
	}

cPiston::cPiston(cWorld * a_World)
	: m_World(a_World)
{

}

unsigned short cPiston::FirstPassthroughBlock(int pistonX, int pistonY, int pistonZ, char pistonmeta)
{
	unsigned short ret;
	pistonmeta &= 7;
	if (pistonmeta >= 6)
	{
		// Just in case, it shouldn't happen but if it would, it'd case inf loop
		LOGD("cPiston::FirstPassthroughBlock - piston has invalid meta data!\n");
		return 9001;
	}
	BLOCKTYPE currBlock;
	for (ret = 0; ret < 24; ret++)  // push up to 24 blocks
	{
		AddDir( pistonX, pistonY, pistonZ, pistonmeta, 1)
		currBlock = m_World->GetBlock( pistonX, pistonY, pistonZ );
		if ((currBlock == E_BLOCK_BEDROCK) || (currBlock == E_BLOCK_OBSIDIAN) || (currBlock == E_BLOCK_PISTON_EXTENSION))
		{
			return 9001;
		}
		if (g_BlockPistonBreakable[currBlock])
		{
			return ret;
		}
	}
	return 9001;
}

void cPiston::ExtendPiston( int pistx, int pisty, int pistz )
{
	BLOCKTYPE pistonBlock;
	NIBBLETYPE pistonMeta;
	m_World->GetBlockTypeMeta(pistx, pisty, pistz, pistonBlock, pistonMeta);
	char isSticky = (char)(pistonBlock == E_BLOCK_STICKY_PISTON) * 8;
	if ( (pistonMeta & 0x8) != 0x0 )
	{
		// Piston already extended, bail out
		return;
	}

	unsigned short dist = FirstPassthroughBlock(pistx, pisty, pistz, pistonMeta);
	if (dist > 9000) return; // too many blocks

	AddDir(pistx, pisty, pistz, pistonMeta & 7, dist + 1)
	BLOCKTYPE currBlock;
	NIBBLETYPE currMeta;
	m_World->GetBlockTypeMeta(pistx, pisty, pistz, currBlock, currMeta);
	if (currBlock != E_BLOCK_AIR)
	{
		cBlockHandler * Handler = BlockHandler(currBlock);
		if (Handler->DoesDropOnUnsuitable())
		{
			Handler->DropBlock(m_World, NULL, pistx, pisty, pistz);
		}
	}
	int oldx = pistx, oldy = pisty, oldz = pistz;
	NIBBLETYPE currBlockMeta;
	for (int i = dist + 1; i > 0; i--)
	{
		AddDir(pistx, pisty, pistz, pistonMeta & 7, -1)
		m_World->GetBlockTypeMeta(pistx, pisty, pistz, currBlock, currBlockMeta);
		m_World->SetBlock( oldx, oldy, oldz, currBlock, currBlockMeta);
		oldx = pistx;
		oldy = pisty;
		oldz = pistz;
	}
	m_World->BroadcastBlockAction(pistx, pisty, pistz, 0, pistonMeta, E_BLOCK_PISTON);
	m_World->BroadcastSoundEffect("tile.piston.out", pistx * 8, pisty * 8, pistz * 8, 0.5f, 0.7f);
	m_World->FastSetBlock( pistx, pisty, pistz, pistonBlock, pistonMeta | 0x8 );

	int extx = pistx;
	int exty = pisty;
	int extz = pistz;

	AddDir(extx, exty, extz, pistonMeta & 7, 1)

	#ifdef _WIN32 // Pause for 0.1 seconds to allow client animation to run
		#include <windows.h>
	    Sleep(100);
	#else
		#include <unistd.h>
		usleep(0.1);
	#endif

	m_World->SetBlock(extx, exty, extz, E_BLOCK_PISTON_EXTENSION, isSticky + pistonMeta & 7);
}

void cPiston::RetractPiston( int pistx, int pisty, int pistz )
{
	BLOCKTYPE pistonBlock;
	NIBBLETYPE pistonMeta;
	m_World->GetBlockTypeMeta(pistx, pisty, pistz, pistonBlock, pistonMeta);
	if (pistonMeta <= 6)
	{
		// Already retracted, bail out
		return;
	}
	m_World->BroadcastBlockAction(pistx, pisty, pistz, 1, pistonMeta & ~(8), E_BLOCK_PISTON);
	m_World->BroadcastSoundEffect("tile.piston.in", pistx * 8, pisty * 8, pistz * 8, 0.5f, 0.7f);
	m_World->FastSetBlock(pistx, pisty, pistz, pistonBlock, pistonMeta & ~(8));

	AddDir(pistx, pisty, pistz, pistonMeta & 7, 1)
	if (m_World->GetBlock(pistx, pisty, pistz) != E_BLOCK_PISTON_EXTENSION)
	{
		LOGD("%s: Piston without an extension?", __FUNCTION__);
		return;
	}

	if (pistonBlock == E_BLOCK_STICKY_PISTON)
	{
		int tempx = pistx, tempy = pisty, tempz = pistz;
		AddDir( tempx, tempy, tempz, pistonMeta & 7, 1 )
		BLOCKTYPE tempblock;
		NIBBLETYPE tempmeta;
		m_World->GetBlockTypeMeta(tempx, tempy, tempz, tempblock, tempmeta);
		if (
			(tempblock == E_BLOCK_OBSIDIAN) ||
			(tempblock == E_BLOCK_BEDROCK) ||
			(tempblock == E_BLOCK_PISTON_EXTENSION)
		)
		{
			// These cannot be moved by the sticky piston, bail out
			return;
		}
		#ifdef _WIN32
			#include <windows.h>
			Sleep(100);
		#else
			#include <unistd.h>
			usleep(0.1);
		#endif

		m_World->SetBlock(pistx, pisty, pistz, tempblock, tempmeta);
		m_World->SetBlock(tempx, tempy, tempz, E_BLOCK_AIR, 0);
	}
	else
	{
		#ifdef _WIN32
			#include <windows.h>
			Sleep(100);
		#else
			#include <unistd.h>
			usleep(0.1);
		#endif

		m_World->SetBlock(pistx, pisty, pistz, E_BLOCK_AIR, 0);
	}
}

<|endoftext|>


<commit_before>#include <Utils/GL+/Texture.h>

namespace GL {

    Texture::Texture() {
        create();
    }

    Texture::Texture(const Util::Image& image, Target target, Format format, InternalFormat internalFormat) {
        create();

        load(image, target, format, internalFormat);
    }

    Texture::Texture(const std::string& path, Target target, Format format, InternalFormat internalFormat) {
        create();

        Util::Image image(path, Util::Image::Format::BMP);
        load(image, target, format, internalFormat);
    }

    Texture::Texture(Texture&& texture) {
        create();

        std::swap(_isAlpha, texture._isAlpha);
        std::swap(_width, texture._width);
        std::swap(_height, texture._height);
        std::swap(_target, texture._target);
        std::swap(_textureID, texture._textureID);
        std::swap(_format, texture._format);
        std::swap(_internalFormat, texture._internalFormat);
    }

    Texture::~Texture() {
        destroy();
    }

    Texture& Texture::operator=(Texture&& texture) {
        std::swap(_isAlpha, texture._isAlpha);
        std::swap(_width, texture._width);
        std::swap(_height, texture._height);
        std::swap(_target, texture._target);
        std::swap(_textureID, texture._textureID);
        std::swap(_format, texture._format);
        std::swap(_internalFormat, texture._internalFormat);

        return *this;
    }

    void Texture::bind() const {
        glBindTexture(static_cast<GLenum>(getTarget()), getID());
    }

    void Texture::unbind() const {
        glBindTexture(static_cast<GLenum>(getTarget()), 0);
    }

    void Texture::load(const Util::Image& image, Target target, Format format, InternalFormat internalFormat) {
        setTarget(target);
        bind();
        assingData(image, format, internalFormat);
        setParameters();
        generateMipmap();
        unbind();
    }

    void Texture::generateMipmap() {
        glGenerateMipmap(static_cast<GLenum>(getTarget()));
    }

    void Texture::setData1D(GLsizei width, GLenum dataType, const GLvoid* data, GLint level) {
        setWidth(width);

        glTexImage1D(
            static_cast<GLenum>(getTarget()),
            level,
            static_cast<GLenum>(getInternalFromat()),
            width,
            0,
            static_cast<GLenum>(getFormat()),
            dataType,
            data
        );
    }

    void Texture::setData2D(GLsizei width, GLsizei height, GLenum dataType, const GLvoid* data, GLint level) {
        setWidth(width);
        setHeight(height);

        glTexImage2D(
            static_cast<GLenum>(getTarget()),
            level,
            static_cast<GLenum>(getInternalFromat()),
            width,
            height,
            0,
            static_cast<GLenum>(getFormat()),
            dataType,
            data
        );
    }

    void Texture::setData3D(GLsizei width, GLsizei height, GLsizei depth, GLenum dataType, const GLvoid* data, GLint level) {
        setWidth(width);
        setHeight(height);

        glTexImage3D(
            static_cast<GLenum>(getTarget()),
            level,
            static_cast<GLenum>(getInternalFromat()),
            width,
            height,
            height,
            0,
            static_cast<GLenum>(getFormat()),
            dataType,
            data
        );
    }

    void Texture::setTarget(Target target) {
        _target = target;
    }

    void Texture::setParameters() {
        glTexParameteri(static_cast<GLenum>(getTarget()), GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameteri(static_cast<GLenum>(getTarget()), GL_TEXTURE_WRAP_T, GL_REPEAT);
        glTexParameteri(static_cast<GLenum>(getTarget()), GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(static_cast<GLenum>(getTarget()), GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    }

    void Texture::setParametersI(std::list<std::pair<GLenum, GLint>> parameters) {
        for(auto& parameter : parameters)
            glTexParameteri(static_cast<GLenum>(getTarget()), parameter.first, parameter.second);
    }

    void Texture::setParametersF(std::list<std::pair<GLenum, GLfloat>> parameters) {
        for(auto& parameter : parameters)
            glTexParameterf(static_cast<GLenum>(getTarget()), parameter.first, parameter.second);
    }

    void Texture::setFormat(Format format) {
        _format = format;
    }

    void Texture::setInternalFromat(InternalFormat format) {
        _internalFormat = format;
    }

    bool Texture::isAlpha() const {
        return _isAlpha;
    }

    unsigned int Texture::getWidth() const {
        return _width;
    }

    unsigned int Texture::getHeight() const {
        return _height;
    }

    Texture::Target Texture::getTarget() const {
        return _target;
    }

    Texture::Format Texture::getFormat() const {
        return _format;
    }

    Texture::InternalFormat Texture::getInternalFromat() const {
        return _internalFormat;
    }

    GLuint Texture::getID() const {
        return _textureID;
    }

    void Texture::create() {
        glGenTextures(1, &_textureID);

        setWidth(0);
        setHeight(0);
    }

    void Texture::destroy() {
        glDeleteTextures(1, &_textureID);
    }

    void Texture::assingData(const Util::Image& image, const Format format, const InternalFormat internalFormat) {
        if(format == Format::DefaultFormat) {
            switch(image.getBits()) {
                case 24:
                    setInternalFromat(InternalFormat::RGB);
                    setFormat(Format::BGR);
                    break;

                case 32:
                    setInternalFromat(InternalFormat::RGBA);
                    setFormat(Format::BGRA);
                    break;

                default:
                    throw Util::Exception::FatalError("Could not determine texture's color profile");
                    break;
            }

        } else {
            setFormat(format);
            setInternalFromat(internalFormat);
        }

        setData2D(image.getWidth(), image.getHeight(), GL_UNSIGNED_INT, image.getData());
    }

    void Texture::setWidth(unsigned int width) {
        _width = width;
    }

    void Texture::setHeight(unsigned int height) {
        _height = height;
    }

}<commit_msg>Fixed bug with Textures when textures tried to load data as integers instead of bytes what resulted in crashes.<commit_after>#include <Utils/GL+/Texture.h>

#include <iostream>

namespace GL {

    Texture::Texture() {
        create();
    }

    Texture::Texture(const Util::Image& image, Target target, Format format, InternalFormat internalFormat) {
        create();

        load(image, target, format, internalFormat);
    }

    Texture::Texture(const std::string& path, Target target, Format format, InternalFormat internalFormat) {
        create();

        Util::Image image(path, Util::Image::Format::BMP);
        load(image, target, format, internalFormat);
    }

    Texture::Texture(Texture&& texture) {
        create();

        std::swap(_isAlpha, texture._isAlpha);
        std::swap(_width, texture._width);
        std::swap(_height, texture._height);
        std::swap(_target, texture._target);
        std::swap(_textureID, texture._textureID);
        std::swap(_format, texture._format);
        std::swap(_internalFormat, texture._internalFormat);
    }

    Texture::~Texture() {
        destroy();
    }

    Texture& Texture::operator=(Texture&& texture) {
        std::swap(_isAlpha, texture._isAlpha);
        std::swap(_width, texture._width);
        std::swap(_height, texture._height);
        std::swap(_target, texture._target);
        std::swap(_textureID, texture._textureID);
        std::swap(_format, texture._format);
        std::swap(_internalFormat, texture._internalFormat);

        return *this;
    }

    void Texture::bind() const {
        glBindTexture(static_cast<GLenum>(getTarget()), getID());
    }

    void Texture::unbind() const {
        glBindTexture(static_cast<GLenum>(getTarget()), 0);
    }

    void Texture::load(const Util::Image& image, Target target, Format format, InternalFormat internalFormat) {
        setTarget(target);
        bind();
        assingData(image, format, internalFormat);
        setParameters();
        generateMipmap();
        unbind();
    }

    void Texture::generateMipmap() {
        glGenerateMipmap(static_cast<GLenum>(getTarget()));
    }

    void Texture::setData1D(GLsizei width, GLenum dataType, const GLvoid* data, GLint level) {
        setWidth(width);

        glTexImage1D(
            static_cast<GLenum>(getTarget()),
            level,
            static_cast<GLenum>(getInternalFromat()),
            width,
            0,
            static_cast<GLenum>(getFormat()),
            dataType,
            data
        );
    }

    void Texture::setData2D(GLsizei width, GLsizei height, GLenum dataType, const GLvoid* data, GLint level) {
        setWidth(width);
        setHeight(height);

        glTexImage2D(
            static_cast<GLenum>(getTarget()),
            level,
            static_cast<GLenum>(getInternalFromat()),
            width,
            height,
            0,
            static_cast<GLenum>(getFormat()),
            dataType,
            data
        );
    }

    void Texture::setData3D(GLsizei width, GLsizei height, GLsizei depth, GLenum dataType, const GLvoid* data, GLint level) {
        setWidth(width);
        setHeight(height);

        glTexImage3D(
            static_cast<GLenum>(getTarget()),
            level,
            static_cast<GLenum>(getInternalFromat()),
            width,
            height,
            height,
            0,
            static_cast<GLenum>(getFormat()),
            dataType,
            data
        );
    }

    void Texture::setTarget(Target target) {
        _target = target;
    }

    void Texture::setParameters() {
        glTexParameteri(static_cast<GLenum>(getTarget()), GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameteri(static_cast<GLenum>(getTarget()), GL_TEXTURE_WRAP_T, GL_REPEAT);
        glTexParameteri(static_cast<GLenum>(getTarget()), GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(static_cast<GLenum>(getTarget()), GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    }

    void Texture::setParametersI(std::list<std::pair<GLenum, GLint>> parameters) {
        for(auto& parameter : parameters)
            glTexParameteri(static_cast<GLenum>(getTarget()), parameter.first, parameter.second);
    }

    void Texture::setParametersF(std::list<std::pair<GLenum, GLfloat>> parameters) {
        for(auto& parameter : parameters)
            glTexParameterf(static_cast<GLenum>(getTarget()), parameter.first, parameter.second);
    }

    void Texture::setFormat(Format format) {
        _format = format;
    }

    void Texture::setInternalFromat(InternalFormat format) {
        _internalFormat = format;
    }

    bool Texture::isAlpha() const {
        return _isAlpha;
    }

    unsigned int Texture::getWidth() const {
        return _width;
    }

    unsigned int Texture::getHeight() const {
        return _height;
    }

    Texture::Target Texture::getTarget() const {
        return _target;
    }

    Texture::Format Texture::getFormat() const {
        return _format;
    }

    Texture::InternalFormat Texture::getInternalFromat() const {
        return _internalFormat;
    }

    GLuint Texture::getID() const {
        return _textureID;
    }

    void Texture::create() {
        glGenTextures(1, &_textureID);

        setWidth(0);
        setHeight(0);
    }

    void Texture::destroy() {
        glDeleteTextures(1, &_textureID);
    }

    void Texture::assingData(const Util::Image& image, const Format format, const InternalFormat internalFormat) {
        if(format == Format::DefaultFormat) {
            switch(image.getBits()) {
                case 24:
                    setInternalFromat(InternalFormat::RGB);
                    setFormat(Format::BGR);
                    break;

                case 32:
                    setInternalFromat(InternalFormat::RGBA);
                    setFormat(Format::BGRA);
                    break;

                default:
                    throw Util::Exception::FatalError("Could not determine texture's color profile");
                    break;
            }

        } else {
            setFormat(format);
            setInternalFromat(internalFormat);
        }

        setData2D(image.getWidth(), image.getHeight(), GL_UNSIGNED_BYTE, image.getData());
    }

    void Texture::setWidth(unsigned int width) {
        _width = width;
    }

    void Texture::setHeight(unsigned int height) {
        _height = height;
    }

}<|endoftext|>