<commit_before>#include <QIntValidator>
#include <QDesktopServices>
#include "assettingsview.h"
#include "pathsetting.h"
#include "optionalsetting.h"
#include "ui_assettingsview.h"

AsSettingsView::AsSettingsView(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::AsSettingsView)
{
    ui->setupUi(this);
    hide();
}

AsSettingsView::~AsSettingsView()
{
    delete ui;
}

void AsSettingsView::init(ISettings* settingsModel)
{
    this->settingsModel = settingsModel;
    ui->parametersLineEdit->setText(settingsModel->launchParameters());

    ui->steamPathSetting->init("Steam", settingsModel->steamPath());
    connect(ui->steamPathSetting, &PathSetting::textEdited, this, &AsSettingsView::setSteamPath);
    connect(ui->steamPathSetting, &PathSetting::resetPressed, [=]
    {
        settingsModel->resetSteamPath();
        ui->steamPathSetting->setValue(settingsModel->steamPath());
    });

    ui->modsPathSetting->init("Mod Download", settingsModel->modDownloadPath());
    connect(ui->modsPathSetting, &PathSetting::textEdited, this, &AsSettingsView::setModDownloadPath);
    connect(ui->modsPathSetting, &PathSetting::resetPressed, [=]
    {
        settingsModel->resetModDownloadPath();
        ui->modsPathSetting->setValue(settingsModel->modDownloadPath());
    });

    ui->teamspeakPathSetting->init("TeamSpeak 3", settingsModel->teamSpeak3Path());
    connect(ui->teamspeakPathSetting, &PathSetting::textEdited, this, &AsSettingsView::setTeamSpeak3Path);
    connect(ui->teamspeakPathSetting, &PathSetting::resetPressed, [=]
    {
        settingsModel->resetTeamSpeak3Path();
        ui->teamspeakPathSetting->setValue(settingsModel->teamSpeak3Path());
    });

    ui->arma3PathSetting->init("Arma 3", settingsModel->arma3Path());
    connect(ui->arma3PathSetting, &PathSetting::textEdited, this, &AsSettingsView::setArma3Path);
    connect(ui->arma3PathSetting, &PathSetting::resetPressed, [=] {
        settingsModel->resetArma3Path();
        ui->arma3PathSetting->setValue(settingsModel->arma3Path());
    });

    ui->downloadSetting->init("Download limit:", settingsModel->maxDownload(), settingsModel->maxDownloadEnabled());
    connect(ui->downloadSetting, &OptionalSetting::checked, [=] (bool ticked)
    {
        settingsModel->setMaxDownloadEnabled(ticked);
    });
    connect(ui->downloadSetting, &OptionalSetting::valueChanged, [=] (QString newValue)
    {
        settingsModel->setMaxDownload(newValue);
    });
    ui->uploadSetting->init("Upload limit:", settingsModel->maxUpload(), settingsModel->maxUploadEnabled());
    connect(ui->uploadSetting, &OptionalSetting::checked, [=] (bool ticked) {
        settingsModel->setMaxUploadEnabled(ticked);
    });
    connect(ui->uploadSetting, &OptionalSetting::valueChanged, [=] (QString newValue)
    {
        settingsModel->setMaxUpload(newValue);
    });

    ui->portLineEdit->setText(settingsModel->port());
    ui->portLineEdit->setValidator(new QIntValidator(0, 65535, this));
    ui->deltaPatchingCheckbox->setChecked(settingsModel->deltaPatchingEnabled());
}

void AsSettingsView::setArma3Path(QString path)
{
    settingsModel->setArma3Path(path);
}

void AsSettingsView::setSteamPath(QString path)
{
    settingsModel->setSteamPath(path);
}

void AsSettingsView::setModDownloadPath(QString path)
{
    settingsModel->setModDownloadPath(path);
}

void AsSettingsView::setTeamSpeak3Path(QString path)
{
    settingsModel->setTeamSpeak3Path(path);
}

void AsSettingsView::on_parametersLineEdit_editingFinished()
{
    settingsModel->setLaunchParameters(ui->parametersLineEdit->text());
}

void AsSettingsView::on_portLineEdit_editingFinished()
{
    settingsModel->setPort(ui->portLineEdit->text());
}

void AsSettingsView::on_reportButton_clicked()
{
    QDesktopServices::openUrl(QUrl::fromEncoded("https://www.google.fi"));
}

void AsSettingsView::on_deltaPatchingCheckbox_toggled(const bool checked)
{
    settingsModel->setDeltaPatchingEnabled(checked);
}
<commit_msg>Report bug fixed<commit_after>#include <QIntValidator>
#include <QDesktopServices>
#include "assettingsview.h"
#include "pathsetting.h"
#include "optionalsetting.h"
#include "ui_assettingsview.h"

AsSettingsView::AsSettingsView(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::AsSettingsView)
{
    ui->setupUi(this);
    hide();
}

AsSettingsView::~AsSettingsView()
{
    delete ui;
}

void AsSettingsView::init(ISettings* settingsModel)
{
    this->settingsModel = settingsModel;
    ui->parametersLineEdit->setText(settingsModel->launchParameters());

    ui->steamPathSetting->init("Steam", settingsModel->steamPath());
    connect(ui->steamPathSetting, &PathSetting::textEdited, this, &AsSettingsView::setSteamPath);
    connect(ui->steamPathSetting, &PathSetting::resetPressed, [=]
    {
        settingsModel->resetSteamPath();
        ui->steamPathSetting->setValue(settingsModel->steamPath());
    });

    ui->modsPathSetting->init("Mod Download", settingsModel->modDownloadPath());
    connect(ui->modsPathSetting, &PathSetting::textEdited, this, &AsSettingsView::setModDownloadPath);
    connect(ui->modsPathSetting, &PathSetting::resetPressed, [=]
    {
        settingsModel->resetModDownloadPath();
        ui->modsPathSetting->setValue(settingsModel->modDownloadPath());
    });

    ui->teamspeakPathSetting->init("TeamSpeak 3", settingsModel->teamSpeak3Path());
    connect(ui->teamspeakPathSetting, &PathSetting::textEdited, this, &AsSettingsView::setTeamSpeak3Path);
    connect(ui->teamspeakPathSetting, &PathSetting::resetPressed, [=]
    {
        settingsModel->resetTeamSpeak3Path();
        ui->teamspeakPathSetting->setValue(settingsModel->teamSpeak3Path());
    });

    ui->arma3PathSetting->init("Arma 3", settingsModel->arma3Path());
    connect(ui->arma3PathSetting, &PathSetting::textEdited, this, &AsSettingsView::setArma3Path);
    connect(ui->arma3PathSetting, &PathSetting::resetPressed, [=] {
        settingsModel->resetArma3Path();
        ui->arma3PathSetting->setValue(settingsModel->arma3Path());
    });

    ui->downloadSetting->init("Download limit:", settingsModel->maxDownload(), settingsModel->maxDownloadEnabled());
    connect(ui->downloadSetting, &OptionalSetting::checked, [=] (bool ticked)
    {
        settingsModel->setMaxDownloadEnabled(ticked);
    });
    connect(ui->downloadSetting, &OptionalSetting::valueChanged, [=] (QString newValue)
    {
        settingsModel->setMaxDownload(newValue);
    });
    ui->uploadSetting->init("Upload limit:", settingsModel->maxUpload(), settingsModel->maxUploadEnabled());
    connect(ui->uploadSetting, &OptionalSetting::checked, [=] (bool ticked) {
        settingsModel->setMaxUploadEnabled(ticked);
    });
    connect(ui->uploadSetting, &OptionalSetting::valueChanged, [=] (QString newValue)
    {
        settingsModel->setMaxUpload(newValue);
    });

    ui->portLineEdit->setText(settingsModel->port());
    ui->portLineEdit->setValidator(new QIntValidator(0, 65535, this));
    ui->deltaPatchingCheckbox->setChecked(settingsModel->deltaPatchingEnabled());
}

void AsSettingsView::setArma3Path(QString path)
{
    settingsModel->setArma3Path(path);
}

void AsSettingsView::setSteamPath(QString path)
{
    settingsModel->setSteamPath(path);
}

void AsSettingsView::setModDownloadPath(QString path)
{
    settingsModel->setModDownloadPath(path);
}

void AsSettingsView::setTeamSpeak3Path(QString path)
{
    settingsModel->setTeamSpeak3Path(path);
}

void AsSettingsView::on_parametersLineEdit_editingFinished()
{
    settingsModel->setLaunchParameters(ui->parametersLineEdit->text());
}

void AsSettingsView::on_portLineEdit_editingFinished()
{
    settingsModel->setPort(ui->portLineEdit->text());
}

void AsSettingsView::on_reportButton_clicked()
{
    QDesktopServices::openUrl(QUrl::fromEncoded("https://form.jotformeu.com/61187638191361"));
}

void AsSettingsView::on_deltaPatchingCheckbox_toggled(const bool checked)
{
    settingsModel->setDeltaPatchingEnabled(checked);
}
<|endoftext|>


<commit_before>#include "Lexer.h"

Lexer::Lexer(Allocator *allocator): lexems(allocator)
{
}

void Lexer::Clear(unsigned count)
{
	if(count)
		lexems.shrink(count);
	else
		lexems.clear();
}

void Lexer::Lexify(const char* code)
{
	lexems.reserve(2048);

	const char *lineStart = code;
	line = 0;

	LexemeType lType = lex_none;
	int lLength = 1;

	while(*code)
	{
		switch(*code)
		{
		case '\r':
			code++;

			if(*code == '\n')
				code++;

			lineStart = code;
			line++;

			continue;
		case '\n':
			code++;

			lineStart = code;
			line++;

			continue;
		case ' ':
		case '\t':
			code++;
			while((unsigned char)(code[0] - 1) < ' ' && *code != '\r' && *code != '\n')
				code++;
			continue;
		case '\"':
			lType = lex_quotedstring;
			{
				const char *pos = code;
				pos++;
				while(*pos && *pos != '\"')
					pos += (pos[0] == '\\' && pos[1]) ? 2 : 1;
				if(*pos)
					pos++;
				lLength = (int)(pos - code);
			}
			break;
		case '\'':
			lType = lex_semiquotedchar;
			{
				const char *pos = code;
				pos++;
				while(*pos && *pos != '\'')
					pos += (pos[0] == '\\' && pos[1]) ? 2 : 1;
				if(*pos)
					pos++;
				lLength = (int)(pos - code);
			}
			break;
		case '.':
			lType = lex_point;
			break;
		case ',':
			lType = lex_comma;
			break;
		case '+':
			lType = lex_add;
			if(code[1] == '=')
			{
				lType = lex_addset;
				lLength = 2;
			}else if(code[1] == '+'){
				lType = lex_inc;
				lLength = 2;
			}
			break;
		case '-':
			lType = lex_sub;
			if(code[1] == '=')
			{
				lType = lex_subset;
				lLength = 2;
			}else if(code[1] == '-'){
				lType = lex_dec;
				lLength = 2;
			}
			break;
		case '*':
			lType = lex_mul;
			if(code[1] == '=')
			{
				lType = lex_mulset;
				lLength = 2;
			}else if(code[1] == '*'){
				lType = lex_pow;
				lLength = 2;
				if(code[2] == '=')
				{
					lType = lex_powset;
					lLength = 3;
				}
			}
			break;
		case '/':
			if(code[1] == '=')
			{
				lType = lex_divset;
				lLength = 2;
			}else if(code[1] == '/'){
				while(code[0] != '\n' && code[0] != '\0')
					code++;
				continue;
			}else if(code[1] == '*'){
				code += 2;
				unsigned depth = 1;
				while(*code && depth)
				{
					if(code[0] == '*' && code[1] == '/')
					{
						code += 2;
						depth--;
					}
					else if(code[0] == '/' && code[1] == '*')
					{
						code += 2;
						depth++;
					}
					else if(code[0] == '\"')
					{
						code++;

						while(code[0] && code[0] != '\"')
						{
							if(code[0] == '\\' && code[1])
							{
								code += 2;
							}
							else if(code[0] == '\r')
							{
								code++;

								if(*code == '\n')
									code++;

								lineStart = code;
								line++;
							}
							else if(code[0] == '\n')
							{
								code++;

								lineStart = code;
								line++;
							}
							else
							{
								code += 1;
							}
						}

						if(code[0] == '\"')
							code++;
					}
					else if(code[0] == '\r')
					{
						code++;

						if(*code == '\n')
							code++;

						lineStart = code;
						line++;
					}
					else if(code[0] == '\n')
					{
						code++;

						lineStart = code;
						line++;
					}
					else
					{
						code++;
					}
				}
				continue;
			}else{
				lType = lex_div;
			}
			break;
		case '%':
			lType = lex_mod;
			if(code[1] == '=')
			{
				lType = lex_modset;
				lLength = 2;
			}
			break;
		case '<':
			lType = lex_less;
			if(code[1] == '=')
			{
				lType = lex_lequal;
				lLength = 2;
			}else if(code[1] == '<'){
				lType = lex_shl;
				lLength = 2;
				if(code[2] == '=')
				{
					lType = lex_shlset;
					lLength = 3;
				}
			}
			break;
		case '>':
			lType = lex_greater;
			if(code[1] == '=')
			{
				lType = lex_gequal;
				lLength = 2;
			}else if(code[1] == '>'){
				lType = lex_shr;
				lLength = 2;
				if(code[2] == '=')
				{
					lType = lex_shrset;
					lLength = 3;
				}
			}
			break;
		case '=':
			lType = lex_set;
			if(code[1] == '=')
			{
				lType = lex_equal;
				lLength = 2;
			}
			break;
		case '!':
			lType = lex_lognot;
			if(code[1] == '=')
			{
				lType = lex_nequal;
				lLength = 2;
			}
			break;
		case '@':
			lType = lex_at;
			break;
		case '~':
			lType = lex_bitnot;
			break;
		case '&':
			lType = lex_bitand;
			if(code[1] == '&')
			{
				lType = lex_logand;
				lLength = 2;
			}else if(code[1] == '='){
				lType = lex_andset;
				lLength = 2;
			}
			break;
		case '|':
			lType = lex_bitor;
			if(code[1] == '|')
			{
				lType = lex_logor;
				lLength = 2;
			}else if(code[1] == '='){
				lType = lex_orset;
				lLength = 2;
			}
			break;
		case '^':
			lType = lex_bitxor;
			if(code[1] == '^')
			{
				lType = lex_logxor;
				lLength = 2;
			}else if(code[1] == '='){
				lType = lex_xorset;
				lLength = 2;
			}
			break;
		case '(':
			lType = lex_oparen;
			break;
		case ')':
			lType = lex_cparen;
			break;
		case '[':
			lType = lex_obracket;
			break;
		case ']':
			lType = lex_cbracket;
			break;
		case '{':
			lType = lex_ofigure;
			break;
		case '}':
			lType = lex_cfigure;
			break;
		case '?':
			lType = lex_questionmark;
			break;
		case ':':
			lType = lex_colon;
			break;
		case ';':
			lType = lex_semicolon;
			break;
		default:
			if(isDigit(*code))
			{
				lType = lex_number;

				const char *pos = code;
				if(pos[0] == '0' && pos[1] == 'x')
				{
					pos += 2;
					while(isDigit(*pos) || ((*pos & ~0x20) >= 'A' && (*pos & ~0x20) <= 'F'))
						pos++;
				}else{
					while(isDigit(*pos))
						pos++;
				}
				if(*pos == '.')
					pos++;
				while(isDigit(*pos))
					pos++;
				if(*pos == 'e')
				{
					pos++;
					if(*pos == '-')
						pos++;
				}
				while(isDigit(*pos))
					pos++;
				lLength = (int)(pos - code);
			}else if(chartype_table[(unsigned char)*code] & ct_start_symbol){
				const char *pos = code;
				while(chartype_table[(unsigned char)*pos] & ct_symbol)
					pos++;
				lLength = (int)(pos - code);

				if(!(chartype_table[(unsigned char)*pos] & ct_symbol))
				{
					switch(lLength)
					{
					case 2:
						if(memcmp(code, "if", 2) == 0)
							lType = lex_if;
						else if(memcmp(code, "in", 2) == 0)
							lType = lex_in;
						else if(memcmp(code, "do", 2) == 0)
							lType = lex_do;
						break;
					case 3:
						if(memcmp(code, "for", 3) == 0)
							lType = lex_for;
						else if(memcmp(code, "ref", 3) == 0)
							lType = lex_ref;
						else if(memcmp(code, "new", 3) == 0)
							lType = lex_new;
						break;
					case 4:
						if(memcmp(code, "case", 4) == 0)
							lType = lex_case;
						else if(memcmp(code, "else", 4) == 0)
							lType = lex_else;
						else if(memcmp(code, "auto", 4) == 0)
							lType = lex_auto;
						else if(memcmp(code, "true", 4) == 0)
							lType = lex_true;
						else if(memcmp(code, "enum", 4) == 0)
							lType = lex_enum;
						else if(memcmp(code, "with", 4) == 0)
							lType = lex_with;
						break;
					case 5:
						if(memcmp(code, "while", 5) == 0)
							lType = lex_while;
						else if(memcmp(code, "break", 5) == 0)
							lType = lex_break;
						else if(memcmp(code, "class", 5) == 0)
							lType = lex_class;
						else if(memcmp(code, "align", 5) == 0)
							lType = lex_align;
						else if(memcmp(code, "yield", 5) == 0)
							lType = lex_yield;
						else if(memcmp(code, "const", 5) == 0)
							lType = lex_const;
						else if(memcmp(code, "false", 5) == 0)
							lType = lex_false;
						break;
					case 6:
						if(memcmp(code, "switch", 6) == 0)
							lType = lex_switch;
						else if(memcmp(code, "return", 6) == 0)
							lType = lex_return;
						else if(memcmp(code, "typeof", 6) == 0)
							lType = lex_typeof;
						else if(memcmp(code, "sizeof", 6) == 0)
							lType = lex_sizeof;
						else if(memcmp(code, "import", 6) == 0)
							lType = lex_import;
						break;
					case 7:
						if(memcmp(code, "noalign", 7) == 0)
							lType = lex_noalign;
						else if(memcmp(code, "default", 7) == 0)
							lType = lex_default;
						else if(memcmp(code, "typedef", 7) == 0)
							lType = lex_typedef;
						else if(memcmp(code, "nullptr", 7) == 0)
							lType = lex_nullptr;
						else if(memcmp(code, "generic", 7) == 0)
							lType = lex_generic;
						break;
					case 8:
						if(memcmp(code, "continue", 8) == 0)
							lType = lex_continue;
						else if(memcmp(code, "operator", 8) == 0)
							lType = lex_operator;
						break;
					case 9:
						if(memcmp(code, "coroutine", 9) == 0)
							lType = lex_coroutine;
						else if(memcmp(code, "namespace", 9) == 0)
							lType = lex_namespace;
						break;
					case 10:
						if(memcmp(code, "extendable", 10) == 0)
							lType = lex_extendable;
						break;
					}
				}

				if(lType == lex_none)
					lType = lex_string;
			}
		}
		Lexeme lex;

		lex.type = lType;
		lex.length = lLength;

		lex.pos = code;

		lex.line = line;
		lex.column = unsigned(code - lineStart);

		lexems.push_back(lex);

		code += lLength;
		lType = lex_none;
		lLength = 1;
	}

	Lexeme lex;

	lex.type = lex_none;
	lex.length = 1;

	lex.pos = code;

	lex.line = line;
	lex.column = unsigned(code - lineStart);

	lexems.push_back(lex);
}

void Lexer::Append(Lexeme* stream, unsigned count)
{
	unsigned oldSize = lexems.size();
	lexems.resize(lexems.size() + count);
	memcpy(&lexems.data[oldSize], stream, count * sizeof(Lexeme));
}

Lexeme* Lexer::GetStreamStart()
{
	return &lexems[0];
}

unsigned int Lexer::GetStreamSize()
{
	return lexems.size();
}
<commit_msg>Fix for line/column location tracking after a multi-line string or character literal<commit_after>#include "Lexer.h"

Lexer::Lexer(Allocator *allocator): lexems(allocator)
{
}

void Lexer::Clear(unsigned count)
{
	if(count)
		lexems.shrink(count);
	else
		lexems.clear();
}

void Lexer::Lexify(const char* code)
{
	lexems.reserve(2048);

	const char *lineStart = code;
	line = 0;

	LexemeType lType = lex_none;
	int lLength = 1;

	while(*code)
	{
		switch(*code)
		{
		case '\r':
			code++;

			if(*code == '\n')
				code++;

			lineStart = code;
			line++;

			continue;
		case '\n':
			code++;

			lineStart = code;
			line++;

			continue;
		case ' ':
		case '\t':
			code++;
			while((unsigned char)(code[0] - 1) < ' ' && *code != '\r' && *code != '\n')
				code++;
			continue;
		case '\"':
			lType = lex_quotedstring;
			{
				const char *pos = code;
				pos++;

				while(*pos && *pos != '\"')
				{
					if(pos[0] == '\\' && pos[1])
					{
						pos += 2;
					}
					else if(pos[0] == '\r')
					{
						pos++;

						if(*pos == '\n')
							pos++;

						lineStart = pos;
						line++;
					}
					else if(pos[0] == '\n')
					{
						pos++;

						lineStart = pos;
						line++;
					}
					else
					{
						pos += 1;
					}
				}

				if(*pos)
					pos++;

				lLength = (int)(pos - code);
			}
			break;
		case '\'':
			lType = lex_semiquotedchar;
			{
				const char *pos = code;
				pos++;

				while(*pos && *pos != '\'')
				{
					if(pos[0] == '\\' && pos[1])
					{
						pos += 2;
					}
					else if(pos[0] == '\r')
					{
						pos++;

						if(*pos == '\n')
							pos++;

						lineStart = pos;
						line++;
					}
					else if(pos[0] == '\n')
					{
						pos++;

						lineStart = pos;
						line++;
					}
					else
					{
						pos += 1;
					}
				}

				if(*pos)
					pos++;

				lLength = (int)(pos - code);
			}
			break;
		case '.':
			lType = lex_point;
			break;
		case ',':
			lType = lex_comma;
			break;
		case '+':
			lType = lex_add;
			if(code[1] == '=')
			{
				lType = lex_addset;
				lLength = 2;
			}else if(code[1] == '+'){
				lType = lex_inc;
				lLength = 2;
			}
			break;
		case '-':
			lType = lex_sub;
			if(code[1] == '=')
			{
				lType = lex_subset;
				lLength = 2;
			}else if(code[1] == '-'){
				lType = lex_dec;
				lLength = 2;
			}
			break;
		case '*':
			lType = lex_mul;
			if(code[1] == '=')
			{
				lType = lex_mulset;
				lLength = 2;
			}else if(code[1] == '*'){
				lType = lex_pow;
				lLength = 2;
				if(code[2] == '=')
				{
					lType = lex_powset;
					lLength = 3;
				}
			}
			break;
		case '/':
			if(code[1] == '=')
			{
				lType = lex_divset;
				lLength = 2;
			}else if(code[1] == '/'){
				while(code[0] != '\n' && code[0] != '\0')
					code++;
				continue;
			}else if(code[1] == '*'){
				code += 2;
				unsigned depth = 1;
				while(*code && depth)
				{
					if(code[0] == '*' && code[1] == '/')
					{
						code += 2;
						depth--;
					}
					else if(code[0] == '/' && code[1] == '*')
					{
						code += 2;
						depth++;
					}
					else if(code[0] == '\"')
					{
						code++;

						while(code[0] && code[0] != '\"')
						{
							if(code[0] == '\\' && code[1])
							{
								code += 2;
							}
							else if(code[0] == '\r')
							{
								code++;

								if(*code == '\n')
									code++;

								lineStart = code;
								line++;
							}
							else if(code[0] == '\n')
							{
								code++;

								lineStart = code;
								line++;
							}
							else
							{
								code += 1;
							}
						}

						if(code[0] == '\"')
							code++;
					}
					else if(code[0] == '\r')
					{
						code++;

						if(*code == '\n')
							code++;

						lineStart = code;
						line++;
					}
					else if(code[0] == '\n')
					{
						code++;

						lineStart = code;
						line++;
					}
					else
					{
						code++;
					}
				}
				continue;
			}else{
				lType = lex_div;
			}
			break;
		case '%':
			lType = lex_mod;
			if(code[1] == '=')
			{
				lType = lex_modset;
				lLength = 2;
			}
			break;
		case '<':
			lType = lex_less;
			if(code[1] == '=')
			{
				lType = lex_lequal;
				lLength = 2;
			}else if(code[1] == '<'){
				lType = lex_shl;
				lLength = 2;
				if(code[2] == '=')
				{
					lType = lex_shlset;
					lLength = 3;
				}
			}
			break;
		case '>':
			lType = lex_greater;
			if(code[1] == '=')
			{
				lType = lex_gequal;
				lLength = 2;
			}else if(code[1] == '>'){
				lType = lex_shr;
				lLength = 2;
				if(code[2] == '=')
				{
					lType = lex_shrset;
					lLength = 3;
				}
			}
			break;
		case '=':
			lType = lex_set;
			if(code[1] == '=')
			{
				lType = lex_equal;
				lLength = 2;
			}
			break;
		case '!':
			lType = lex_lognot;
			if(code[1] == '=')
			{
				lType = lex_nequal;
				lLength = 2;
			}
			break;
		case '@':
			lType = lex_at;
			break;
		case '~':
			lType = lex_bitnot;
			break;
		case '&':
			lType = lex_bitand;
			if(code[1] == '&')
			{
				lType = lex_logand;
				lLength = 2;
			}else if(code[1] == '='){
				lType = lex_andset;
				lLength = 2;
			}
			break;
		case '|':
			lType = lex_bitor;
			if(code[1] == '|')
			{
				lType = lex_logor;
				lLength = 2;
			}else if(code[1] == '='){
				lType = lex_orset;
				lLength = 2;
			}
			break;
		case '^':
			lType = lex_bitxor;
			if(code[1] == '^')
			{
				lType = lex_logxor;
				lLength = 2;
			}else if(code[1] == '='){
				lType = lex_xorset;
				lLength = 2;
			}
			break;
		case '(':
			lType = lex_oparen;
			break;
		case ')':
			lType = lex_cparen;
			break;
		case '[':
			lType = lex_obracket;
			break;
		case ']':
			lType = lex_cbracket;
			break;
		case '{':
			lType = lex_ofigure;
			break;
		case '}':
			lType = lex_cfigure;
			break;
		case '?':
			lType = lex_questionmark;
			break;
		case ':':
			lType = lex_colon;
			break;
		case ';':
			lType = lex_semicolon;
			break;
		default:
			if(isDigit(*code))
			{
				lType = lex_number;

				const char *pos = code;
				if(pos[0] == '0' && pos[1] == 'x')
				{
					pos += 2;
					while(isDigit(*pos) || ((*pos & ~0x20) >= 'A' && (*pos & ~0x20) <= 'F'))
						pos++;
				}else{
					while(isDigit(*pos))
						pos++;
				}
				if(*pos == '.')
					pos++;
				while(isDigit(*pos))
					pos++;
				if(*pos == 'e')
				{
					pos++;
					if(*pos == '-')
						pos++;
				}
				while(isDigit(*pos))
					pos++;
				lLength = (int)(pos - code);
			}else if(chartype_table[(unsigned char)*code] & ct_start_symbol){
				const char *pos = code;
				while(chartype_table[(unsigned char)*pos] & ct_symbol)
					pos++;
				lLength = (int)(pos - code);

				if(!(chartype_table[(unsigned char)*pos] & ct_symbol))
				{
					switch(lLength)
					{
					case 2:
						if(memcmp(code, "if", 2) == 0)
							lType = lex_if;
						else if(memcmp(code, "in", 2) == 0)
							lType = lex_in;
						else if(memcmp(code, "do", 2) == 0)
							lType = lex_do;
						break;
					case 3:
						if(memcmp(code, "for", 3) == 0)
							lType = lex_for;
						else if(memcmp(code, "ref", 3) == 0)
							lType = lex_ref;
						else if(memcmp(code, "new", 3) == 0)
							lType = lex_new;
						break;
					case 4:
						if(memcmp(code, "case", 4) == 0)
							lType = lex_case;
						else if(memcmp(code, "else", 4) == 0)
							lType = lex_else;
						else if(memcmp(code, "auto", 4) == 0)
							lType = lex_auto;
						else if(memcmp(code, "true", 4) == 0)
							lType = lex_true;
						else if(memcmp(code, "enum", 4) == 0)
							lType = lex_enum;
						else if(memcmp(code, "with", 4) == 0)
							lType = lex_with;
						break;
					case 5:
						if(memcmp(code, "while", 5) == 0)
							lType = lex_while;
						else if(memcmp(code, "break", 5) == 0)
							lType = lex_break;
						else if(memcmp(code, "class", 5) == 0)
							lType = lex_class;
						else if(memcmp(code, "align", 5) == 0)
							lType = lex_align;
						else if(memcmp(code, "yield", 5) == 0)
							lType = lex_yield;
						else if(memcmp(code, "const", 5) == 0)
							lType = lex_const;
						else if(memcmp(code, "false", 5) == 0)
							lType = lex_false;
						break;
					case 6:
						if(memcmp(code, "switch", 6) == 0)
							lType = lex_switch;
						else if(memcmp(code, "return", 6) == 0)
							lType = lex_return;
						else if(memcmp(code, "typeof", 6) == 0)
							lType = lex_typeof;
						else if(memcmp(code, "sizeof", 6) == 0)
							lType = lex_sizeof;
						else if(memcmp(code, "import", 6) == 0)
							lType = lex_import;
						break;
					case 7:
						if(memcmp(code, "noalign", 7) == 0)
							lType = lex_noalign;
						else if(memcmp(code, "default", 7) == 0)
							lType = lex_default;
						else if(memcmp(code, "typedef", 7) == 0)
							lType = lex_typedef;
						else if(memcmp(code, "nullptr", 7) == 0)
							lType = lex_nullptr;
						else if(memcmp(code, "generic", 7) == 0)
							lType = lex_generic;
						break;
					case 8:
						if(memcmp(code, "continue", 8) == 0)
							lType = lex_continue;
						else if(memcmp(code, "operator", 8) == 0)
							lType = lex_operator;
						break;
					case 9:
						if(memcmp(code, "coroutine", 9) == 0)
							lType = lex_coroutine;
						else if(memcmp(code, "namespace", 9) == 0)
							lType = lex_namespace;
						break;
					case 10:
						if(memcmp(code, "extendable", 10) == 0)
							lType = lex_extendable;
						break;
					}
				}

				if(lType == lex_none)
					lType = lex_string;
			}
		}
		Lexeme lex;

		lex.type = lType;
		lex.length = lLength;

		lex.pos = code;

		lex.line = line;
		lex.column = unsigned(code - lineStart);

		lexems.push_back(lex);

		code += lLength;
		lType = lex_none;
		lLength = 1;
	}

	Lexeme lex;

	lex.type = lex_none;
	lex.length = 1;

	lex.pos = code;

	lex.line = line;
	lex.column = unsigned(code - lineStart);

	lexems.push_back(lex);
}

void Lexer::Append(Lexeme* stream, unsigned count)
{
	unsigned oldSize = lexems.size();
	lexems.resize(lexems.size() + count);
	memcpy(&lexems.data[oldSize], stream, count * sizeof(Lexeme));
}

Lexeme* Lexer::GetStreamStart()
{
	return &lexems[0];
}

unsigned int Lexer::GetStreamSize()
{
	return lexems.size();
}
<|endoftext|>


<commit_before>//===-- Mutex.cpp -----------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lldb/Host/Mutex.h"
#include "lldb/Host/Host.h"

#include <string.h>
#include <stdio.h>
#include <unistd.h>

#if 0
// This logging is way too verbose to enable even for a log channel.
// This logging can be enabled by changing the "#if 0", but should be
// reverted prior to checking in.
#include <cstdio>
#define DEBUG_LOG(fmt, ...) printf(fmt, ## __VA_ARGS__)
#else
#define DEBUG_LOG(fmt, ...)
#endif

// Enable extra mutex error checking
#ifdef LLDB_CONFIGURATION_DEBUG
#define ENABLE_MUTEX_ERROR_CHECKING 1
#endif

using namespace lldb_private;

//----------------------------------------------------------------------
// Default constructor.
//
// This will create a scoped mutex locking object that doesn't have
// a mutex to lock. One will need to be provided using the Reset()
// method.
//----------------------------------------------------------------------
Mutex::Locker::Locker () :
    m_mutex_ptr(NULL)
{
}

//----------------------------------------------------------------------
// Constructor with a Mutex object.
//
// This will create a scoped mutex locking object that extracts the
// mutex owned by "m" and locks it.
//----------------------------------------------------------------------
Mutex::Locker::Locker (Mutex& m) :
    m_mutex_ptr(m.GetMutex())
{
    if (m_mutex_ptr)
        Mutex::Lock (m_mutex_ptr);
}

//----------------------------------------------------------------------
// Constructor with a Mutex object pointer.
//
// This will create a scoped mutex locking object that extracts the
// mutex owned by "m" and locks it.
//----------------------------------------------------------------------
Mutex::Locker::Locker (Mutex* m) :
    m_mutex_ptr(m ? m->GetMutex() : NULL)
{
    if (m_mutex_ptr)
        Mutex::Lock (m_mutex_ptr);
}

//----------------------------------------------------------------------
// Constructor with a raw pthread mutex object pointer.
//
// This will create a scoped mutex locking object that locks "mutex"
//----------------------------------------------------------------------
Mutex::Locker::Locker (pthread_mutex_t *mutex_ptr) :
    m_mutex_ptr(mutex_ptr)
{
    if (m_mutex_ptr)
        Mutex::Lock (m_mutex_ptr);
}

//----------------------------------------------------------------------
// Destructor
//
// Unlocks any owned mutex object (if it is valid).
//----------------------------------------------------------------------
Mutex::Locker::~Locker ()
{
    Reset();
}

//----------------------------------------------------------------------
// Unlock the current mutex in this object (if this owns a valid
// mutex) and lock the new "mutex" object if it is non-NULL.
//----------------------------------------------------------------------
void
Mutex::Locker::Reset (pthread_mutex_t *mutex_ptr)
{
    // We already have this mutex locked or both are NULL...
    if (m_mutex_ptr == mutex_ptr)
        return;

    if (m_mutex_ptr)
        Mutex::Unlock (m_mutex_ptr);

    m_mutex_ptr = mutex_ptr;
    if (m_mutex_ptr)
        Mutex::Lock (m_mutex_ptr);
}

bool
Mutex::Locker::TryLock (pthread_mutex_t *mutex_ptr)
{
    // We already have this mutex locked!
    if (m_mutex_ptr == mutex_ptr)
        return true;

    Reset ();

    if (mutex_ptr)
    {
        if (Mutex::TryLock (mutex_ptr) == 0)
            m_mutex_ptr = mutex_ptr;
    }
    return m_mutex_ptr != NULL;
}

//----------------------------------------------------------------------
// Default constructor.
//
// Creates a pthread mutex with no attributes.
//----------------------------------------------------------------------
Mutex::Mutex () :
    m_mutex()
{
    int err;
    err = ::pthread_mutex_init (&m_mutex, NULL);
    assert(err == 0);
}

//----------------------------------------------------------------------
// Default constructor.
//
// Creates a pthread mutex with "type" as the mutex type.
//----------------------------------------------------------------------
Mutex::Mutex (Mutex::Type type) :
    m_mutex()
{
    int err;
    ::pthread_mutexattr_t attr;
    err = ::pthread_mutexattr_init (&attr);
    assert(err == 0);
    switch (type)
    {
    case eMutexTypeNormal:
#if ENABLE_MUTEX_ERROR_CHECKING
        err = ::pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_ERRORCHECK);
#else
        err = ::pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_NORMAL);
#endif
        break;

    case eMutexTypeRecursive:
        err = ::pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
        break;

    default:
        err = -1;
        break;
    }
    assert(err == 0);
    err = ::pthread_mutex_init (&m_mutex, &attr);
    assert(err == 0);
    err = ::pthread_mutexattr_destroy (&attr);
    assert(err == 0);
}

//----------------------------------------------------------------------
// Destructor.
//
// Destroys the mutex owned by this object.
//----------------------------------------------------------------------
Mutex::~Mutex()
{
    int err;
    err = ::pthread_mutex_destroy (&m_mutex);
#if ENABLE_MUTEX_ERROR_CHECKING
    if (err)
    {
        Host::SetCrashDescriptionWithFormat ("%s error: pthread_mutex_destroy() => err = %i (%s)", __PRETTY_FUNCTION__, err, strerror(err));
        assert(err == 0);
    }
    memset (&m_mutex, '\xba', sizeof(m_mutex));
#endif
}

//----------------------------------------------------------------------
// Mutex get accessor.
//----------------------------------------------------------------------
pthread_mutex_t *
Mutex::GetMutex()
{
    return &m_mutex;
}

int
Mutex::Lock (pthread_mutex_t *mutex_ptr)
{
    DEBUG_LOG ("[%4.4x/%4.4x] pthread_mutex_lock (%p)...\n", Host::GetCurrentProcessID(), Host::GetCurrentThreadID(), mutex_ptr);
    int err = ::pthread_mutex_lock (mutex_ptr);
#if ENABLE_MUTEX_ERROR_CHECKING
    if (err)
    {
        Host::SetCrashDescriptionWithFormat ("%s error: pthread_mutex_destroy(%p) => err = %i (%s)", __PRETTY_FUNCTION__, mutex_ptr, err, strerror(err));
        assert(err == 0);
    }
#endif
    DEBUG_LOG ("[%4.4x/%4.4x] pthread_mutex_lock (%p) => %i\n", Host::GetCurrentProcessID(), Host::GetCurrentThreadID(), mutex_ptr, err);
    return err;
}

int
Mutex::TryLock (pthread_mutex_t *mutex_ptr)
{
    int err = ::pthread_mutex_trylock (mutex_ptr);
    DEBUG_LOG ("[%4.4x/%4.4x] pthread_mutex_trylock (%p) => %i\n", Host::GetCurrentProcessID(), Host::GetCurrentThreadID(), mutex_ptr, err);
    return err;
}

int
Mutex::Unlock (pthread_mutex_t *mutex_ptr)
{
    int err = ::pthread_mutex_unlock (mutex_ptr);
#if ENABLE_MUTEX_ERROR_CHECKING
    if (err)
    {
        Host::SetCrashDescriptionWithFormat ("%s error: pthread_mutex_unlock(%p) => err = %i (%s)", __PRETTY_FUNCTION__, mutex_ptr, err, strerror(err));
        assert(err == 0);
    }
#endif
    DEBUG_LOG ("[%4.4x/%4.4x] pthread_mutex_unlock (%p) => %i\n", Host::GetCurrentProcessID(), Host::GetCurrentThreadID(), mutex_ptr, err);
    return err;
}

//----------------------------------------------------------------------
// Locks the mutex owned by this object, if the mutex is already
// locked, the calling thread will block until the mutex becomes
// available.
//
// RETURNS
//  The error code from the pthread_mutex_lock() function call.
//----------------------------------------------------------------------
int
Mutex::Lock()
{
    return Mutex::Lock (&m_mutex);
}

//----------------------------------------------------------------------
// Attempts to lock the mutex owned by this object without blocking.
// If the mutex is already locked, TryLock() will not block waiting
// for the mutex, but will return an error condition.
//
// RETURNS
//  The error code from the pthread_mutex_trylock() function call.
//----------------------------------------------------------------------
int
Mutex::TryLock()
{
    return Mutex::TryLock (&m_mutex);
}

//----------------------------------------------------------------------
// If the current thread holds the lock on the owned mutex, then
// Unlock() will unlock the mutex. Calling Unlock() on this object
// that the calling thread does not hold will result in undefined
// behavior.
//
// RETURNS
//  The error code from the pthread_mutex_unlock() function call.
//----------------------------------------------------------------------
int
Mutex::Unlock()
{
    return Mutex::Unlock (&m_mutex);
}
<commit_msg>Fix typo.<commit_after>//===-- Mutex.cpp -----------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lldb/Host/Mutex.h"
#include "lldb/Host/Host.h"

#include <string.h>
#include <stdio.h>
#include <unistd.h>

#if 0
// This logging is way too verbose to enable even for a log channel.
// This logging can be enabled by changing the "#if 0", but should be
// reverted prior to checking in.
#include <cstdio>
#define DEBUG_LOG(fmt, ...) printf(fmt, ## __VA_ARGS__)
#else
#define DEBUG_LOG(fmt, ...)
#endif

// Enable extra mutex error checking
#ifdef LLDB_CONFIGURATION_DEBUG
#define ENABLE_MUTEX_ERROR_CHECKING 1
#endif

using namespace lldb_private;

//----------------------------------------------------------------------
// Default constructor.
//
// This will create a scoped mutex locking object that doesn't have
// a mutex to lock. One will need to be provided using the Reset()
// method.
//----------------------------------------------------------------------
Mutex::Locker::Locker () :
    m_mutex_ptr(NULL)
{
}

//----------------------------------------------------------------------
// Constructor with a Mutex object.
//
// This will create a scoped mutex locking object that extracts the
// mutex owned by "m" and locks it.
//----------------------------------------------------------------------
Mutex::Locker::Locker (Mutex& m) :
    m_mutex_ptr(m.GetMutex())
{
    if (m_mutex_ptr)
        Mutex::Lock (m_mutex_ptr);
}

//----------------------------------------------------------------------
// Constructor with a Mutex object pointer.
//
// This will create a scoped mutex locking object that extracts the
// mutex owned by "m" and locks it.
//----------------------------------------------------------------------
Mutex::Locker::Locker (Mutex* m) :
    m_mutex_ptr(m ? m->GetMutex() : NULL)
{
    if (m_mutex_ptr)
        Mutex::Lock (m_mutex_ptr);
}

//----------------------------------------------------------------------
// Constructor with a raw pthread mutex object pointer.
//
// This will create a scoped mutex locking object that locks "mutex"
//----------------------------------------------------------------------
Mutex::Locker::Locker (pthread_mutex_t *mutex_ptr) :
    m_mutex_ptr(mutex_ptr)
{
    if (m_mutex_ptr)
        Mutex::Lock (m_mutex_ptr);
}

//----------------------------------------------------------------------
// Destructor
//
// Unlocks any owned mutex object (if it is valid).
//----------------------------------------------------------------------
Mutex::Locker::~Locker ()
{
    Reset();
}

//----------------------------------------------------------------------
// Unlock the current mutex in this object (if this owns a valid
// mutex) and lock the new "mutex" object if it is non-NULL.
//----------------------------------------------------------------------
void
Mutex::Locker::Reset (pthread_mutex_t *mutex_ptr)
{
    // We already have this mutex locked or both are NULL...
    if (m_mutex_ptr == mutex_ptr)
        return;

    if (m_mutex_ptr)
        Mutex::Unlock (m_mutex_ptr);

    m_mutex_ptr = mutex_ptr;
    if (m_mutex_ptr)
        Mutex::Lock (m_mutex_ptr);
}

bool
Mutex::Locker::TryLock (pthread_mutex_t *mutex_ptr)
{
    // We already have this mutex locked!
    if (m_mutex_ptr == mutex_ptr)
        return true;

    Reset ();

    if (mutex_ptr)
    {
        if (Mutex::TryLock (mutex_ptr) == 0)
            m_mutex_ptr = mutex_ptr;
    }
    return m_mutex_ptr != NULL;
}

//----------------------------------------------------------------------
// Default constructor.
//
// Creates a pthread mutex with no attributes.
//----------------------------------------------------------------------
Mutex::Mutex () :
    m_mutex()
{
    int err;
    err = ::pthread_mutex_init (&m_mutex, NULL);
    assert(err == 0);
}

//----------------------------------------------------------------------
// Default constructor.
//
// Creates a pthread mutex with "type" as the mutex type.
//----------------------------------------------------------------------
Mutex::Mutex (Mutex::Type type) :
    m_mutex()
{
    int err;
    ::pthread_mutexattr_t attr;
    err = ::pthread_mutexattr_init (&attr);
    assert(err == 0);
    switch (type)
    {
    case eMutexTypeNormal:
#if ENABLE_MUTEX_ERROR_CHECKING
        err = ::pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_ERRORCHECK);
#else
        err = ::pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_NORMAL);
#endif
        break;

    case eMutexTypeRecursive:
        err = ::pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
        break;

    default:
        err = -1;
        break;
    }
    assert(err == 0);
    err = ::pthread_mutex_init (&m_mutex, &attr);
    assert(err == 0);
    err = ::pthread_mutexattr_destroy (&attr);
    assert(err == 0);
}

//----------------------------------------------------------------------
// Destructor.
//
// Destroys the mutex owned by this object.
//----------------------------------------------------------------------
Mutex::~Mutex()
{
    int err;
    err = ::pthread_mutex_destroy (&m_mutex);
#if ENABLE_MUTEX_ERROR_CHECKING
    if (err)
    {
        Host::SetCrashDescriptionWithFormat ("%s error: pthread_mutex_destroy() => err = %i (%s)", __PRETTY_FUNCTION__, err, strerror(err));
        assert(err == 0);
    }
    memset (&m_mutex, '\xba', sizeof(m_mutex));
#endif
}

//----------------------------------------------------------------------
// Mutex get accessor.
//----------------------------------------------------------------------
pthread_mutex_t *
Mutex::GetMutex()
{
    return &m_mutex;
}

int
Mutex::Lock (pthread_mutex_t *mutex_ptr)
{
    DEBUG_LOG ("[%4.4x/%4.4x] pthread_mutex_lock (%p)...\n", Host::GetCurrentProcessID(), Host::GetCurrentThreadID(), mutex_ptr);
    int err = ::pthread_mutex_lock (mutex_ptr);
#if ENABLE_MUTEX_ERROR_CHECKING
    if (err)
    {
        Host::SetCrashDescriptionWithFormat ("%s error: pthread_mutex_lock(%p) => err = %i (%s)", __PRETTY_FUNCTION__, mutex_ptr, err, strerror(err));
        assert(err == 0);
    }
#endif
    DEBUG_LOG ("[%4.4x/%4.4x] pthread_mutex_lock (%p) => %i\n", Host::GetCurrentProcessID(), Host::GetCurrentThreadID(), mutex_ptr, err);
    return err;
}

int
Mutex::TryLock (pthread_mutex_t *mutex_ptr)
{
    int err = ::pthread_mutex_trylock (mutex_ptr);
    DEBUG_LOG ("[%4.4x/%4.4x] pthread_mutex_trylock (%p) => %i\n", Host::GetCurrentProcessID(), Host::GetCurrentThreadID(), mutex_ptr, err);
    return err;
}

int
Mutex::Unlock (pthread_mutex_t *mutex_ptr)
{
    int err = ::pthread_mutex_unlock (mutex_ptr);
#if ENABLE_MUTEX_ERROR_CHECKING
    if (err)
    {
        Host::SetCrashDescriptionWithFormat ("%s error: pthread_mutex_unlock(%p) => err = %i (%s)", __PRETTY_FUNCTION__, mutex_ptr, err, strerror(err));
        assert(err == 0);
    }
#endif
    DEBUG_LOG ("[%4.4x/%4.4x] pthread_mutex_unlock (%p) => %i\n", Host::GetCurrentProcessID(), Host::GetCurrentThreadID(), mutex_ptr, err);
    return err;
}

//----------------------------------------------------------------------
// Locks the mutex owned by this object, if the mutex is already
// locked, the calling thread will block until the mutex becomes
// available.
//
// RETURNS
//  The error code from the pthread_mutex_lock() function call.
//----------------------------------------------------------------------
int
Mutex::Lock()
{
    return Mutex::Lock (&m_mutex);
}

//----------------------------------------------------------------------
// Attempts to lock the mutex owned by this object without blocking.
// If the mutex is already locked, TryLock() will not block waiting
// for the mutex, but will return an error condition.
//
// RETURNS
//  The error code from the pthread_mutex_trylock() function call.
//----------------------------------------------------------------------
int
Mutex::TryLock()
{
    return Mutex::TryLock (&m_mutex);
}

//----------------------------------------------------------------------
// If the current thread holds the lock on the owned mutex, then
// Unlock() will unlock the mutex. Calling Unlock() on this object
// that the calling thread does not hold will result in undefined
// behavior.
//
// RETURNS
//  The error code from the pthread_mutex_unlock() function call.
//----------------------------------------------------------------------
int
Mutex::Unlock()
{
    return Mutex::Unlock (&m_mutex);
}
<|endoftext|>


<commit_before>#include "palabos3D.h"
#include "palabos3D.hh"
#include <vector>
#include <cmath>
#include <time.h>

using namespace plb;
using namespace plb::descriptors;
using namespace std;

typedef double T;
typedef Array<T,3> Velocity;
//#define DESCRIPTOR descriptors::D3Q27Descriptor
#define DESCRIPTOR MRTD3Q19Descriptor
 typedef MRTdynamics<T,DESCRIPTOR> BackgroundDynamics;
 typedef AnechoicMRTdynamics<T,DESCRIPTOR> AnechoicBackgroundDynamics;

// ---------------------------------------------
// Includes of acoustics resources
#include "acoustics/acoustics3D.h"
using namespace plb_acoustics_3D;
// ---------------------------------------------

const T rho0 = 1;
const T drho = rho0/10;

// Get current date/time, format is YYYY-MM-DD.HH:mm:ss
const std::string currentDateTime() {
    time_t     now = time(0);
    struct tm  tstruct;
    char       buf[80];
    tstruct = *localtime(&now);
    // Visit http://en.cppreference.com/w/cpp/chrono/c/strftime
    // for more information about date/time format
    strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct);

    return buf;
}

void writeGifs(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, plint iter){
    const plint nx = lattice.getNx();
    const plint ny = lattice.getNy();
    const plint nz = lattice.getNz();

    const plint imSize = 600;
    ImageWriter<T> imageWriter("leeloo");

    Box3D slice(0, nx-1, 0, ny-1, nz/2, nz/2);
    //imageWriter.writeGif(createFileName("u", iT, 6),
     //*computeDensity(lattice), );

    imageWriter.writeGif( createFileName("rho", iter, 6),
    *computeDensity(lattice, slice),
    (T) rho0 - drho/1000000, (T) rho0 + drho/1000000, imSize, imSize);
}

void writeVTK(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, plint iter){
        VtkImageOutput3D<T> vtkOut(createFileName("vtk", iter, 6), 1.);
        vtkOut.writeData<float>(*computeDensity(lattice), "density", 1.);
        //vtkOut.writeData<3,float>(*computeVelocity(lattice), "velocity", 1.);
}

void build_duct(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, plint nx, plint ny,
    Array<plint,3> position, plint radius, plint length, plint thickness, T omega){
    length += 4;
    // Duct is constructed along the Z direction
    //plint size_square = 50;
    plint size_square = 2*radius;
    plint radius_intern = radius - thickness;
    for (plint x = position[0] - radius; x < nx/2 + size_square/2; ++x){
        for (plint y = position[1] - radius; y < ny/2 + size_square/2; ++y){
            for (plint z = position[2]; z < length + position[2]; ++z){

                if (radius*radius > (x-nx/2)*(x-nx/2) + (y-ny/2)*(y-ny/2)){
                    //pcout << "passou" << endl;
                    DotList3D points_to_aplly_dynamics;
                    points_to_aplly_dynamics.addDot(Dot3D(x,y,z));
                    //OnLatticeBoundaryCondition3D<T,DESCRIPTOR> *bc = createLocalBoundaryCondition3D<T,DESCRIPTOR>();
                    //bc->setVelocityConditionOnBlockBoundaries(lattice, points_to_aplly_dynamics, boundary::freeslip);
                    defineDynamics(lattice, points_to_aplly_dynamics, new BounceBack<T,DESCRIPTOR>(0));
                }
                // extrude
                if (radius_intern*radius_intern > (x-nx/2)*(x-nx/2) + (y-ny/2)*(y-ny/2) && z > position[2] + 2){
                    //pcout << "passou" << endl;
                    DotList3D points_to_aplly_dynamics;
                    points_to_aplly_dynamics.addDot(Dot3D(x,y,z));
                    defineDynamics(lattice, points_to_aplly_dynamics, new BackgroundDynamics(omega));
                }

            }
        }
    }

}

int main(int argc, char **argv){
    plbInit(&argc, &argv);

    //const plint length_domain = 420;
    const plint radius = 20;
    const plint diameter = 2*radius;
    //const plint length_domain = 150;
    const plint nx = 12*diameter + 60;
    const plint ny = 12*diameter + 60;
    const plint position_duct_z = 30;
    const plint nz = 9*diameter + 60;
    const T lattice_speed_sound = 1/sqrt(3);
    const T omega = 1.985;
    const plint maxT = 15000;
    Array<T,3> u0(0, 0, 0);

    //const plint maxT = 2*120/lattice_speed_sound;
    const plint maxT_final_source = maxT - nz*sqrt(3);
    const T ka_max = 2.5;
    const T ka_min = 0;
    const T cs2 = lattice_speed_sound*lattice_speed_sound;
    clock_t t;

    // Saving a propery directory
    std::string fNameOut = currentDateTime() + "+tmp";
    std::string command = "mkdir -p " + fNameOut;
    char to_char_command[1024];
    strcpy(to_char_command, command.c_str());
    system(to_char_command);
    global::directories().setOutputDir(fNameOut+"/");

    // Setting anechoic dynamics like this way
    MultiBlockLattice3D<T, DESCRIPTOR> lattice(nx, ny, nz,  new AnechoicBackgroundDynamics(omega));
    defineDynamics(lattice, lattice.getBoundingBox(), new BackgroundDynamics(omega));

    pcout << "Creation of the lattice. Time max: " << maxT << endl;

    pcout << getMultiBlockInfo(lattice) << std::endl;

    // Switch off periodicity.
    lattice.periodicity().toggleAll(false);

    pcout << "Initilization of rho and u." << endl;
    initializeAtEquilibrium(lattice, lattice.getBoundingBox(), rho0 , u0);

    /*plint size_square = 10;
    Box3D square(
    35, 35 + size_square,
    ny/2 - size_square/2, ny/2 + size_square/2,
    nz/2 - size_square/2, nz/2 + size_square/2);
    defineDynamics(lattice, square, new BounceBack<T,DESCRIPTOR>((T)0));*/

    /*(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, plint nx, plint ny,
    Array<plint,3> position, plint radius, plint length, plint thickness)*/
    Array<plint,3> position(nx/2, ny/2, position_duct_z);
    plint length_duct = 3*diameter;
    plint thickness_duct = 2;
    build_duct(lattice, nx, ny, position, radius, length_duct, thickness_duct, omega);

    T rhoBar_target = 0;
    //const T mach_number = 0.2;
    //const T velocity_flow = mach_number*lattice_speed_sound;
    Array<T,3> j_target(0, 0, 0);
    T size_anechoic_buffer = 30;
    defineAnechoicMRTBoards(nx, ny, nz, lattice, size_anechoic_buffer,
      omega, j_target, j_target, j_target, j_target, j_target, j_target,
      rhoBar_target);

    lattice.initialize();

    pcout << std::endl << "Voxelizing the domain." << std::endl;

    pcout << "Simulation begins" << endl;

    // Setting probes
    plint radius_probe = (radius - 1)/sqrt(2);
    // half size
    plint position_z_3r = position[2] + length_duct - 3*radius;
    Box3D surface_probe_3r(nx/2 - radius_probe/sqrt(2),
            nx/2 + radius_probe/sqrt(2),
            ny/2 - radius_probe/sqrt(2),
            ny/2 + radius_probe/sqrt(2),
            position_z_3r, position_z_3r);

    //plint position_z_4r = position[2] + length_duct - 4*radius;
    plint position_z_boca = position[2] + length_duct;
    Box3D surface_probe_boca(nx/2 - radius_probe/sqrt(2),
            nx/2 + radius_probe/sqrt(2),
            ny/2 - radius_probe/sqrt(2),
            ny/2 + radius_probe/sqrt(2),
            position_z_boca, position_z_boca);

    std::string pressures_boca_string = fNameOut+"/history_pressures_boca.dat";
    char to_char_pressures_boca[1024];
    strcpy(to_char_pressures_boca, pressures_boca_string.c_str());
    plb_ofstream history_pressures_boca(to_char_pressures_boca);

    std::string velocities_boca_string = fNameOut+"/history_velocities_boca.dat";
    char to_char_velocities_boca[1024];
    strcpy(to_char_velocities_boca, velocities_boca_string.c_str());
    plb_ofstream history_velocities_boca(to_char_velocities_boca);

    std::string pressures_3r_string = fNameOut+"/history_pressures_3r.dat";
    char to_char_pressures_3r[1024];
    strcpy(to_char_pressures_3r, pressures_3r_string.c_str());
    plb_ofstream history_pressures_3r(to_char_pressures_3r);

    std::string velocities_3r_string = fNameOut+"/history_velocities_3r.dat";
    char to_char_velocities_3r[1024];
    strcpy(to_char_velocities_3r, velocities_3r_string.c_str());
    plb_ofstream history_velocities_3r(to_char_velocities_3r);

    t = clock();
    std::string AllSimulationInfo_string = fNameOut + "/AllSimulationInfo.txt";
    char to_char_AllSimulationInfo[1024];
    strcpy(to_char_AllSimulationInfo, AllSimulationInfo_string.c_str());
    plb_ofstream AllSimulationInfo(to_char_AllSimulationInfo);

    std::string title = "\nSimulacao para testar a questao da inercia.\n";
    AllSimulationInfo << endl
    << title << endl
    << "Dados da simulação" << endl
    << "Lattice:" << endl << endl
    << "nx: " << nx << " ny: " << ny << " nz: " << nz << endl
    << " omega: " << omega << endl << endl
    << "Tempos: " << endl
    << "Total Time step: " << maxT << endl
    << "Discretizacao: " << radius/thickness_duct << endl
    << "Tamanho duto: " << length_duct << endl
    << "Posicao do duto: " << position[2] << endl;

    for (plint iT=0; iT<maxT; ++iT){
        //pcout << " foi 1 " << iT << endl;
        if (iT <= maxT_final_source){
            //drho*sin(2*M_PI*(lattice_speed_sound/20)*iT);
            //drho*cos((lattice_speed_sound/radius)*(ka_max*((maxT-iT)/maxT)));

            T initial_frequency = ka_min*lattice_speed_sound/(2*M_PI*radius);
            T frequency_max_lattice = ka_max*lattice_speed_sound/(2*M_PI*radius);
            T variation_frequency = (frequency_max_lattice - initial_frequency)/maxT_final_source;
            T frequency_function = initial_frequency*iT + (variation_frequency*iT*iT)/2;
            T phase = 2*M_PI*frequency_function;
            T chirp_hand = 1. + drho*sin(phase);

            T rho_changing = 1. + drho*sin(2*M_PI*(lattice_speed_sound/20)*iT);
            //Box3D impulse(nx/2, nx/2, ny/2, ny/2, position_z_3r, position_z_3r);
            plint source_radius = radius - 1;
            Box3D place_source(position[0] - source_radius/sqrt(2),
                position[0] + source_radius/sqrt(2),
                position[1] - source_radius/sqrt(2),
                position[1] + source_radius/sqrt(2),
                position[2] + 3, position[2] + 8);
            //Box3D impulse(centerLB[0] + 10, centerLB[0] + 10, ny/2, ny/2, nz/2, nz/2);
            initializeAtEquilibrium(lattice, place_source, rho_changing, u0);
        }else{
            plint source_radius = radius - 1;
            Box3D place_source(position[0] - source_radius/sqrt(2),
                position[0] + source_radius/sqrt(2),
                position[1] - source_radius/sqrt(2),
                position[1] + source_radius/sqrt(2),
                position[2] + 3, position[2] + 8);
            initializeAtEquilibrium(lattice, place_source, rho0, u0);
        }

        if (iT % 10 == 0 && iT>0) {
            pcout << "Iteration " << iT << endl;
        }

        if (iT % 1000 == 0) {
            //writeGifs(lattice,iT);
            writeVTK(lattice, iT);
        }

        // extract values of pressure and velocities
        history_pressures_3r << setprecision(10) << (computeAverageDensity(lattice, surface_probe_3r) - rho0)*cs2 << endl;
        history_pressures_boca << setprecision(10) << (computeAverageDensity(lattice, surface_probe_boca) - rho0)*cs2 << endl;

        std::auto_ptr<MultiScalarField3D<T> > velocity_boca(plb::computeVelocityComponent(lattice, surface_probe_boca, 2));
        history_velocities_boca << setprecision(10) <<
        computeAverage(*velocity_boca, surface_probe_boca)/lattice_speed_sound << endl;
        std::auto_ptr<MultiScalarField3D<T> > velocity_3r(plb::computeVelocityComponent(lattice, surface_probe_3r, 2));
        history_velocities_boca << setprecision(10) <<
        computeAverage(*velocity_3r, surface_probe_3r)/lattice_speed_sound << endl;

        lattice.collideAndStream();
    }

    t = (clock() - t)/CLOCKS_PER_SEC;
    AllSimulationInfo << endl << "Execution time: " << t << " segundos" << endl << endl;

    pcout << "End of simulation at iteration " << endl;
}
<commit_msg>Adding correction on chirp<commit_after>#include "palabos3D.h"
#include "palabos3D.hh"
#include <vector>
#include <cmath>
#include <time.h>

using namespace plb;
using namespace plb::descriptors;
using namespace std;

typedef double T;
typedef Array<T,3> Velocity;
//#define DESCRIPTOR descriptors::D3Q27Descriptor
#define DESCRIPTOR MRTD3Q19Descriptor
 typedef MRTdynamics<T,DESCRIPTOR> BackgroundDynamics;
 typedef AnechoicMRTdynamics<T,DESCRIPTOR> AnechoicBackgroundDynamics;

// ---------------------------------------------
// Includes of acoustics resources
#include "acoustics/acoustics3D.h"
using namespace plb_acoustics_3D;
// ---------------------------------------------

const T rho0 = 1;
const T drho = rho0/10;

// Get current date/time, format is YYYY-MM-DD.HH:mm:ss
const std::string currentDateTime() {
    time_t     now = time(0);
    struct tm  tstruct;
    char       buf[80];
    tstruct = *localtime(&now);
    // Visit http://en.cppreference.com/w/cpp/chrono/c/strftime
    // for more information about date/time format
    strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct);

    return buf;
}

void writeGifs(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, plint iter){
    const plint nx = lattice.getNx();
    const plint ny = lattice.getNy();
    const plint nz = lattice.getNz();

    const plint imSize = 600;
    ImageWriter<T> imageWriter("leeloo");

    Box3D slice(0, nx-1, 0, ny-1, nz/2, nz/2);
    //imageWriter.writeGif(createFileName("u", iT, 6),
     //*computeDensity(lattice), );

    imageWriter.writeGif( createFileName("rho", iter, 6),
    *computeDensity(lattice, slice),
    (T) rho0 - drho/1000000, (T) rho0 + drho/1000000, imSize, imSize);
}

void writeVTK(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, plint iter){
        VtkImageOutput3D<T> vtkOut(createFileName("vtk", iter, 6), 1.);
        vtkOut.writeData<float>(*computeDensity(lattice), "density", 1.);
        //vtkOut.writeData<3,float>(*computeVelocity(lattice), "velocity", 1.);
}

void build_duct(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, plint nx, plint ny,
    Array<plint,3> position, plint radius, plint length, plint thickness, T omega){
    length += 4;
    // Duct is constructed along the Z direction
    //plint size_square = 50;
    plint size_square = 2*radius;
    plint radius_intern = radius - thickness;
    for (plint x = position[0] - radius; x < nx/2 + size_square/2; ++x){
        for (plint y = position[1] - radius; y < ny/2 + size_square/2; ++y){
            for (plint z = position[2]; z < length + position[2]; ++z){

                if (radius*radius > (x-nx/2)*(x-nx/2) + (y-ny/2)*(y-ny/2)){
                    //pcout << "passou" << endl;
                    DotList3D points_to_aplly_dynamics;
                    points_to_aplly_dynamics.addDot(Dot3D(x,y,z));
                    //OnLatticeBoundaryCondition3D<T,DESCRIPTOR> *bc = createLocalBoundaryCondition3D<T,DESCRIPTOR>();
                    //bc->setVelocityConditionOnBlockBoundaries(lattice, points_to_aplly_dynamics, boundary::freeslip);
                    defineDynamics(lattice, points_to_aplly_dynamics, new BounceBack<T,DESCRIPTOR>(0));
                }
                // extrude
                if (radius_intern*radius_intern > (x-nx/2)*(x-nx/2) + (y-ny/2)*(y-ny/2) && z > position[2] + 2){
                    //pcout << "passou" << endl;
                    DotList3D points_to_aplly_dynamics;
                    points_to_aplly_dynamics.addDot(Dot3D(x,y,z));
                    defineDynamics(lattice, points_to_aplly_dynamics, new BackgroundDynamics(omega));
                }

            }
        }
    }

}

int main(int argc, char **argv){
    plbInit(&argc, &argv);

    //const plint length_domain = 420;
    const plint radius = 20;
    const plint diameter = 2*radius;
    //const plint length_domain = 150;
    const plint nx = 12*diameter + 60;
    const plint ny = 12*diameter + 60;
    const plint position_duct_z = 30;
    const plint nz = 9*diameter + 60;
    const T lattice_speed_sound = 1/sqrt(3);
    const T omega = 1.985;
    const plint maxT = 15000;
    Array<T,3> u0(0, 0, 0);

    //const plint maxT = 2*120/lattice_speed_sound;
    const plint maxT_final_source = maxT - nz*sqrt(3);
    const T ka_max = 2.5;
    const T ka_min = 0;
    const T cs2 = lattice_speed_sound*lattice_speed_sound;
    clock_t t;

    // Saving a propery directory
    std::string fNameOut = currentDateTime() + "+tmp";
    std::string command = "mkdir -p " + fNameOut;
    char to_char_command[1024];
    strcpy(to_char_command, command.c_str());
    system(to_char_command);
    global::directories().setOutputDir(fNameOut+"/");

    // Setting anechoic dynamics like this way
    MultiBlockLattice3D<T, DESCRIPTOR> lattice(nx, ny, nz,  new AnechoicBackgroundDynamics(omega));
    defineDynamics(lattice, lattice.getBoundingBox(), new BackgroundDynamics(omega));

    pcout << "Creation of the lattice. Time max: " << maxT << endl;

    pcout << getMultiBlockInfo(lattice) << std::endl;

    // Switch off periodicity.
    lattice.periodicity().toggleAll(false);

    pcout << "Initilization of rho and u." << endl;
    initializeAtEquilibrium(lattice, lattice.getBoundingBox(), rho0 , u0);

    /*plint size_square = 10;
    Box3D square(
    35, 35 + size_square,
    ny/2 - size_square/2, ny/2 + size_square/2,
    nz/2 - size_square/2, nz/2 + size_square/2);
    defineDynamics(lattice, square, new BounceBack<T,DESCRIPTOR>((T)0));*/

    /*(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, plint nx, plint ny,
    Array<plint,3> position, plint radius, plint length, plint thickness)*/
    Array<plint,3> position(nx/2, ny/2, position_duct_z);
    plint length_duct = 3*diameter;
    plint thickness_duct = 2;
    build_duct(lattice, nx, ny, position, radius, length_duct, thickness_duct, omega);

    T rhoBar_target = 0;
    //const T mach_number = 0.2;
    //const T velocity_flow = mach_number*lattice_speed_sound;
    Array<T,3> j_target(0, 0, 0);
    T size_anechoic_buffer = 30;
    defineAnechoicMRTBoards(nx, ny, nz, lattice, size_anechoic_buffer,
      omega, j_target, j_target, j_target, j_target, j_target, j_target,
      rhoBar_target);

    lattice.initialize();

    pcout << std::endl << "Voxelizing the domain." << std::endl;

    pcout << "Simulation begins" << endl;

    // Setting probes
    plint radius_probe = (radius - 1)/sqrt(2);
    // half size
    plint position_z_3r = position[2] + length_duct - 3*radius;
    Box3D surface_probe_3r(nx/2 - radius_probe/sqrt(2),
            nx/2 + radius_probe/sqrt(2),
            ny/2 - radius_probe/sqrt(2),
            ny/2 + radius_probe/sqrt(2),
            position_z_3r, position_z_3r);

    //plint position_z_4r = position[2] + length_duct - 4*radius;
    plint position_z_boca = position[2] + length_duct;
    Box3D surface_probe_boca(nx/2 - radius_probe/sqrt(2),
            nx/2 + radius_probe/sqrt(2),
            ny/2 - radius_probe/sqrt(2),
            ny/2 + radius_probe/sqrt(2),
            position_z_boca, position_z_boca);

    std::string pressures_boca_string = fNameOut+"/history_pressures_boca.dat";
    char to_char_pressures_boca[1024];
    strcpy(to_char_pressures_boca, pressures_boca_string.c_str());
    plb_ofstream history_pressures_boca(to_char_pressures_boca);

    std::string velocities_boca_string = fNameOut+"/history_velocities_boca.dat";
    char to_char_velocities_boca[1024];
    strcpy(to_char_velocities_boca, velocities_boca_string.c_str());
    plb_ofstream history_velocities_boca(to_char_velocities_boca);

    std::string pressures_3r_string = fNameOut+"/history_pressures_3r.dat";
    char to_char_pressures_3r[1024];
    strcpy(to_char_pressures_3r, pressures_3r_string.c_str());
    plb_ofstream history_pressures_3r(to_char_pressures_3r);

    std::string velocities_3r_string = fNameOut+"/history_velocities_3r.dat";
    char to_char_velocities_3r[1024];
    strcpy(to_char_velocities_3r, velocities_3r_string.c_str());
    plb_ofstream history_velocities_3r(to_char_velocities_3r);

    t = clock();
    std::string AllSimulationInfo_string = fNameOut + "/AllSimulationInfo.txt";
    char to_char_AllSimulationInfo[1024];
    strcpy(to_char_AllSimulationInfo, AllSimulationInfo_string.c_str());
    plb_ofstream AllSimulationInfo(to_char_AllSimulationInfo);

    std::string title = "\nSimulacao para testar a questao da inercia.\n";
    AllSimulationInfo << endl
    << title << endl
    << "Dados da simulação" << endl
    << "Lattice:" << endl << endl
    << "nx: " << nx << " ny: " << ny << " nz: " << nz << endl
    << " omega: " << omega << endl << endl
    << "Tempos: " << endl
    << "Total Time step: " << maxT << endl
    << "Discretizacao: " << radius/thickness_duct << endl
    << "Tamanho duto: " << length_duct << endl
    << "Posicao do duto: " << position[2] << endl;

    for (plint iT=0; iT<maxT; ++iT){
        //pcout << " foi 1 " << iT << endl;
        if (iT <= maxT_final_source){
            //drho*sin(2*M_PI*(lattice_speed_sound/20)*iT);
            //drho*cos((lattice_speed_sound/radius)*(ka_max*((maxT-iT)/maxT)));

            T initial_frequency = ka_min*lattice_speed_sound/(2*M_PI*radius);
            T frequency_max_lattice = ka_max*lattice_speed_sound/(2*M_PI*radius);
            T variation_frequency = (frequency_max_lattice - initial_frequency)/maxT_final_source;
            T frequency_function = initial_frequency*iT + (variation_frequency*iT*iT)/2;
            T phase = 2*M_PI*frequency_function;
            T chirp_hand = 1. + drho*sin(phase);

            //T rho_changing = 1. + drho*sin(2*M_PI*(lattice_speed_sound/20)*iT);
            //Box3D impulse(nx/2, nx/2, ny/2, ny/2, position_z_3r, position_z_3r);
            plint source_radius = radius - 1;
            Box3D place_source(position[0] - source_radius/sqrt(2),
                position[0] + source_radius/sqrt(2),
                position[1] - source_radius/sqrt(2),
                position[1] + source_radius/sqrt(2),
                position[2] + 3, position[2] + 8);
            //Box3D impulse(centerLB[0] + 10, centerLB[0] + 10, ny/2, ny/2, nz/2, nz/2);
            initializeAtEquilibrium(lattice, place_source, chirp_hand, u0);
        }else{
            plint source_radius = radius - 1;
            Box3D place_source(position[0] - source_radius/sqrt(2),
                position[0] + source_radius/sqrt(2),
                position[1] - source_radius/sqrt(2),
                position[1] + source_radius/sqrt(2),
                position[2] + 3, position[2] + 8);
            initializeAtEquilibrium(lattice, place_source, rho0, u0);
        }

        if (iT % 10 == 0 && iT>0) {
            pcout << "Iteration " << iT << endl;
        }

        if (iT % 1000 == 0) {
            //writeGifs(lattice,iT);
            writeVTK(lattice, iT);
        }

        // extract values of pressure and velocities
        history_pressures_3r << setprecision(10) << (computeAverageDensity(lattice, surface_probe_3r) - rho0)*cs2 << endl;
        history_pressures_boca << setprecision(10) << (computeAverageDensity(lattice, surface_probe_boca) - rho0)*cs2 << endl;

        std::auto_ptr<MultiScalarField3D<T> > velocity_boca(plb::computeVelocityComponent(lattice, surface_probe_boca, 2));
        history_velocities_boca << setprecision(10) <<
        computeAverage(*velocity_boca, surface_probe_boca)/lattice_speed_sound << endl;
        std::auto_ptr<MultiScalarField3D<T> > velocity_3r(plb::computeVelocityComponent(lattice, surface_probe_3r, 2));
        history_velocities_boca << setprecision(10) <<
        computeAverage(*velocity_3r, surface_probe_3r)/lattice_speed_sound << endl;

        lattice.collideAndStream();
    }

    t = (clock() - t)/CLOCKS_PER_SEC;
    AllSimulationInfo << endl << "Execution time: " << t << " segundos" << endl << endl;

    pcout << "End of simulation at iteration " << endl;
}
<|endoftext|>


<commit_before>/*** Copyright (c), The Regents of the University of California            ***
 *** For more information please refer to files in the COPYRIGHT directory ***/
/* rsFileOpendir.c - server routine that handles the fileOpendir
 * API
 */

/* script generated code */
#include "fileOpendir.hpp"
#include "miscServerFunct.hpp"
#include "rsGlobalExtern.hpp"

// =-=-=-=-=-=-=-
#include "irods_log.hpp"
#include "irods_collection_object.hpp"
#include "irods_resource_backport.hpp"
#include "irods_stacktrace.hpp"

int
rsFileOpendir( rsComm_t *rsComm, fileOpendirInp_t *fileOpendirInp ) {
    rodsServerHost_t *rodsServerHost;
    int remoteFlag;
    int fileInx;
    int status;
    void *dirPtr = NULL;

    //remoteFlag = resolveHost (&fileOpendirInp->addr, &rodsServerHost);
    irods::error ret = irods::get_host_for_hier_string( fileOpendirInp->resc_hier_, remoteFlag, rodsServerHost );
    if ( !ret.ok() ) {
        irods::log( PASSMSG( "failed in call to irods::get_host_for_hier_string", ret ) );
        return -1;
    }

    if ( remoteFlag == LOCAL_HOST ) {
        status = _rsFileOpendir( rsComm, fileOpendirInp, &dirPtr );
    }
    else if ( remoteFlag == REMOTE_HOST ) {
        status = remoteFileOpendir( rsComm, fileOpendirInp, rodsServerHost );
    }
    else {
        if ( remoteFlag < 0 ) {
            return ( remoteFlag );
        }
        else {
            rodsLog( LOG_NOTICE,
                     "rsFileOpendir: resolveHost returned unrecognized value %d",
                     remoteFlag );
            return ( SYS_UNRECOGNIZED_REMOTE_FLAG );
        }
    }

    if ( status < 0 ) {
        return ( status );
    }

    fileInx = allocAndFillFileDesc( rodsServerHost, fileOpendirInp->objPath, fileOpendirInp->dirName, fileOpendirInp->resc_hier_,
                                    status, 0 );
    FileDesc[fileInx].driverDep = dirPtr;

    return ( fileInx );
}

int
remoteFileOpendir( rsComm_t *rsComm, fileOpendirInp_t *fileOpendirInp,
                   rodsServerHost_t *rodsServerHost ) {
    int fileInx;
    int status;

    if ( rodsServerHost == NULL ) {
        rodsLog( LOG_NOTICE,
                 "remoteFileOpendir: Invalid rodsServerHost" );
        return SYS_INVALID_SERVER_HOST;
    }

    if ( ( status = svrToSvrConnect( rsComm, rodsServerHost ) ) < 0 ) {
        return status;
    }

    fileInx = rcFileOpendir( rodsServerHost->conn, fileOpendirInp );

    if ( fileInx < 0 ) {
        rodsLog( LOG_NOTICE,
                 "remoteFileOpendir: rcFileOpendir failed for %s",
                 fileOpendirInp->dirName );
    }

    return fileInx;
}

// =-=-=-=-=-=-=-
// _rsFileOpendir - this the local version of rsFileOpendir.
int _rsFileOpendir(
    rsComm_t*         _comm,
    fileOpendirInp_t* _opendir_inp,
    void**            _dir_ptr ) {
    // =-=-=-=-=-=-=-
    // FIXME:: XXXX need to check resource permission and vault permission
    // when RCAT is available

    // =-=-=-=-=-=-=-
    // make the call to opendir via resource plugin
    irods::collection_object_ptr coll_obj(
        new irods::collection_object(
            _opendir_inp->dirName,
            _opendir_inp->resc_hier_,
            0, 0 ) );
    irods::error opendir_err = fileOpendir( _comm, coll_obj );

    // =-=-=-=-=-=-=-
    // log an error, if any
    if ( !opendir_err.ok() ) {
        std::stringstream msg;
        msg << "fileOpendir failed for [";
        msg << _opendir_inp->dirName;
        msg << "]";
        irods::error err = PASSMSG( msg.str(), opendir_err );
        irods::log( err );
    }

    ( *_dir_ptr ) = coll_obj->directory_pointer(); // JMC -- TEMPORARY

    return ( opendir_err.code() );

} // _rsFileOpendir

<commit_msg>[#2212] CID25904:<commit_after>/*** Copyright (c), The Regents of the University of California            ***
 *** For more information please refer to files in the COPYRIGHT directory ***/
/* rsFileOpendir.c - server routine that handles the fileOpendir
 * API
 */

/* script generated code */
#include "fileOpendir.hpp"
#include "miscServerFunct.hpp"
#include "rsGlobalExtern.hpp"

// =-=-=-=-=-=-=-
#include "irods_log.hpp"
#include "irods_collection_object.hpp"
#include "irods_resource_backport.hpp"
#include "irods_stacktrace.hpp"

int
rsFileOpendir( rsComm_t *rsComm, fileOpendirInp_t *fileOpendirInp ) {
    rodsServerHost_t *rodsServerHost;
    int remoteFlag;
    int fileInx;
    int status;
    void *dirPtr = NULL;

    //remoteFlag = resolveHost (&fileOpendirInp->addr, &rodsServerHost);
    irods::error ret = irods::get_host_for_hier_string( fileOpendirInp->resc_hier_, remoteFlag, rodsServerHost );
    if ( !ret.ok() ) {
        irods::log( PASSMSG( "failed in call to irods::get_host_for_hier_string", ret ) );
        return -1;
    }

    if ( remoteFlag == LOCAL_HOST ) {
        status = _rsFileOpendir( rsComm, fileOpendirInp, &dirPtr );
    }
    else if ( remoteFlag == REMOTE_HOST ) {
        status = remoteFileOpendir( rsComm, fileOpendirInp, rodsServerHost );
    }
    else {
        if ( remoteFlag < 0 ) {
            return ( remoteFlag );
        }
        else {
            rodsLog( LOG_NOTICE,
                     "rsFileOpendir: resolveHost returned unrecognized value %d",
                     remoteFlag );
            return ( SYS_UNRECOGNIZED_REMOTE_FLAG );
        }
    }

    if ( status < 0 ) {
        return ( status );
    }

    fileInx = allocAndFillFileDesc( rodsServerHost, fileOpendirInp->objPath, fileOpendirInp->dirName, fileOpendirInp->resc_hier_,
                                    status, 0 );
    if ( fileInx < 0 ) {
        rodsLog( LOG_NOTICE, "call to allocAndFileDesc failed with status %ji", ( intmax_t ) fileInx );
        return fileInx;
    }
    FileDesc[fileInx].driverDep = dirPtr;

    return ( fileInx );
}

int
remoteFileOpendir( rsComm_t *rsComm, fileOpendirInp_t *fileOpendirInp,
                   rodsServerHost_t *rodsServerHost ) {
    int fileInx;
    int status;

    if ( rodsServerHost == NULL ) {
        rodsLog( LOG_NOTICE,
                 "remoteFileOpendir: Invalid rodsServerHost" );
        return SYS_INVALID_SERVER_HOST;
    }

    if ( ( status = svrToSvrConnect( rsComm, rodsServerHost ) ) < 0 ) {
        return status;
    }

    fileInx = rcFileOpendir( rodsServerHost->conn, fileOpendirInp );

    if ( fileInx < 0 ) {
        rodsLog( LOG_NOTICE,
                 "remoteFileOpendir: rcFileOpendir failed for %s",
                 fileOpendirInp->dirName );
    }

    return fileInx;
}

// =-=-=-=-=-=-=-
// _rsFileOpendir - this the local version of rsFileOpendir.
int _rsFileOpendir(
    rsComm_t*         _comm,
    fileOpendirInp_t* _opendir_inp,
    void**            _dir_ptr ) {
    // =-=-=-=-=-=-=-
    // FIXME:: XXXX need to check resource permission and vault permission
    // when RCAT is available

    // =-=-=-=-=-=-=-
    // make the call to opendir via resource plugin
    irods::collection_object_ptr coll_obj(
        new irods::collection_object(
            _opendir_inp->dirName,
            _opendir_inp->resc_hier_,
            0, 0 ) );
    irods::error opendir_err = fileOpendir( _comm, coll_obj );

    // =-=-=-=-=-=-=-
    // log an error, if any
    if ( !opendir_err.ok() ) {
        std::stringstream msg;
        msg << "fileOpendir failed for [";
        msg << _opendir_inp->dirName;
        msg << "]";
        irods::error err = PASSMSG( msg.str(), opendir_err );
        irods::log( err );
    }

    ( *_dir_ptr ) = coll_obj->directory_pointer(); // JMC -- TEMPORARY

    return ( opendir_err.code() );

} // _rsFileOpendir

<|endoftext|>


<commit_before>#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <stdlib.h>
#include <iostream>

cv::Rect const getRegionOfInterest(cv::Mat const &imgThreshold){
	cv::Mat tmp;
	imgThreshold.copyTo(tmp); // i don't know why this is necessary :(
	cv::Rect boundingRectangle;
	std::vector<std::vector<cv::Point>> contours;
	cv::findContours(tmp, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
	if(contours.size() > 0){ //found something
		int maxArea = 0;
		for(int i = 0; i < contours.size(); i++){
			cv::Rect tmpRect = cv::boundingRect(contours[i]);
			if(tmpRect.area() > maxArea){
				boundingRectangle = tmpRect;
				maxArea = tmpRect.area();
			}
		}
	}
	return boundingRectangle;
}

void morphOps(cv::Mat &img, cv::Mat const &structuringElement){
	//morphological opening (remove small objects from the foreground)
	cv::erode(img, img, structuringElement);
	cv::dilate(img, img, structuringElement);
	//morphological closing (fill small holes in the foreground)
	cv::dilate(img, img, structuringElement);
	cv::erode(img, img, structuringElement);
}

int main(int argc, char* argv[]){
	using namespace cv;

	if(argc != 2){
		std::cerr << "usage: ./track_detection <filename>" << std::endl;
		return EXIT_FAILURE;
	}

	//namedWindow("Control", CV_WINDOW_AUTOSIZE);
	//int lowH = 0, highH = 179;
	//int lowS = 0, highS = 255;
	//int lowV = 0, highV = 255;

	//cvCreateTrackbar("LowH", "Control", &lowH, 179);
	//cvCreateTrackbar("HighH", "Control", &highH, 179);

	//cvCreateTrackbar("LowS", "Control", &lowS, 255);
	//cvCreateTrackbar("HighS", "Control", &highS, 255);

	//cvCreateTrackbar("LowV", "Control", &lowV, 255);
	//cvCreateTrackbar("HighV", "Control", &highV, 255);

	namedWindow("Thresholded Image", CV_WINDOW_KEEPRATIO);
	namedWindow("Orginal", CV_WINDOW_KEEPRATIO);
	namedWindow("Cut", CV_WINDOW_KEEPRATIO);
	Mat imgOrginal, imgHSV, imgThresholded, imgCut;
	Mat se = getStructuringElement(MORPH_ELLIPSE, Size(5, 5));
	while(true){
		imgOrginal = imread(argv[1]);
		if(!imgOrginal.data){
			std::cerr << "could not read img!" << std::endl;
			return EXIT_FAILURE;
		}

		cvtColor(imgOrginal, imgHSV, COLOR_BGR2HSV);
		//inRange(imgHSV, Scalar(lowH, lowS, lowV), Scalar(highH, highS, highV), imgThresholded);
		inRange(imgHSV, Scalar(0, 0, 0), Scalar(180, 170, 170), imgThresholded);

		morphOps(imgThresholded, se);

		//rectangle(imgOrginal, getRegionOfInterest(imgThresholded), cv::Scalar(0, 0, 255), 8);
		imgOrginal(getRegionOfInterest(imgThresholded)).copyTo(imgCut);
		imshow("Thresholded Image", imgThresholded);
		imshow("Orginal", imgOrginal);
		imshow("Cut", imgCut);

		switch(waitKey(10)){
			case 27: //ESC
				return EXIT_SUCCESS;
				break;
			default:
				//do nothing
				break;
		}
	}

	return EXIT_SUCCESS;
}
<commit_msg>added tarckbars to control values<commit_after>#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <stdlib.h>
#include <iostream>

int lowH = 0, highH = 179;
int lowS = 0, highS = 255;
int lowV = 0, highV = 255;

cv::Rect const getRegionOfInterest(cv::Mat const &imgThreshold){
	cv::Mat tmp;
	imgThreshold.copyTo(tmp); // i don't know why this is necessary :(
	cv::Rect boundingRectangle;
	std::vector<std::vector<cv::Point>> contours;
	cv::findContours(tmp, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
	if(contours.size() > 0){ //found something
		int maxArea = 0;
		for(unsigned int i = 0; i < contours.size(); i++){
			cv::Rect tmpRect = cv::boundingRect(contours[i]);
			if(tmpRect.area() > maxArea){
				boundingRectangle = tmpRect;
				maxArea = tmpRect.area();
			}
		}
	}
	return boundingRectangle;
}

void morphOps(cv::Mat &img, cv::Mat const &structuringElement){
	//morphological opening (remove small objects from the foreground)
	cv::erode(img, img, structuringElement);
	cv::dilate(img, img, structuringElement);
	//morphological closing (fill small holes in the foreground)
	cv::dilate(img, img, structuringElement);
	cv::erode(img, img, structuringElement);
}

void createControl(){
	cvCreateTrackbar("LowH", "Thresholded Image", &lowH, 179);
	cvCreateTrackbar("HighH", "Thresholded Image", &highH, 179);

	cvCreateTrackbar("LowS", "Thresholded Image", &lowS, 255);
	cvCreateTrackbar("HighS", "Thresholded Image", &highS, 255);

	cvCreateTrackbar("LowV", "Thresholded Image", &lowV, 255);
	cvCreateTrackbar("HighV", "Thresholded Image", &highV, 255);
}

int main(int argc, char* argv[]){
	using namespace cv;

	if(argc != 2){
		std::cerr << "usage: ./track_detection <filename>" << std::endl;
		return EXIT_FAILURE;
	}

	//namedWindow("Control", CV_WINDOW_AUTOSIZE);

	namedWindow("Thresholded Image", CV_WINDOW_KEEPRATIO);
	namedWindow("Orginal", CV_WINDOW_KEEPRATIO);
	namedWindow("Cut", CV_WINDOW_KEEPRATIO);
	namedWindow("HSV", CV_WINDOW_KEEPRATIO);
	createControl();

	Mat imgOrginal, imgHSV, imgThresholded, imgCut;
	Mat se = getStructuringElement(MORPH_ELLIPSE, Size(5, 5));
	while(true){
		imgOrginal = imread(argv[1]);
		if(!imgOrginal.data){
			std::cerr << "could not read img!" << std::endl;
			return EXIT_FAILURE;
		}

		cvtColor(imgOrginal, imgHSV, COLOR_BGR2HSV);
		inRange(imgHSV, Scalar(lowH, lowS, lowV), Scalar(highH, highS, highV), imgThresholded);
		//inRange(imgHSV, Scalar(0, 0, 0), Scalar(180, 170, 170), imgThresholded);

		morphOps(imgThresholded, se);

		//rectangle(imgOrginal, getRegionOfInterest(imgThresholded), cv::Scalar(0, 0, 255), 8);
		imgOrginal(getRegionOfInterest(imgThresholded)).copyTo(imgCut);
		imshow("Thresholded Image", imgThresholded);
		imshow("Orginal", imgOrginal);
		imshow("Cut", imgCut);
		imshow("HSV", imgHSV);

		switch(waitKey(10)){
			case 27: //ESC
				return EXIT_SUCCESS;
				break;
			default:
				//do nothing
				break;
		}
	}

	return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*
 * ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2013, Numenta, Inc.  Unless you have purchased from
 * Numenta, Inc. a separate commercial license for this software code, the
 * following terms and conditions apply:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * 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.
 *
 * http://numenta.org/licenses/
 * ---------------------------------------------------------------------
 */

#include <iostream>

#include <nta/engine/RegionImpl.hpp>
#include <nta/ntypes/Buffer.hpp>
#include <nta/ntypes/Array.hpp>
#include <nta/types/BasicType.hpp>
#include <nta/engine/Region.hpp>
#include <nta/engine/Spec.hpp>
#include <nta/ntypes/Dimensions.hpp>
#include <nta/ntypes/BundleIO.hpp>
#include <nta/os/FStream.hpp>

namespace nta
{

RegionImpl::RegionImpl(Region *region) :
  region_(region)
{
}

RegionImpl::~RegionImpl()
{
}

// convenience method
const std::string& RegionImpl::getType() const
{
  return region_->getType();
}

const std::string& RegionImpl::getName() const
{
  return region_->getName();
}

const NodeSet& RegionImpl::getEnabledNodes() const
{
  return region_->getEnabledNodes();
}

/* ------------- Parameter support --------------- */
// By default, all typed getParameter calls forward to the
// untyped getParameter that serializes to a buffer

// Use macros to implement these methods.
// This is similar to a template + explicit instantiation, but
// templated methods can't be virtual and thus can't be
// overridden by subclasses.

#define getParameterT(Type) \
Type RegionImpl::getParameter##Type(const std::string& name, Int64 index) \
{\
  if (! region_->getSpec()->parameters.contains(name))     \
    NTA_THROW << "getParameter" #Type ": parameter " << name << " does not exist in nodespec"; \
  ParameterSpec p = region_->getSpec()->parameters.getByName(name); \
  if (p.dataType != NTA_BasicType_ ## Type) \
    NTA_THROW << "getParameter" #Type ": parameter " << name << " is of type " \
              << BasicType::getName(p.dataType) << " not " #Type; \
  WriteBuffer wb; \
  getParameterFromBuffer(name, index, wb); \
  ReadBuffer rb(wb.getData(), wb.getSize(), false /* copy */); \
  Type val; \
  int rc = rb.read(val); \
  if (rc != 0)  \
  { \
    NTA_THROW << "getParameter" #Type " -- failure to get parameter '"  \
              << name << "' on node of type " << getType(); \
  } \
  return val; \
}

getParameterT(Int32);
getParameterT(UInt32);
getParameterT(Int64);
getParameterT(UInt64)
getParameterT(Real32);
getParameterT(Real64);

#define setParameterT(Type) \
void RegionImpl::setParameter##Type(const std::string& name, Int64 index, Type value) \
{ \
  WriteBuffer wb; \
  wb.write((Type)value); \
  ReadBuffer rb(wb.getData(), wb.getSize(), false /* copy */); \
  setParameterFromBuffer(name, index, rb); \
}

setParameterT(Int32);
setParameterT(UInt32);
setParameterT(Int64);
setParameterT(UInt64)
setParameterT(Real32);
setParameterT(Real64);

// buffer mechanism can't handle Handles. RegionImpl must override these methods.
Handle RegionImpl::getParameterHandle(const std::string& name, Int64 index)
{
  NTA_THROW << "Unknown parameter '"  << name << "' of type Handle.";
}

void RegionImpl::setParameterHandle(const std::string& name, Int64 index, Handle h)
{
  NTA_THROW << "Unknown parameter '"  << name << "' of type Handle.";
}

void RegionImpl::getParameterArray(const std::string& name, Int64 index, Array & array)
{
  WriteBuffer wb;
  getParameterFromBuffer(name, index, wb);
  ReadBuffer rb(wb.getData(), wb.getSize(), false /* copy */);
  size_t count = array.getCount();
  void *buffer = array.getBuffer();

  for (size_t i = 0; i < count; i++)
  {
    int rc;
    switch (array.getType())
    {

    case NTA_BasicType_Byte:
      rc = rb.read(((Byte*)buffer)[i]);
      break;
    case NTA_BasicType_Int32:
      rc = rb.read(((Int32*)buffer)[i]);
      break;
    case NTA_BasicType_UInt32:
      rc = rb.read(((UInt32*)buffer)[i]);
      break;
    case NTA_BasicType_Int64:
      rc = rb.read(((Int64*)buffer)[i]);
      break;
    case NTA_BasicType_UInt64:
      rc = rb.read(((UInt64*)buffer)[i]);
      break;
    case NTA_BasicType_Real32:
      rc = rb.read(((Real32*)buffer)[i]);
      break;
    case NTA_BasicType_Real64:
      rc = rb.read(((Real64*)buffer)[i]);
      break;
    default:
      NTA_THROW << "Unsupported basic type " << BasicType::getName(array.getType())
                << " in getParameterArray for parameter " << name;
      break;
    }

    if (rc != 0)
    {
      NTA_THROW << "getParameterArray -- failure to get parameter '"
                << name << "' on node of type " << getType();
    }
  }
  return;
}

void RegionImpl::setParameterArray(const std::string& name, Int64 index,const Array & array)
{
  WriteBuffer wb;
  size_t count = array.getCount();
  void *buffer = array.getBuffer();
  for (size_t i = 0; i < count; i++)
  {
    int rc;
    switch (array.getType())
    {

    case NTA_BasicType_Byte:
      rc = wb.write(((Byte*)buffer)[i]);
      break;
    case NTA_BasicType_Int32:
      rc = wb.write(((Int32*)buffer)[i]);
      break;
    case NTA_BasicType_UInt32:
      rc = wb.write(((UInt32*)buffer)[i]);
      break;
    case NTA_BasicType_Int64:
      rc = wb.write(((Int64*)buffer)[i]);
      break;
    case NTA_BasicType_UInt64:
      rc = wb.write(((UInt64*)buffer)[i]);
      break;
    case NTA_BasicType_Real32:
      rc = wb.write(((Real32*)buffer)[i]);
      break;
    case NTA_BasicType_Real64:
      rc = wb.write(((Real64*)buffer)[i]);
      break;
    default:
      NTA_THROW << "Unsupported basic type " << BasicType::getName(array.getType())
                << " in setParameterArray for parameter " << name;
      break;
    }
  }

  if (rc != 0)
  {
    NTA_THROW << "getParameterArray -- failure to get parameter '"
              << name << "' on node of type " << getType();
  }

  ReadBuffer rb(wb.getData(), wb.getSize(), false);
  setParameterFromBuffer(name, index, rb);
}

void RegionImpl::setParameterString(const std::string& name, Int64 index, const std::string& s)
{
  ReadBuffer rb(s.c_str(), s.size(), false);
  setParameterFromBuffer(name, index, rb);
}

std::string RegionImpl::getParameterString(const std::string& name, Int64 index)
{
  WriteBuffer wb;
  getParameterFromBuffer(name, index, wb);
  return std::string(wb.getData(), wb.getSize());
}

// Must be overridden by subclasses
bool RegionImpl::isParameterShared(const std::string& name)
{
  NTA_THROW << "RegionImpl::isParameterShared was not overridden in node type " << getType();
}

void RegionImpl::getParameterFromBuffer(const std::string& name,
                             Int64 index,
                             IWriteBuffer& value)
{
  NTA_THROW << "RegionImpl::getParameterFromBuffer must be overridden by subclasses";
}

void RegionImpl::setParameterFromBuffer(const std::string& name,
                          Int64 index,
                          IReadBuffer& value)
{
  NTA_THROW << "RegionImpl::setParameterFromBuffer must be overridden by subclasses";
}

size_t RegionImpl::getParameterArrayCount(const std::string& name, Int64 index)
{
  // Default implementation for RegionImpls with no array parameters
  // that have a dynamic length.
  //std::map<std::string, ParameterSpec*>::iterator i = nodespec_->parameters.find(name);
  //if (i == nodespec_->parameters.end())

  if (!region_->getSpec()->parameters.contains(name))
  {
    NTA_THROW << "getParameterArrayCount -- no parameter named '"
              << name << "' in node of type " << getType();
  }
  UInt32 count = region_->getSpec()->parameters.getByName(name).count;
  if (count == 0)
  {
    NTA_THROW << "Internal Error -- unknown element count for "
              << "node type " << getType() << ". The RegionImpl "
              << "implementation should override this method.";
  }

  return count;
}

// Provide data access for subclasses

const Input* RegionImpl::getInput(const std::string& name)
{
  return region_->getInput(name);
}

const Output* RegionImpl::getOutput(const std::string& name)
{
  return region_->getOutput(name);
}

const Dimensions& RegionImpl::getDimensions()
{
  return region_->getDimensions();
}

}

<commit_msg>move rc check inside for loop<commit_after>/*
 * ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2013, Numenta, Inc.  Unless you have purchased from
 * Numenta, Inc. a separate commercial license for this software code, the
 * following terms and conditions apply:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * 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.
 *
 * http://numenta.org/licenses/
 * ---------------------------------------------------------------------
 */

#include <iostream>

#include <nta/engine/RegionImpl.hpp>
#include <nta/ntypes/Buffer.hpp>
#include <nta/ntypes/Array.hpp>
#include <nta/types/BasicType.hpp>
#include <nta/engine/Region.hpp>
#include <nta/engine/Spec.hpp>
#include <nta/ntypes/Dimensions.hpp>
#include <nta/ntypes/BundleIO.hpp>
#include <nta/os/FStream.hpp>

namespace nta
{

RegionImpl::RegionImpl(Region *region) :
  region_(region)
{
}

RegionImpl::~RegionImpl()
{
}

// convenience method
const std::string& RegionImpl::getType() const
{
  return region_->getType();
}

const std::string& RegionImpl::getName() const
{
  return region_->getName();
}

const NodeSet& RegionImpl::getEnabledNodes() const
{
  return region_->getEnabledNodes();
}

/* ------------- Parameter support --------------- */
// By default, all typed getParameter calls forward to the
// untyped getParameter that serializes to a buffer

// Use macros to implement these methods.
// This is similar to a template + explicit instantiation, but
// templated methods can't be virtual and thus can't be
// overridden by subclasses.

#define getParameterT(Type) \
Type RegionImpl::getParameter##Type(const std::string& name, Int64 index) \
{\
  if (! region_->getSpec()->parameters.contains(name))     \
    NTA_THROW << "getParameter" #Type ": parameter " << name << " does not exist in nodespec"; \
  ParameterSpec p = region_->getSpec()->parameters.getByName(name); \
  if (p.dataType != NTA_BasicType_ ## Type) \
    NTA_THROW << "getParameter" #Type ": parameter " << name << " is of type " \
              << BasicType::getName(p.dataType) << " not " #Type; \
  WriteBuffer wb; \
  getParameterFromBuffer(name, index, wb); \
  ReadBuffer rb(wb.getData(), wb.getSize(), false /* copy */); \
  Type val; \
  int rc = rb.read(val); \
  if (rc != 0)  \
  { \
    NTA_THROW << "getParameter" #Type " -- failure to get parameter '"  \
              << name << "' on node of type " << getType(); \
  } \
  return val; \
}

getParameterT(Int32);
getParameterT(UInt32);
getParameterT(Int64);
getParameterT(UInt64)
getParameterT(Real32);
getParameterT(Real64);

#define setParameterT(Type) \
void RegionImpl::setParameter##Type(const std::string& name, Int64 index, Type value) \
{ \
  WriteBuffer wb; \
  wb.write((Type)value); \
  ReadBuffer rb(wb.getData(), wb.getSize(), false /* copy */); \
  setParameterFromBuffer(name, index, rb); \
}

setParameterT(Int32);
setParameterT(UInt32);
setParameterT(Int64);
setParameterT(UInt64)
setParameterT(Real32);
setParameterT(Real64);

// buffer mechanism can't handle Handles. RegionImpl must override these methods.
Handle RegionImpl::getParameterHandle(const std::string& name, Int64 index)
{
  NTA_THROW << "Unknown parameter '"  << name << "' of type Handle.";
}

void RegionImpl::setParameterHandle(const std::string& name, Int64 index, Handle h)
{
  NTA_THROW << "Unknown parameter '"  << name << "' of type Handle.";
}

void RegionImpl::getParameterArray(const std::string& name, Int64 index, Array & array)
{
  WriteBuffer wb;
  getParameterFromBuffer(name, index, wb);
  ReadBuffer rb(wb.getData(), wb.getSize(), false /* copy */);
  size_t count = array.getCount();
  void *buffer = array.getBuffer();

  for (size_t i = 0; i < count; i++)
  {
    int rc;
    switch (array.getType())
    {

    case NTA_BasicType_Byte:
      rc = rb.read(((Byte*)buffer)[i]);
      break;
    case NTA_BasicType_Int32:
      rc = rb.read(((Int32*)buffer)[i]);
      break;
    case NTA_BasicType_UInt32:
      rc = rb.read(((UInt32*)buffer)[i]);
      break;
    case NTA_BasicType_Int64:
      rc = rb.read(((Int64*)buffer)[i]);
      break;
    case NTA_BasicType_UInt64:
      rc = rb.read(((UInt64*)buffer)[i]);
      break;
    case NTA_BasicType_Real32:
      rc = rb.read(((Real32*)buffer)[i]);
      break;
    case NTA_BasicType_Real64:
      rc = rb.read(((Real64*)buffer)[i]);
      break;
    default:
      NTA_THROW << "Unsupported basic type " << BasicType::getName(array.getType())
                << " in getParameterArray for parameter " << name;
      break;
    }

    if (rc != 0)
    {
      NTA_THROW << "getParameterArray -- failure to get parameter '"
                << name << "' on node of type " << getType();
    }
  }
  return;
}

void RegionImpl::setParameterArray(const std::string& name, Int64 index,const Array & array)
{
  WriteBuffer wb;
  size_t count = array.getCount();
  void *buffer = array.getBuffer();
  for (size_t i = 0; i < count; i++)
  {
    int rc;
    switch (array.getType())
    {

    case NTA_BasicType_Byte:
      rc = wb.write(((Byte*)buffer)[i]);
      break;
    case NTA_BasicType_Int32:
      rc = wb.write(((Int32*)buffer)[i]);
      break;
    case NTA_BasicType_UInt32:
      rc = wb.write(((UInt32*)buffer)[i]);
      break;
    case NTA_BasicType_Int64:
      rc = wb.write(((Int64*)buffer)[i]);
      break;
    case NTA_BasicType_UInt64:
      rc = wb.write(((UInt64*)buffer)[i]);
      break;
    case NTA_BasicType_Real32:
      rc = wb.write(((Real32*)buffer)[i]);
      break;
    case NTA_BasicType_Real64:
      rc = wb.write(((Real64*)buffer)[i]);
      break;
    default:
      NTA_THROW << "Unsupported basic type " << BasicType::getName(array.getType())
                << " in setParameterArray for parameter " << name;
      break;
    }

    if (rc != 0)
    {
      NTA_THROW << "getParameterArray -- failure to get parameter '"
                << name << "' on node of type " << getType();
    }
  }

  ReadBuffer rb(wb.getData(), wb.getSize(), false);
  setParameterFromBuffer(name, index, rb);
}

void RegionImpl::setParameterString(const std::string& name, Int64 index, const std::string& s)
{
  ReadBuffer rb(s.c_str(), s.size(), false);
  setParameterFromBuffer(name, index, rb);
}

std::string RegionImpl::getParameterString(const std::string& name, Int64 index)
{
  WriteBuffer wb;
  getParameterFromBuffer(name, index, wb);
  return std::string(wb.getData(), wb.getSize());
}

// Must be overridden by subclasses
bool RegionImpl::isParameterShared(const std::string& name)
{
  NTA_THROW << "RegionImpl::isParameterShared was not overridden in node type " << getType();
}

void RegionImpl::getParameterFromBuffer(const std::string& name,
                             Int64 index,
                             IWriteBuffer& value)
{
  NTA_THROW << "RegionImpl::getParameterFromBuffer must be overridden by subclasses";
}

void RegionImpl::setParameterFromBuffer(const std::string& name,
                          Int64 index,
                          IReadBuffer& value)
{
  NTA_THROW << "RegionImpl::setParameterFromBuffer must be overridden by subclasses";
}

size_t RegionImpl::getParameterArrayCount(const std::string& name, Int64 index)
{
  // Default implementation for RegionImpls with no array parameters
  // that have a dynamic length.
  //std::map<std::string, ParameterSpec*>::iterator i = nodespec_->parameters.find(name);
  //if (i == nodespec_->parameters.end())

  if (!region_->getSpec()->parameters.contains(name))
  {
    NTA_THROW << "getParameterArrayCount -- no parameter named '"
              << name << "' in node of type " << getType();
  }
  UInt32 count = region_->getSpec()->parameters.getByName(name).count;
  if (count == 0)
  {
    NTA_THROW << "Internal Error -- unknown element count for "
              << "node type " << getType() << ". The RegionImpl "
              << "implementation should override this method.";
  }

  return count;
}

// Provide data access for subclasses

const Input* RegionImpl::getInput(const std::string& name)
{
  return region_->getInput(name);
}

const Output* RegionImpl::getOutput(const std::string& name)
{
  return region_->getOutput(name);
}

const Dimensions& RegionImpl::getDimensions()
{
  return region_->getDimensions();
}

}

<|endoftext|>