<commit_before>/* Copyright (C) 2005-2011, Thorvald Natvig <thorvald@natvig.com>

   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:

   - Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.
   - Redistributions in binary form must reproduce the above copyright notice,
     this list of conditions and the following disclaimer in the documentation
     and/or other materials provided with the distribution.
   - Neither the name of the Mumble Developers nor the names of its
     contributors may be used to endorse or promote products derived from this
     software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
   A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "mumble_pch.hpp"

#include "VersionCheck.h"

#include "Global.h"
#include "MainWindow.h"
#include "WebFetch.h"

VersionCheck::VersionCheck(bool autocheck, QObject *p, bool focus) : QObject(p) {
	bSilent = autocheck;

	QUrl url;
	url.setPath(focus ? QLatin1String("/v1/banner") : QLatin1String("/v1/version-check"));

	QList<QPair<QString, QString> > queryItems;
	queryItems << qMakePair(QString::fromLatin1("ver"), QString::fromLatin1(QUrl::toPercentEncoding(QLatin1String(MUMBLE_RELEASE))));
#if defined(Q_OS_WIN)
# if defined(Q_OS_WIN64)
	queryItems << qMakePair(QString::fromLatin1("os"), QString::fromLatin1("WinX64"));
# else
	queryItems << qMakePair(QString::fromLatin1("os"), QString::fromLatin1("Win32"));
# endif
#elif defined(Q_OS_MAC)
# if defined(USE_MAC_UNIVERSAL)
	queryItems << qMakePair(QString::fromLatin1("os"), QString::fromLatin1("MacOSX-Universal"));
# else
	queryItems << qMakePair(QString::fromLatin1("os"), QString::fromLatin1("MacOSX"));
# endif
#else
	queryItems << qMakePair(QString::fromLatin1("os"), QString::fromLatin1("Unix"));
#endif
	if (! g.s.bUsage)
		queryItems << qMakePair(QString::fromLatin1("nousage"), QString::fromLatin1("1"));
	if (autocheck)
		queryItems << qMakePair(QString::fromLatin1("auto"), QString::fromLatin1("1"));

	queryItems << qMakePair(QString::fromLatin1("locale"), g.s.qsLanguage.isEmpty() ? QLocale::system().name() : g.s.qsLanguage);

	QFile f(qApp->applicationFilePath());
	if (! f.open(QIODevice::ReadOnly)) {
		qWarning("VersionCheck: Failed to open binary");
	} else {
		QByteArray a = f.readAll();
		if (a.size() < 1) {
			qWarning("VersionCheck: suspiciously small binary");
		} else {
			QCryptographicHash qch(QCryptographicHash::Sha1);
			qch.addData(a);
			queryItems << qMakePair(QString::fromLatin1("sha1"), QString::fromLatin1(qch.result().toHex()));
		}
	}

#if QT_VERSION >= 0x050000
	QUrlQuery query;
	query.setQueryItems(queryItems);
	url.setQuery(query);
#else
	for (int i = 0; i < queryItems.size(); i++) {
		const QPair<QString, QString> &queryPair = queryItems.at(i);
		url.addQueryItem(queryPair.first, queryPair.second);
	}
#endif
	WebFetch::fetch(QLatin1String("update"), url, this, SLOT(fetched(QByteArray,QUrl)));
}

void VersionCheck::fetched(QByteArray a, QUrl url) {
	if (! a.isNull()) {
		if (! a.isEmpty()) {
#ifdef SNAPSHOT_BUILD
			if (url.path() == QLatin1String("/v1/banner")) {
				g.mw->msgBox(QString::fromUtf8(a));
			} else if (url.path() == QLatin1String("/v1/version-check")) {
#ifndef Q_OS_WIN
				g.mw->msgBox(QString::fromUtf8(a));
#else
				QDomDocument qdd;
				qdd.setContent(a);

				QDomElement elem = qdd.firstChildElement(QLatin1String("p"));
				elem = elem.firstChildElement(QLatin1String("a"));

				QUrl fetch = QUrl(elem.attribute(QLatin1String("href")));
				fetch.setHost(QString());
				fetch.setScheme(QString());
				if (! fetch.isValid()) {
					g.mw->msgBox(QString::fromUtf8(a));
				} else {
					QString filename = g.qdBasePath.absoluteFilePath(QLatin1String("Snapshots/") + QFileInfo(fetch.path()).fileName());

					QFile qf(filename);
					if (qf.exists()) {
						std::wstring native = QDir::toNativeSeparators(filename).toStdWString();

						WINTRUST_FILE_INFO file;
						ZeroMemory(&file, sizeof(file));
						file.cbStruct = sizeof(file);
						file.pcwszFilePath = native.c_str();

						WINTRUST_DATA data;
						ZeroMemory(&data, sizeof(data));
						data.cbStruct = sizeof(data);
						data.dwUIChoice = WTD_UI_NONE;
						data.fdwRevocationChecks = WTD_REVOKE_NONE;
						data.dwUnionChoice = WTD_CHOICE_FILE;
						data.pFile = &file;
						data.dwProvFlags = WTD_SAFER_FLAG | WTD_USE_DEFAULT_OSVER_CHECK | WTD_LIFETIME_SIGNING_FLAG;
						data.dwUIContext = WTD_UICONTEXT_INSTALL;

						static GUID guid = WINTRUST_ACTION_GENERIC_VERIFY_V2;

						LONG ts = WinVerifyTrust(0, &guid , &data);

						if (ts == 0) {
							if (QMessageBox::question(g.mw,
							                          tr("Upgrade Mumble"),
							                          tr("A new version of Mumble has been detected and automatically downloaded. It is recommended that you either upgrade to this version, or downgrade to the latest stable release. Do you want to launch the installer now?"),
							                          QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes) {
								SHELLEXECUTEINFOW execinfo;
								std::wstring filenative = filename.toStdWString();
								std::wstring dirnative = QDir::toNativeSeparators(QDir::tempPath()).toStdWString();
								ZeroMemory(&execinfo, sizeof(execinfo));
								execinfo.cbSize = sizeof(execinfo);
								execinfo.lpFile = filenative.c_str();
								execinfo.lpDirectory = dirnative.c_str();
								execinfo.nShow = SW_NORMAL;

								if (ShellExecuteExW(&execinfo)) {
									g.mw->bSuppressAskOnQuit = true;
									qApp->closeAllWindows();
								} else {
									g.mw->msgBox(tr("Failed to launch snapshot installer."));
								}
							}

						} else {
							g.mw->msgBox(tr("Corrupt download of new version detected. Automatically removed."));
							qf.remove();
						}

						// Delete all but the N most recent snapshots
						size_t numberOfSnapshotsToKeep = 1;

						QDir snapdir(g.qdBasePath.absolutePath() + QLatin1String("/Snapshots/"),
						             QString(),
						             QDir::Name,
						             QDir::Files);

						foreach(const QFileInfo fileInfo, snapdir.entryInfoList(QStringList(), QDir::NoFilter, QDir::Time)) {
							if (numberOfSnapshotsToKeep) {
								--numberOfSnapshotsToKeep;
								continue;
							}

							qWarning() << "Purging old snapshot" << fileInfo.fileName();
							QFile file(fileInfo.absoluteFilePath());
							file.remove();
						}
					} else {
						g.mw->msgBox(tr("Downloading new snapshot from %1 to %2").arg(Qt::escape(fetch.toString()), Qt::escape(filename)));
						WebFetch::fetch(fetch, this, SLOT(fetched(QByteArray,QUrl)));
						return;
					}
				}
			} else {
				QString filename = g.qdBasePath.absoluteFilePath(QLatin1String("Snapshots/") + QFileInfo(url.path()).fileName());

				QFile qf(filename);
				if (qf.open(QIODevice::WriteOnly)) {
					qf.write(a);
					qf.close();
					new VersionCheck(true, g.mw);
				} else {
					g.mw->msgBox(tr("Failed to write new version to disk."));
				}
#endif
			}
#else
			Q_UNUSED(url);
			g.mw->msgBox(QString::fromUtf8(a));
#endif
		}
	} else if (bSilent) {
		g.mw->msgBox(tr("Mumble failed to retrieve version information from the central server."));
	}

	deleteLater();
}
<commit_msg>VersionCheck: use updated WebFetch::fetch() for snapshot downloads.<commit_after>/* Copyright (C) 2005-2011, Thorvald Natvig <thorvald@natvig.com>

   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:

   - Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.
   - Redistributions in binary form must reproduce the above copyright notice,
     this list of conditions and the following disclaimer in the documentation
     and/or other materials provided with the distribution.
   - Neither the name of the Mumble Developers nor the names of its
     contributors may be used to endorse or promote products derived from this
     software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
   A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "mumble_pch.hpp"

#include "VersionCheck.h"

#include "Global.h"
#include "MainWindow.h"
#include "WebFetch.h"

VersionCheck::VersionCheck(bool autocheck, QObject *p, bool focus) : QObject(p) {
	bSilent = autocheck;

	QUrl url;
	url.setPath(focus ? QLatin1String("/v1/banner") : QLatin1String("/v1/version-check"));

	QList<QPair<QString, QString> > queryItems;
	queryItems << qMakePair(QString::fromLatin1("ver"), QString::fromLatin1(QUrl::toPercentEncoding(QLatin1String(MUMBLE_RELEASE))));
#if defined(Q_OS_WIN)
# if defined(Q_OS_WIN64)
	queryItems << qMakePair(QString::fromLatin1("os"), QString::fromLatin1("WinX64"));
# else
	queryItems << qMakePair(QString::fromLatin1("os"), QString::fromLatin1("Win32"));
# endif
#elif defined(Q_OS_MAC)
# if defined(USE_MAC_UNIVERSAL)
	queryItems << qMakePair(QString::fromLatin1("os"), QString::fromLatin1("MacOSX-Universal"));
# else
	queryItems << qMakePair(QString::fromLatin1("os"), QString::fromLatin1("MacOSX"));
# endif
#else
	queryItems << qMakePair(QString::fromLatin1("os"), QString::fromLatin1("Unix"));
#endif
	if (! g.s.bUsage)
		queryItems << qMakePair(QString::fromLatin1("nousage"), QString::fromLatin1("1"));
	if (autocheck)
		queryItems << qMakePair(QString::fromLatin1("auto"), QString::fromLatin1("1"));

	queryItems << qMakePair(QString::fromLatin1("locale"), g.s.qsLanguage.isEmpty() ? QLocale::system().name() : g.s.qsLanguage);

	QFile f(qApp->applicationFilePath());
	if (! f.open(QIODevice::ReadOnly)) {
		qWarning("VersionCheck: Failed to open binary");
	} else {
		QByteArray a = f.readAll();
		if (a.size() < 1) {
			qWarning("VersionCheck: suspiciously small binary");
		} else {
			QCryptographicHash qch(QCryptographicHash::Sha1);
			qch.addData(a);
			queryItems << qMakePair(QString::fromLatin1("sha1"), QString::fromLatin1(qch.result().toHex()));
		}
	}

#if QT_VERSION >= 0x050000
	QUrlQuery query;
	query.setQueryItems(queryItems);
	url.setQuery(query);
#else
	for (int i = 0; i < queryItems.size(); i++) {
		const QPair<QString, QString> &queryPair = queryItems.at(i);
		url.addQueryItem(queryPair.first, queryPair.second);
	}
#endif
	WebFetch::fetch(QLatin1String("update"), url, this, SLOT(fetched(QByteArray,QUrl)));
}

void VersionCheck::fetched(QByteArray a, QUrl url) {
	if (! a.isNull()) {
		if (! a.isEmpty()) {
#ifdef SNAPSHOT_BUILD
			if (url.path() == QLatin1String("/v1/banner")) {
				g.mw->msgBox(QString::fromUtf8(a));
			} else if (url.path() == QLatin1String("/v1/version-check")) {
#ifndef Q_OS_WIN
				g.mw->msgBox(QString::fromUtf8(a));
#else
				QDomDocument qdd;
				qdd.setContent(a);

				QDomElement elem = qdd.firstChildElement(QLatin1String("p"));
				elem = elem.firstChildElement(QLatin1String("a"));

				QUrl fetch = QUrl(elem.attribute(QLatin1String("href")));
				fetch.setHost(QString());
				fetch.setScheme(QString());
				if (! fetch.isValid()) {
					g.mw->msgBox(QString::fromUtf8(a));
				} else {
					QString filename = g.qdBasePath.absoluteFilePath(QLatin1String("Snapshots/") + QFileInfo(fetch.path()).fileName());

					QFile qf(filename);
					if (qf.exists()) {
						std::wstring native = QDir::toNativeSeparators(filename).toStdWString();

						WINTRUST_FILE_INFO file;
						ZeroMemory(&file, sizeof(file));
						file.cbStruct = sizeof(file);
						file.pcwszFilePath = native.c_str();

						WINTRUST_DATA data;
						ZeroMemory(&data, sizeof(data));
						data.cbStruct = sizeof(data);
						data.dwUIChoice = WTD_UI_NONE;
						data.fdwRevocationChecks = WTD_REVOKE_NONE;
						data.dwUnionChoice = WTD_CHOICE_FILE;
						data.pFile = &file;
						data.dwProvFlags = WTD_SAFER_FLAG | WTD_USE_DEFAULT_OSVER_CHECK | WTD_LIFETIME_SIGNING_FLAG;
						data.dwUIContext = WTD_UICONTEXT_INSTALL;

						static GUID guid = WINTRUST_ACTION_GENERIC_VERIFY_V2;

						LONG ts = WinVerifyTrust(0, &guid , &data);

						if (ts == 0) {
							if (QMessageBox::question(g.mw,
							                          tr("Upgrade Mumble"),
							                          tr("A new version of Mumble has been detected and automatically downloaded. It is recommended that you either upgrade to this version, or downgrade to the latest stable release. Do you want to launch the installer now?"),
							                          QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes) {
								SHELLEXECUTEINFOW execinfo;
								std::wstring filenative = filename.toStdWString();
								std::wstring dirnative = QDir::toNativeSeparators(QDir::tempPath()).toStdWString();
								ZeroMemory(&execinfo, sizeof(execinfo));
								execinfo.cbSize = sizeof(execinfo);
								execinfo.lpFile = filenative.c_str();
								execinfo.lpDirectory = dirnative.c_str();
								execinfo.nShow = SW_NORMAL;

								if (ShellExecuteExW(&execinfo)) {
									g.mw->bSuppressAskOnQuit = true;
									qApp->closeAllWindows();
								} else {
									g.mw->msgBox(tr("Failed to launch snapshot installer."));
								}
							}

						} else {
							g.mw->msgBox(tr("Corrupt download of new version detected. Automatically removed."));
							qf.remove();
						}

						// Delete all but the N most recent snapshots
						size_t numberOfSnapshotsToKeep = 1;

						QDir snapdir(g.qdBasePath.absolutePath() + QLatin1String("/Snapshots/"),
						             QString(),
						             QDir::Name,
						             QDir::Files);

						foreach(const QFileInfo fileInfo, snapdir.entryInfoList(QStringList(), QDir::NoFilter, QDir::Time)) {
							if (numberOfSnapshotsToKeep) {
								--numberOfSnapshotsToKeep;
								continue;
							}

							qWarning() << "Purging old snapshot" << fileInfo.fileName();
							QFile file(fileInfo.absoluteFilePath());
							file.remove();
						}
					} else {
						g.mw->msgBox(tr("Downloading new snapshot from %1 to %2").arg(Qt::escape(fetch.toString()), Qt::escape(filename)));
						WebFetch::fetch(QLatin1String("dl"), fetch, this, SLOT(fetched(QByteArray,QUrl)));
						return;
					}
				}
			} else {
				QString filename = g.qdBasePath.absoluteFilePath(QLatin1String("Snapshots/") + QFileInfo(url.path()).fileName());

				QFile qf(filename);
				if (qf.open(QIODevice::WriteOnly)) {
					qf.write(a);
					qf.close();
					new VersionCheck(true, g.mw);
				} else {
					g.mw->msgBox(tr("Failed to write new version to disk."));
				}
#endif
			}
#else
			Q_UNUSED(url);
			g.mw->msgBox(QString::fromUtf8(a));
#endif
		}
	} else if (bSilent) {
		g.mw->msgBox(tr("Mumble failed to retrieve version information from the central server."));
	}

	deleteLater();
}
<|endoftext|>


<commit_before>#include "Image.h"

namespace hm
{
	Image::Image()
	{

	}

	Image::Image(std::string filename, SDL_Renderer* renderer)
	{
		loadImage(filename, renderer);
	}

	void Image::loadImage(std::string filename, SDL_Renderer* renderer)
	{
		// Unload a previous image.
		if(texture != nullptr)
		{
			SDL_DestroyTexture(texture);
			texture = nullptr;
		}

		SDL_Surface* surface = IMG_Load(filename.c_str());

		// Check if it was loaded.
		if(surface == NULL)
		{
			std::cout << "Could not open " << filename << std::endl;
			return;
		}

		// Color key surface
		Uint32 key = SDL_MapRGB(surface->format, 0xFF, 0x00, 0xFF);
		SDL_SetColorKey(surface, SDL_TRUE, key);

		// Convert to texture.
		texture = SDL_CreateTextureFromSurface(renderer, surface);
		SDL_FreeSurface(surface);
		surface = nullptr;

		// Get dimensions.
		SDL_QueryTexture(texture, nullptr, nullptr, &info.w, &info.h);

		return;
	}

	void Image::setColorKey(Uint8 r, Uint8 g, Uint8 b)
	{
		color_key = { r, g, b, 0 };
		return;
	}
}
<commit_msg>Make it more obvious that a file name should follow.<commit_after>#include "Image.h"

namespace hm
{
	Image::Image()
	{

	}

	Image::Image(std::string filename, SDL_Renderer* renderer)
	{
		loadImage(filename, renderer);
	}

	void Image::loadImage(std::string filename, SDL_Renderer* renderer)
	{
		// Unload a previous image.
		if(texture != nullptr)
		{
			SDL_DestroyTexture(texture);
			texture = nullptr;
		}

		SDL_Surface* surface = IMG_Load(filename.c_str());

		// Check if it was loaded.
		if(surface == NULL)
		{
			std::cout << "Could not open image: " << filename << std::endl;
			return;
		}

		// Color key surface
		Uint32 key = SDL_MapRGB(surface->format, 0xFF, 0x00, 0xFF);
		SDL_SetColorKey(surface, SDL_TRUE, key);

		// Convert to texture.
		texture = SDL_CreateTextureFromSurface(renderer, surface);
		SDL_FreeSurface(surface);
		surface = nullptr;

		// Get dimensions.
		SDL_QueryTexture(texture, nullptr, nullptr, &info.w, &info.h);

		return;
	}

	void Image::setColorKey(Uint8 r, Uint8 g, Uint8 b)
	{
		color_key = { r, g, b, 0 };
		return;
	}
}
<|endoftext|>


<commit_before>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#include "passive_aggressive_2.hpp"

#include <algorithm>
#include <string>

using std::string;

namespace jubatus {
namespace classifier {

passive_aggressive_2::passive_aggressive_2(storage::storage_base* storage)
    : classifier_base(storage) {
}

passive_aggressive_2::passive_aggressive_2(
    const classifier_config& config,
    storage::storage_base* storage)
    : classifier_base(storage) {
}

void passive_aggressive_2::train(const sfv_t& sfv, const string& label) {
  string incorrect_label;
  float margin = calc_margin(sfv, label, incorrect_label);
  float loss = 1.f + margin;

  if (loss < 0.f) {
    return;
  }
  float sfv_norm = squared_norm(sfv);
  if (sfv_norm == 0.f) {
    return;
  }
  update_weight(
      sfv, loss / (2 * sfv_norm + 1 / (2 * config.C)), label, incorrect_label);
}

string passive_aggressive_2::name() const {
  return string("passive_aggressive_2");
}

}  // namespace classifier
}  // namespace jubatus
<commit_msg>fix passive_aggressive_2 to use config<commit_after>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#include "passive_aggressive_2.hpp"

#include <algorithm>
#include <string>

using std::string;

namespace jubatus {
namespace classifier {

passive_aggressive_2::passive_aggressive_2(storage::storage_base* storage)
    : classifier_base(storage) {
}

passive_aggressive_2::passive_aggressive_2(
    const classifier_config& config,
    storage::storage_base* storage)
    : classifier_base(storage),
      config(config) {
}

void passive_aggressive_2::train(const sfv_t& sfv, const string& label) {
  string incorrect_label;
  float margin = calc_margin(sfv, label, incorrect_label);
  float loss = 1.f + margin;

  if (loss < 0.f) {
    return;
  }
  float sfv_norm = squared_norm(sfv);
  if (sfv_norm == 0.f) {
    return;
  }
  update_weight(
      sfv, loss / (2 * sfv_norm + 1 / (2 * config.C)), label, incorrect_label);
}

string passive_aggressive_2::name() const {
  return string("passive_aggressive_2");
}

}  // namespace classifier
}  // namespace jubatus
<|endoftext|>


<commit_before>/*
 * TTBlue Signal Crossfader Object
 * Copyright © 2008, Timothy Place
 *
 * License: This code is licensed under the terms of the GNU LGPL
 * http://www.gnu.org/licenses/lgpl.html
 */

#include "TTCrossfade.h"

TTCrossfade::TTCrossfade(TTUInt8 newMaxNumChannels)
	: TTAudioObject("audio.crossfade", newMaxNumChannels), attrShape((TTSymbol&)kTTSymEmpty), attrMode((TTSymbol&)kTTSymEmpty)
{
	registerAttribute(TT("position"),	kTypeFloat64,	&attrPosition);
	registerAttribute(TT("shape"),		kTypeSymbol,	&attrShape,		(TTGetterMethod)NULL, (TTSetterMethod)&TTCrossfade::setShape);
	registerAttribute(TT("mode"),		kTypeSymbol,	&attrMode,		(TTGetterMethod)NULL, (TTSetterMethod)&TTCrossfade::setMode);

	// Set Defaults (the attribute setters will set the process method for us)...
	setAttributeValue(TT("position"),	0.5);
	setAttributeValue(TT("shape"),		TT("equalPower"));
	setAttributeValue(TT("mode"),		TT("lookup"));
}

TTCrossfade::~TTCrossfade()
{
	;
}

TTErr TTCrossfade::setShape(const TTValue& newValue)
{
	attrShape = newValue;
	return setProcessPointers();
}

TTErr TTCrossfade::setMode(const TTValue& newValue)
{
	attrMode = newValue;
	return setProcessPointers();
}

TTErr TTCrossfade::setProcessPointers()
{
	TTErr	err =kTTErrNone;

	if(attrShape == TT("equalPower") && attrMode == TT("lookup")){
		err |= setProcessWithSidechain((TTProcessWithSidechainMethod)&TTCrossfade::processLookupUsingSidechain);
		err |= setProcess((TTProcessMethod)&TTCrossfade::processLookup);
	}
	else if(attrShape == TT("equalPower") && attrMode == TT("calculate")){
		err |= setProcessWithSidechain((TTProcessWithSidechainMethod)&TTCrossfade::processCalcUsingSidechain);
		err |= setProcess((TTProcessMethod)&TTCrossfade::processCalc);
	}
	else{
		err |= setProcessWithSidechain((TTProcessWithSidechainMethod)&TTCrossfade::processLinearUsingSidechain);
		err |= setProcess((TTProcessMethod)&TTCrossfade::processLinear);
	}
	return err;
}

#if 0
#pragma mark -
#pragma mark Interleaved Process Methods
#endif

TTErr TTCrossfade::processLinear(TTAudioSignal& in, TTAudioSignal& out)
{
	short			vs;
	TTSampleValue	*inSampleA,
					*inSampleB,
					*outSample;
	short			numchannels = out.getNumChannels();
	short			channel;

	if(in.getNumChannels() != out.getNumChannels()*2)
		return kTTErrGeneric;

	for(channel=0; channel<numchannels; channel++){
		inSampleA = in.sampleVectors[channel];
		inSampleB = in.sampleVectors[numchannels+channel];
		outSample = out.sampleVectors[channel];
		vs = in.getVectorSize();

		while(vs--)
			*outSample++ = (*inSampleB++ * attrPosition) + (*inSampleA++ * (1.0 - attrPosition));
	}
	return kTTErrNone;
}

TTErr TTCrossfade::processLookup(TTAudioSignal& in, TTAudioSignal& out)
{
	short			vs;
	TTSampleValue	*inSampleA,
					*inSampleB,
					*outSample;
	short			numchannels = out.getNumChannels();
	short			channel;
	int				index;

	if(in.getNumChannels() != out.getNumChannels()*2)
		return kTTErrGeneric;

	for(channel=0; channel<numchannels; channel++){
		inSampleA = in.sampleVectors[channel];
		inSampleB = in.sampleVectors[numchannels+channel];
		outSample = out.sampleVectors[channel];
		vs = in.getVectorSize();

		while(vs--){
			index = (int)(attrPosition * 511.0);
			*outSample++ = (*inSampleB++ * kTTLookupEqualPower[511 - index]) + (*inSampleA++ * kTTLookupEqualPower[index]);
		}
	}
	return kTTErrNone;
}

TTErr TTCrossfade::processCalc(TTAudioSignal& in, TTAudioSignal& out)
{
	short			vs;
	TTSampleValue	*inSampleA,
					*inSampleB,
					*outSample;
	short			numchannels = out.getNumChannels();
	short			channel;

	if(in.getNumChannels() != out.getNumChannels()*2)
		return kTTErrGeneric;

	for(channel=0; channel<numchannels; channel++){
		inSampleA = in.sampleVectors[channel];
		inSampleB = in.sampleVectors[numchannels+channel];
		outSample = out.sampleVectors[channel];
		vs = in.getVectorSize();

		while(vs--)
			*outSample++ = (*inSampleB++ * (sin(attrPosition * 1.5707963))) + (*inSampleA++ * (sin((1 - attrPosition) * 1.5707963)));
	}
	return kTTErrNone;
}

#if 0
#pragma mark -
#pragma mark Sidechain Process Methods
#endif

TTErr TTCrossfade::processLinearUsingSidechain(TTAudioSignal& in1, TTAudioSignal& in2, TTAudioSignal& out, TTAudioSignal&)
{
	TTUInt16		vs;
	TTSampleValue	*inSampleA,
					*inSampleB,
					*outSample;
	TTUInt8			numChannels = TTAudioSignal::getMinChannelCount(in1, in2, out);;
	TTUInt8			channel;

	for(channel=0; channel<numChannels; channel++){
		inSampleA = in1.sampleVectors[channel];
		inSampleB = in2.sampleVectors[channel];
		outSample = out.sampleVectors[channel];
		vs = in1.getVectorSize();

		while(vs--)
			*outSample++ = (*inSampleB++ * attrPosition) + (*inSampleA++ * (1.0 - attrPosition));
	}
	return kTTErrNone;
}

TTErr TTCrossfade::processLookupUsingSidechain(TTAudioSignal& in1, TTAudioSignal& in2, TTAudioSignal& out, TTAudioSignal&)
{
	TTUInt16		vs;
	TTSampleValue	*inSampleA,
					*inSampleB,
					*outSample;
	TTUInt8			numChannels = TTAudioSignal::getMinChannelCount(in1, in2, out);;
	TTUInt8			channel;
	int				index;

	for(channel=0; channel<numChannels; channel++){
		inSampleA = in1.sampleVectors[channel];
		inSampleB = in2.sampleVectors[channel];
		outSample = out.sampleVectors[channel];
		vs = in1.getVectorSize();

		while(vs--){
			index = (int)(attrPosition * 511.0);
			*outSample++ = (*inSampleB++ * kTTLookupEqualPower[511 - index]) + (*inSampleA++ * kTTLookupEqualPower[index]);
		}
	}
	return kTTErrNone;
}

TTErr TTCrossfade::processCalcUsingSidechain(TTAudioSignal& in1, TTAudioSignal& in2, TTAudioSignal& out, TTAudioSignal&)
{
	TTUInt16		vs;
	TTSampleValue	*inSampleA,
					*inSampleB,
					*outSample;
	TTUInt8			numChannels = TTAudioSignal::getMinChannelCount(in1, in2, out);;
	TTUInt8			channel;

	for(channel=0; channel<numChannels; channel++){
		inSampleA = in1.sampleVectors[channel];
		inSampleB = in2.sampleVectors[channel];
		outSample = out.sampleVectors[channel];
		vs = in1.getVectorSize();

		while(vs--)
			*outSample++ = (*inSampleB++ * (sin(attrPosition * 1.5707963))) + (*inSampleA++ * (sin((1 - attrPosition) * 1.5707963)));
	}
	return kTTErrNone;
}

<commit_msg>some initial work to try and handle cases of crossfading between signals with differing numbers of channels<commit_after>/*
 * TTBlue Signal Crossfader Object
 * Copyright © 2008, Timothy Place
 *
 * License: This code is licensed under the terms of the GNU LGPL
 * http://www.gnu.org/licenses/lgpl.html
 */

#include "TTCrossfade.h"

static bool zeroed = false;
static TTSampleValue zeroVector1[2048]; //TODO: make this dynamically sized
static TTSampleValue zeroVector2[2048]; //TODO: make this dynamically sized
static TTSampleValue zeroVector3[2048]; //TODO: make this dynamically sized

TTCrossfade::TTCrossfade(TTUInt8 newMaxNumChannels)
	: TTAudioObject("audio.crossfade", newMaxNumChannels), attrShape(*kTTSymEmpty), attrMode(*kTTSymEmpty)
{
	registerAttribute(TT("position"),	kTypeFloat64,	&attrPosition);
	registerAttribute(TT("shape"),		kTypeSymbol,	&attrShape,		(TTGetterMethod)NULL, (TTSetterMethod)&TTCrossfade::setShape);
	registerAttribute(TT("mode"),		kTypeSymbol,	&attrMode,		(TTGetterMethod)NULL, (TTSetterMethod)&TTCrossfade::setMode);

	if(!zeroed){
		memset(zeroVector1, 0, sizeof(TTSampleValue) * 2048);
		memset(zeroVector2, 0, sizeof(TTSampleValue) * 2048);
		memset(zeroVector3, 0, sizeof(TTSampleValue) * 2048);
	}

	// Set Defaults (the attribute setters will set the process method for us)...
	setAttributeValue(TT("position"),	0.5);
	setAttributeValue(TT("shape"),		TT("equalPower"));
	setAttributeValue(TT("mode"),		TT("lookup"));
}

TTCrossfade::~TTCrossfade()
{
	;
}

TTErr TTCrossfade::setShape(const TTValue& newValue)
{
	attrShape = newValue;
	return setProcessPointers();
}

TTErr TTCrossfade::setMode(const TTValue& newValue)
{
	attrMode = newValue;
	return setProcessPointers();
}

TTErr TTCrossfade::setProcessPointers()
{
	TTErr	err =kTTErrNone;

	if(attrShape == TT("equalPower") && attrMode == TT("lookup")){
		err |= setProcessWithSidechain((TTProcessWithSidechainMethod)&TTCrossfade::processLookupUsingSidechain);
		err |= setProcess((TTProcessMethod)&TTCrossfade::processLookup);
	}
	else if(attrShape == TT("equalPower") && attrMode == TT("calculate")){
		err |= setProcessWithSidechain((TTProcessWithSidechainMethod)&TTCrossfade::processCalcUsingSidechain);
		err |= setProcess((TTProcessMethod)&TTCrossfade::processCalc);
	}
	else{
		err |= setProcessWithSidechain((TTProcessWithSidechainMethod)&TTCrossfade::processLinearUsingSidechain);
		err |= setProcess((TTProcessMethod)&TTCrossfade::processLinear);
	}
	return err;
}

#if 0
#pragma mark -
#pragma mark Interleaved Process Methods
#endif

TTErr TTCrossfade::processLinear(TTAudioSignal& in, TTAudioSignal& out)
{
	short			vs;
	TTSampleValue	*inSampleA,
					*inSampleB,
					*outSample;
	short			numchannels = out.getNumChannels();
	short			channel;

	if(in.getNumChannels() != out.getNumChannels()*2)
		return kTTErrGeneric;

	for(channel=0; channel<numchannels; channel++){
		inSampleA = in.sampleVectors[channel];
		inSampleB = in.sampleVectors[numchannels+channel];
		outSample = out.sampleVectors[channel];
		vs = in.getVectorSize();

		while(vs--)
			*outSample++ = (*inSampleB++ * attrPosition) + (*inSampleA++ * (1.0 - attrPosition));
	}
	return kTTErrNone;
}

TTErr TTCrossfade::processLookup(TTAudioSignal& in, TTAudioSignal& out)
{
	short			vs;
	TTSampleValue	*inSampleA,
					*inSampleB,
					*outSample;
	short			numchannels = out.getNumChannels();
	short			channel;
	int				index;

	if(in.getNumChannels() != out.getNumChannels()*2)
		return kTTErrGeneric;

	for(channel=0; channel<numchannels; channel++){
		inSampleA = in.sampleVectors[channel];
		inSampleB = in.sampleVectors[numchannels+channel];
		outSample = out.sampleVectors[channel];
		vs = in.getVectorSize();

		while(vs--){
			index = (int)(attrPosition * 511.0);
			*outSample++ = (*inSampleB++ * kTTLookupEqualPower[511 - index]) + (*inSampleA++ * kTTLookupEqualPower[index]);
		}
	}
	return kTTErrNone;
}

TTErr TTCrossfade::processCalc(TTAudioSignal& in, TTAudioSignal& out)
{
	short			vs;
	TTSampleValue	*inSampleA,
					*inSampleB,
					*outSample;
	short			numchannels = out.getNumChannels();
	short			channel;

	if(in.getNumChannels() != out.getNumChannels()*2)
		return kTTErrGeneric;

	for(channel=0; channel<numchannels; channel++){
		inSampleA = in.sampleVectors[channel];
		inSampleB = in.sampleVectors[numchannels+channel];
		outSample = out.sampleVectors[channel];
		vs = in.getVectorSize();

		while(vs--)
			*outSample++ = (*inSampleB++ * (sin(attrPosition * 1.5707963))) + (*inSampleA++ * (sin((1 - attrPosition) * 1.5707963)));
	}
	return kTTErrNone;
}

#if 0
#pragma mark -
#pragma mark Sidechain Process Methods
#endif

TTErr TTCrossfade::processLinearUsingSidechain(TTAudioSignal& in1, TTAudioSignal& in2, TTAudioSignal& out, TTAudioSignal&)
{
	TTUInt16		vs;
	TTSampleValue	*inSampleA,
					*inSampleB,
					*outSample;
	TTUInt8			numChannels = TTAudioSignal::getMaxChannelCount(in1, in2, out);;
	TTUInt8			channel;

	for(channel=0; channel<numChannels; channel++){
//		inSampleA = in1.sampleVectors[channel];
//		inSampleB = in2.sampleVectors[channel];
//		outSample = out.sampleVectors[channel];
		if(channel < in1.getNumChannels())
			inSampleA = in1.sampleVectors[channel];
		else
			inSampleA = zeroVector1;

		if(channel < in2.getNumChannels())
			inSampleB = in2.sampleVectors[channel];
		else
			inSampleB = zeroVector2;

		if(channel < out.getNumChannels())
			outSample = out.sampleVectors[channel];
		else
			outSample = zeroVector3;

		vs = in1.getVectorSize();

		while(vs--)
			*outSample++ = (*inSampleB++ * attrPosition) + (*inSampleA++ * (1.0 - attrPosition));
	}
	return kTTErrNone;
}

TTErr TTCrossfade::processLookupUsingSidechain(TTAudioSignal& in1, TTAudioSignal& in2, TTAudioSignal& out, TTAudioSignal&)
{
	TTUInt16		vs;
	TTSampleValue	*inSampleA,
					*inSampleB,
					*outSample;
	TTUInt8			numChannels = TTAudioSignal::getMaxChannelCount(in1, in2, out);;
	TTUInt8			channel;
	int				index;

	for(channel=0; channel<numChannels; channel++){
		if(channel < in1.getNumChannels())
			inSampleA = in1.sampleVectors[channel];
		else
			inSampleA = zeroVector1;

		if(channel < in2.getNumChannels())
			inSampleB = in2.sampleVectors[channel];
		else
			inSampleB = zeroVector2;

		if(channel < out.getNumChannels())
			outSample = out.sampleVectors[channel];
		else
			outSample = zeroVector3;

		vs = in1.getVectorSize();

		while(vs--){
			index = (int)(attrPosition * 511.0);
			*outSample++ = (*inSampleB++ * kTTLookupEqualPower[511 - index]) + (*inSampleA++ * kTTLookupEqualPower[index]);
		}
	}
	return kTTErrNone;
}

TTErr TTCrossfade::processCalcUsingSidechain(TTAudioSignal& in1, TTAudioSignal& in2, TTAudioSignal& out, TTAudioSignal&)
{
	TTUInt16		vs;
	TTSampleValue	*inSampleA,
					*inSampleB,
					*outSample;
	TTUInt8			numChannels = TTAudioSignal::getMinChannelCount(in1, in2, out);;
	TTUInt8			channel;

	for(channel=0; channel<numChannels; channel++){
		inSampleA = in1.sampleVectors[channel];
		inSampleB = in2.sampleVectors[channel];
		outSample = out.sampleVectors[channel];
		vs = in1.getVectorSize();

		while(vs--)
			*outSample++ = (*inSampleB++ * (sin(attrPosition * 1.5707963))) + (*inSampleA++ * (sin((1 - attrPosition) * 1.5707963)));
	}
	return kTTErrNone;
}

<|endoftext|>


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

// include system headers
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <sstream>

// include openGL headers
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>

#include <wcl/camera/CameraException.h>
#include <wcl/camera/VirtualCamera.h>
#include <wcl/camera/CameraFactory.h>

#define WIDTH 640

using namespace std;
using namespace wcl;

Camera *cam;
unsigned char* data;

void usage()
{
    printf("Usage: camera [devicenode]\n"
	   "\n"
	   "eg: camera /dev/video0\n"
	   "\n"
	   "If no device node is given the first available camera is used. If no physical camera exists, the virtual camera is used\n"
	  );
}

/**
 * Initialise OpenGL
 */
GLvoid init()
{
	glShadeModel(GL_SMOOTH);
	glClearColor(0,0,0,0);
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);

	data = new unsigned char[cam->getFormatBufferSize(Camera::RGB8)];

	// create a texture for the image...
	glTexImage2D(GL_TEXTURE_2D,             //target
				 0,                         //level of detail
				 3,                         //colour components
				 cam->getActiveConfiguration().width,     //width
				 cam->getActiveConfiguration().height,    //height
				 0,                         //border
				 GL_RGB,                    //image format
				 GL_UNSIGNED_BYTE,
				 data);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);

	glEnable(GL_TEXTURE_2D);

	glMatrixMode(GL_PROJECTION);
	gluOrtho2D(0,1,0,1);
	glMatrixMode(GL_MODELVIEW);
}

/**
 * Constantly fetch a new image from the camera to display
 */
GLvoid idle()
{
	glutPostRedisplay();
}

/**
 * Display Loop.
 */
GLvoid display()
{
	glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);

	const unsigned char* frame = cam->getFrame(Camera::RGB8);
	glTexSubImage2D(GL_TEXTURE_2D,
	                0,
					0,
					0,
					cam->getActiveConfiguration().width,
					cam->getActiveConfiguration().height,
					GL_RGB,
					GL_UNSIGNED_BYTE,
					frame);

	glMatrixMode(GL_MODELVIEW);

	glLoadIdentity();
		glColor3f(1,0,0);
		glBegin(GL_QUADS);

		glTexCoord2f(0,1);
		glVertex2f(0,0);

		glTexCoord2f(1,1);
		glVertex2f(1,0);

		glTexCoord2f(1,0);
		glVertex2f(1,1);

		glTexCoord2f(0,0);
		glVertex2f(0,1);
	glEnd();

	glFlush();
	glutSwapBuffers();

	// print out any opengl errors to the console
	GLenum error = glGetError();
	if (error != GL_NO_ERROR)
	{
		cout << gluErrorString(error) << endl;
	}
}

/**
 * This doesn't do what it is supposed to do!
 */
GLvoid reshape(int width, int height)
{
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluOrtho2D(0,1,0,1);
	glMatrixMode(GL_MODELVIEW);
	glViewport(0,0, (GLsizei)width, (GLsizei)height);
}

void keyboard(unsigned char key, int w, int h)
{
    if(key==27)
	exit(EXIT_SUCCESS);
}

int main(int argc, char** argv)
{
    if(argc >=  2 &&
       (strcmp(argv[1],"--help") == 0 ||
        strcmp(argv[1],"-h" ) == 0)){
	usage();
	return 1;
    }

    try {

	if( argc == 2 ){
	    cout << "Attempting to use Camera specified:" << argv[1] <<endl;
	    cam = CameraFactory::getCamera(argv[1], CameraFactory::ALL);
	} else {
	    cout << "No Camera Specified, using CameraFactory to find the first camera..." << endl;
	    std::vector<Camera *> cameras = CameraFactory::getCameras(CameraFactory::ALL);
	    CameraFactory::printDetails(false);

	    if( cameras.size() == 0 ){
		cout << "No physical camera's found, using virtual camera" << endl;
		cam = new VirtualCamera();
	    } else {
		cam = CameraFactory::getCamera(CameraFactory::ALL);
	    }
	}
	if (cam == NULL ){
	    std::cout << "No usable cameras found" << std::endl;
	    exit(0);
	}

	/*
	 * Print out camera details
	 */
	cam->printDetails();

	cout << "Setting Camera to a width of " << WIDTH << " pixels" << endl;

	Camera::Configuration c;
	c.width = WIDTH;
	cam->setConfiguration(cam->findConfiguration(c));

	//Set power frequency compensation to 50 Hz
	//this is noncritical so don't stop the program if it fails
	try {
	cam->setControlValue(Camera::POWER_FREQUENCY, 1);
	}catch(CameraException &e){}

	// Create GLUT window
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
	glutInitWindowSize(cam->getActiveConfiguration().width, cam->getActiveConfiguration().height);
	glutCreateWindow(argv[0]);

	init();

	// register callbacks
	glutDisplayFunc(display);
	glutReshapeFunc(reshape);
	glutKeyboardFunc(keyboard);
	glutIdleFunc(idle);

	// GO!
	glutMainLoop();

	cout << "Deleting Cam" << endl;

	cam->shutdown();
	delete cam;

    }
    catch (Exception &e)
    {
	cout << "Exception Occured: " << e.what() << endl;
    }

    return 0;
}

<commit_msg>example: Add the ability to list what cameras exist via -l<commit_after>/*-
 * Copyright (c) 2008 Michael Marner <michael@20papercups.net>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

// include system headers
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <sstream>

// include openGL headers
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>

#include <wcl/camera/CameraException.h>
#include <wcl/camera/VirtualCamera.h>
#include <wcl/camera/CameraFactory.h>

#define WIDTH 640

using namespace std;
using namespace wcl;

Camera *cam;
unsigned char* data;

void usage()
{
    printf("Usage: camera [-l|-h|devicenode]\n"
	   "\n"
	   "eg: camera /dev/video0\n"
	   "\n"
	   "Options:\n"
	   "\n"
	   "-h = List this help\n"
	   "-l = List available cameras then exit\n"
	   "If no device node is given the first available camera is used. If no physical camera exists, the virtual camera is used\n"
	  );
}

/**
 * Initialise OpenGL
 */
GLvoid init()
{
	glShadeModel(GL_SMOOTH);
	glClearColor(0,0,0,0);
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);

	data = new unsigned char[cam->getFormatBufferSize(Camera::RGB8)];

	// create a texture for the image...
	glTexImage2D(GL_TEXTURE_2D,             //target
				 0,                         //level of detail
				 3,                         //colour components
				 cam->getActiveConfiguration().width,     //width
				 cam->getActiveConfiguration().height,    //height
				 0,                         //border
				 GL_RGB,                    //image format
				 GL_UNSIGNED_BYTE,
				 data);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);

	glEnable(GL_TEXTURE_2D);

	glMatrixMode(GL_PROJECTION);
	gluOrtho2D(0,1,0,1);
	glMatrixMode(GL_MODELVIEW);
}

/**
 * Constantly fetch a new image from the camera to display
 */
GLvoid idle()
{
	glutPostRedisplay();
}

/**
 * Display Loop.
 */
GLvoid display()
{
	glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);

	const unsigned char* frame = cam->getFrame(Camera::RGB8);
	glTexSubImage2D(GL_TEXTURE_2D,
	                0,
					0,
					0,
					cam->getActiveConfiguration().width,
					cam->getActiveConfiguration().height,
					GL_RGB,
					GL_UNSIGNED_BYTE,
					frame);

	glMatrixMode(GL_MODELVIEW);

	glLoadIdentity();
		glColor3f(1,0,0);
		glBegin(GL_QUADS);

		glTexCoord2f(0,1);
		glVertex2f(0,0);

		glTexCoord2f(1,1);
		glVertex2f(1,0);

		glTexCoord2f(1,0);
		glVertex2f(1,1);

		glTexCoord2f(0,0);
		glVertex2f(0,1);
	glEnd();

	glFlush();
	glutSwapBuffers();

	// print out any opengl errors to the console
	GLenum error = glGetError();
	if (error != GL_NO_ERROR)
	{
		cout << gluErrorString(error) << endl;
	}
}

/**
 * This doesn't do what it is supposed to do!
 */
GLvoid reshape(int width, int height)
{
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluOrtho2D(0,1,0,1);
	glMatrixMode(GL_MODELVIEW);
	glViewport(0,0, (GLsizei)width, (GLsizei)height);
}

void keyboard(unsigned char key, int w, int h)
{
    if(key==27)
	exit(EXIT_SUCCESS);
}

void listCameras()
{
    cout << "Searching for Cameras..." << endl;
    std::vector<Camera *> cameras = CameraFactory::getCameras(CameraFactory::ALL);
    CameraFactory::printDetails(false);
}

int main(int argc, char** argv)
{
    if(argc >= 2){
       if( strcmp(argv[1],"--help") == 0 || strcmp(argv[1],"-h" ) == 0){
	usage();
	return 1;
       }
       if( strcmp(argv[1],"-l") == 0){
	   listCameras();
	   return 1;
       }
    }

    try {

	if( argc == 2 ){
	    cout << "Attempting to use Camera specified:" << argv[1] <<endl;
	    cam = CameraFactory::getCamera(argv[1], CameraFactory::ALL);
	} else {
	    cout << "No Camera Specified, using CameraFactory to find the first camera..." << endl;
	    cout << "Searching for Cameras..." << endl;
	    std::vector<Camera *> cameras = CameraFactory::getCameras(CameraFactory::ALL);
	    CameraFactory::printDetails(false);

	    if( cameras.size() == 0 ){
		cout << "No physical camera's found, using virtual camera" << endl;
		cam = new VirtualCamera();
	    } else {
		cam = CameraFactory::getCamera(CameraFactory::ALL);
	    }
	}
	if (cam == NULL ){
	    std::cout << "No usable cameras found" << std::endl;
	    exit(0);
	}

	/*
	 * Print out camera details
	 */
	cam->printDetails();

	cout << "Setting Camera to a width of " << WIDTH << " pixels" << endl;

	Camera::Configuration c;
	c.width = WIDTH;
	cam->setConfiguration(cam->findConfiguration(c));

	//Set power frequency compensation to 50 Hz
	//this is noncritical so don't stop the program if it fails
	try {
	cam->setControlValue(Camera::POWER_FREQUENCY, 1);
	}catch(CameraException &e){}

	// Create GLUT window
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
	glutInitWindowSize(cam->getActiveConfiguration().width, cam->getActiveConfiguration().height);
	glutCreateWindow(argv[0]);

	init();

	// register callbacks
	glutDisplayFunc(display);
	glutReshapeFunc(reshape);
	glutKeyboardFunc(keyboard);
	glutIdleFunc(idle);

	// GO!
	glutMainLoop();

	cout << "Deleting Cam" << endl;

	cam->shutdown();
	delete cam;

    }
    catch (Exception &e)
    {
	cout << "Exception Occured: " << e.what() << endl;
    }

    return 0;
}

<|endoftext|>


<commit_before>
#include <crcpp/crcpp.h>

// Reflect the entire namespace and implement each class
crcpp_reflect(TestClassImpl)
namespace TestClassImpl
{
	class A
	{
	public:
		A()
		{
			x = 1;
			y = 2;
			z = 3;
		}

		int x, y, z;
	};

	struct B
	{
		B()
		{
			a = 1.5f;
			b = 2.5f;
			c = 3.5f;
		}

		float a, b, c;
	};
}

crcpp_impl_class(TestClassImpl::A, A)
crcpp_impl_class(TestClassImpl::B, B)

void TestConstructorDestructor(crcpp::Database& db)
{
	const crcpp::Class* ca = crcpp_get_type(db, TestClassImpl::A)->AsClass();
	const crcpp::Class* cb = crcpp_get_type(db, TestClassImpl::B)->AsClass();

	TestClassImpl::A* a = (TestClassImpl::A*)new char[sizeof(TestClassImpl::A)];
	TestClassImpl::B* b = (TestClassImpl::B*)new char[sizeof(TestClassImpl::B)];

	typedef void (*ClassImplFunc)(void*);
	ClassImplFunc cona = (ClassImplFunc)ca->constructor->address;
	ClassImplFunc conb = (ClassImplFunc)cb->constructor->address;
	ClassImplFunc desa = (ClassImplFunc)ca->destructor->address;
	ClassImplFunc desb = (ClassImplFunc)cb->destructor->address;

	cona(a);
	conb(b);

	desa(a);
	desb(b);

	delete [] (char*) a;
	delete [] (char*) b;
}<commit_msg>Interesting concept... getting too close to a function library, though.<commit_after>
#include <crcpp/crcpp.h>

// Reflect the entire namespace and implement each class
crcpp_reflect(TestClassImpl)
namespace TestClassImpl
{
	class A
	{
	public:
		A()
		{
			x = 1;
			y = 2;
			z = 3;
		}

		int x, y, z;
	};

	struct B
	{
		B()
		{
			a = 1.5f;
			b = 2.5f;
			c = 3.5f;
		}

		float a, b, c;
	};
}

crcpp_impl_class(TestClassImpl::A, A)
crcpp_impl_class(TestClassImpl::B, B)

template <typename A0> void Call(const crcpp::Function* function, A0 a0)
{
	typedef void (*CallFunc)(A0);
	CallFunc call_func = (CallFunc)function->address;
	call_func(a0);
}

void TestConstructorDestructor(crcpp::Database& db)
{
	const crcpp::Class* ca = crcpp_get_type(db, TestClassImpl::A)->AsClass();
	const crcpp::Class* cb = crcpp_get_type(db, TestClassImpl::B)->AsClass();

	TestClassImpl::A* a = (TestClassImpl::A*)new char[sizeof(TestClassImpl::A)];
	TestClassImpl::B* b = (TestClassImpl::B*)new char[sizeof(TestClassImpl::B)];

	Call(ca->constructor, a);
	Call(cb->constructor, b);

	Call(ca->destructor, a);
	Call(cb->destructor, b);

	delete [] (char*) a;
	delete [] (char*) b;
}<|endoftext|>


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

#include "paintinstruments.h"
#include "imagearea.h"
#include "easypaintenums.h"
#include "datasingleton.h"

#include <QtGui/QPainter>
#include <QtGui/QLabel>
#include <math.h>

PaintInstruments::PaintInstruments(ImageArea *pImageArea, QObject *parent) :
    QObject(parent)
{
    mPImageArea = pImageArea;
}

PaintInstruments::~PaintInstruments()
{

}

void PaintInstruments::line(bool isSecondColor, bool isLastic)
{
    QPainter painter(mPImageArea->getImage());
    if(isLastic)
    {
        painter.setPen(QPen(Qt::white, DataSingleton::Instance()->getPenSize(),
                            Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
    }
    else
    {
        if(isSecondColor)
        {
            painter.setPen(QPen(DataSingleton::Instance()->getSecondColor(),
                                DataSingleton::Instance()->getPenSize(),
                                Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
        }
        else
        {
            painter.setPen(QPen(DataSingleton::Instance()->getFirstColor(),
                                DataSingleton::Instance()->getPenSize(),
                                Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
        }
    }

    if(mStartPoint != mEndPoint)
    {
        painter.drawLine(mStartPoint, mEndPoint);
    }
    if(DataSingleton::Instance()->getInstrument() == PEN && mStartPoint == mEndPoint)
    {
        if(DataSingleton::Instance()->getPenSize() > 1)
        {
            painter.setPen(QPen(DataSingleton::Instance()->getFirstColor(),
                                round(DataSingleton::Instance()->getPenSize() / 2),
                                Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
            painter.drawRect(QRect(mStartPoint, mEndPoint));
        }
        else
        {
            painter.drawPoint(mStartPoint);
        }
    }
    mPImageArea->setEdited(true);
//    int rad(DataSingleton::Instance()->getPenSize() + round(sqrt((mStartPoint.x() - mEndPoint.x()) *
//                                                                 (mStartPoint.x() - mEndPoint.x()) +
//                                                                 (mStartPoint.y() - mEndPoint.y()) *
//                                                                 (mStartPoint.y() - mEndPoint.y()))));
//    mPImageArea->update(QRect(mStartPoint, mEndPoint).normalized().adjusted(-rad, -rad, +rad, +rad));
    painter.end();
    mPImageArea->update();
}

void PaintInstruments::pipette(bool isSecondColor)
{
    bool inArea(true);
    if(mStartPoint.x() < 0 || mStartPoint.y() < 0
            || mStartPoint.x() > mPImageArea->getImage()->width()
            || mStartPoint.y() > mPImageArea->getImage()->height())
        inArea = false;

    if(inArea && isSecondColor)
    {
        QRgb pixel(mPImageArea->getImage()->pixel(mStartPoint));
        QColor getColor(pixel);
        DataSingleton::Instance()->setSecondColor(getColor);
    }
    if(inArea)
    {
        QRgb pixel(mPImageArea->getImage()->pixel(mStartPoint));
        QColor getColor(pixel);
        DataSingleton::Instance()->setFirstColor(getColor);
    }
}

void PaintInstruments::rect(bool isSecondColor)
{
    QPainter painter(mPImageArea->getImage());
    painter.setPen(QPen(DataSingleton::Instance()->getFirstColor(),
                        DataSingleton::Instance()->getPenSize(),
                        Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
    if(isSecondColor)
    {
        painter.setBrush(QBrush(DataSingleton::Instance()->getSecondColor()));
    }
    if(mStartPoint != mEndPoint)
    {
        painter.drawRect(QRect(mStartPoint, mEndPoint));
    }
    mPImageArea->setEdited(true);
//    int rad(DataSingleton::Instance()->getPenSize() + round(sqrt((mStartPoint.x() - mEndPoint.x()) *
//                                                                 (mStartPoint.x() - mEndPoint.x()) +
//                                                                 (mStartPoint.y() - mEndPoint.y()) *
//                                                                 (mStartPoint.y() - mEndPoint.y()))));
//    mPImageArea->update(QRect(mStartPoint, mEndPoint).normalized().adjusted(-rad, -rad, +rad, +rad));
    painter.end();
    mPImageArea->update();
}

void PaintInstruments::ellipse(bool isSecondColor)
{
    QPainter painter(mPImageArea->getImage());
    painter.setPen(QPen(DataSingleton::Instance()->getFirstColor(),
                        DataSingleton::Instance()->getPenSize(),
                        Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
    if(isSecondColor)
    {
        painter.setBrush(QBrush(DataSingleton::Instance()->getSecondColor()));
    }
    if(mStartPoint != mEndPoint)
    {
        painter.drawEllipse(QRect(mStartPoint, mEndPoint));
    }
    mPImageArea->setEdited(true);
//    int rad(DataSingleton::Instance()->getPenSize() + round(sqrt((mStartPoint.x() - mEndPoint.x()) *
//                                                                 (mStartPoint.x() - mEndPoint.x()) +
//                                                                 (mStartPoint.y() - mEndPoint.y()) *
//                                                                 (mStartPoint.y() - mEndPoint.y()))));
//    mPImageArea->update(QRect(mStartPoint, mEndPoint).normalized().adjusted(-rad, -rad, +rad, +rad));
    painter.end();
    mPImageArea->update();
}

void PaintInstruments::spray(bool isSecondColor)
{
    QPainter painter(mPImageArea->getImage());
    if(isSecondColor)
    {
        painter.setPen(QPen(DataSingleton::Instance()->getSecondColor(),
                            sqrt(DataSingleton::Instance()->getPenSize()),
                            Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
    }
    else
    {
        painter.setPen(QPen(DataSingleton::Instance()->getFirstColor(),
                            sqrt(DataSingleton::Instance()->getPenSize()),
                            Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
    }

    for(int i(0); i < 10; i++)
    {
        int x = qrand() %
                ((7 + 1) + 7) * sqrt(DataSingleton::Instance()->getPenSize()) -
                7 * sqrt(DataSingleton::Instance()->getPenSize());
        int y = qrand() %
                ((7 + 1) + 7) * sqrt(DataSingleton::Instance()->getPenSize()) -
                7 * sqrt(DataSingleton::Instance()->getPenSize());
        painter.drawLine(mEndPoint.x() + x,
                         mEndPoint.y() + y,
                         mEndPoint.x() + x + 1,
                         mEndPoint.y() + y + 1);
    }
    mPImageArea->setEdited(true);
    painter.end();
    mPImageArea->update();
}

void PaintInstruments::fill(bool isSecondColor)
{
    QColor switchColor;
    if(!isSecondColor)
    {
        switchColor = DataSingleton::Instance()->getFirstColor();
    }
    else
    {
        switchColor = DataSingleton::Instance()->getSecondColor();
    }

    QRgb pixel(mPImageArea->getImage()->pixel(mStartPoint));
    QColor oldColor(pixel);

    if(switchColor != oldColor)
    {
        fillRecurs(mStartPoint.x(), mStartPoint.y(),
                       switchColor, oldColor,
                       *mPImageArea->getImage());
    }

    mPImageArea->setEdited(true);
    mPImageArea->update();
}

void PaintInstruments::fillRecurs(int x, int y, QColor switchColor, QColor oldColor, QImage &tempImage)
{
    int temp_x(x), left_x(0);
    while(1)
    {
        QRgb pixsel(tempImage.pixel(temp_x, y));
        QColor currentColor;
        currentColor.setRgb(pixsel);
        if(currentColor != oldColor)
            break;
        pixsel = switchColor.rgb();
        tempImage.setPixel(temp_x, y, pixsel);
        if(temp_x > 0)
        {
            temp_x--;
            left_x = temp_x;
        }
        else
            break;
    }

    int right_x(0);
    temp_x = x + 1;
    while(1)
    {
        QRgb pixsel(tempImage.pixel(temp_x, y));
        QColor currentColor;
        currentColor.setRgb(pixsel);
        if(currentColor != oldColor)
            break;
        pixsel = switchColor.rgb();
        tempImage.setPixel(temp_x, y, pixsel);
        if(temp_x < tempImage.width() - 1)
        {
            temp_x++;
            right_x = temp_x;
        }
        else
            break;
    }

    for(int x_(left_x+1); x_ < right_x; x_++)
    {
        if(y < 1)
            break;
        if(right_x > tempImage.width())
            break;
        QRgb pixsel(tempImage.pixel(x_, y-1));
        QColor currentColor;
        currentColor.setRgb(pixsel);
        if(currentColor == oldColor && currentColor != switchColor)
            fillRecurs(x_, y-1, switchColor, oldColor, tempImage);
    }
    for(int x_(left_x+1); x_ < right_x; x_++)
    {
        if(y >= tempImage.height() - 1)
            break;
        if(right_x > tempImage.width())
            break;
        QRgb pixsel(tempImage.pixel(x_, y+1));
        QColor currentColor;
        currentColor.setRgb(pixsel);
        if(currentColor == oldColor && currentColor != switchColor)
            fillRecurs(x_, y+1, switchColor, oldColor, tempImage);
    }
}
<commit_msg>Changed spray mechanism<commit_after>/*
 * This source file is part of EasyPaint.
 *
 * Copyright (c) 2012 EasyPaint <https://github.com/Gr1N/EasyPaint>
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include "paintinstruments.h"
#include "imagearea.h"
#include "easypaintenums.h"
#include "datasingleton.h"

#include <QtGui/QPainter>
#include <QtGui/QLabel>
#include <math.h>

PaintInstruments::PaintInstruments(ImageArea *pImageArea, QObject *parent) :
    QObject(parent)
{
    mPImageArea = pImageArea;
}

PaintInstruments::~PaintInstruments()
{

}

void PaintInstruments::line(bool isSecondColor, bool isLastic)
{
    QPainter painter(mPImageArea->getImage());
    if(isLastic)
    {
        painter.setPen(QPen(Qt::white, DataSingleton::Instance()->getPenSize(),
                            Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
    }
    else
    {
        if(isSecondColor)
        {
            painter.setPen(QPen(DataSingleton::Instance()->getSecondColor(),
                                DataSingleton::Instance()->getPenSize(),
                                Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
        }
        else
        {
            painter.setPen(QPen(DataSingleton::Instance()->getFirstColor(),
                                DataSingleton::Instance()->getPenSize(),
                                Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
        }
    }

    if(mStartPoint != mEndPoint)
    {
        painter.drawLine(mStartPoint, mEndPoint);
    }
    if(DataSingleton::Instance()->getInstrument() == PEN && mStartPoint == mEndPoint)
    {
        if(DataSingleton::Instance()->getPenSize() > 1)
        {
            painter.setPen(QPen(DataSingleton::Instance()->getFirstColor(),
                                round(DataSingleton::Instance()->getPenSize() / 2),
                                Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
            painter.drawRect(QRect(mStartPoint, mEndPoint));
        }
        else
        {
            painter.drawPoint(mStartPoint);
        }
    }
    mPImageArea->setEdited(true);
//    int rad(DataSingleton::Instance()->getPenSize() + round(sqrt((mStartPoint.x() - mEndPoint.x()) *
//                                                                 (mStartPoint.x() - mEndPoint.x()) +
//                                                                 (mStartPoint.y() - mEndPoint.y()) *
//                                                                 (mStartPoint.y() - mEndPoint.y()))));
//    mPImageArea->update(QRect(mStartPoint, mEndPoint).normalized().adjusted(-rad, -rad, +rad, +rad));
    painter.end();
    mPImageArea->update();
}

void PaintInstruments::pipette(bool isSecondColor)
{
    bool inArea(true);
    if(mStartPoint.x() < 0 || mStartPoint.y() < 0
            || mStartPoint.x() > mPImageArea->getImage()->width()
            || mStartPoint.y() > mPImageArea->getImage()->height())
        inArea = false;

    if(inArea && isSecondColor)
    {
        QRgb pixel(mPImageArea->getImage()->pixel(mStartPoint));
        QColor getColor(pixel);
        DataSingleton::Instance()->setSecondColor(getColor);
    }
    if(inArea)
    {
        QRgb pixel(mPImageArea->getImage()->pixel(mStartPoint));
        QColor getColor(pixel);
        DataSingleton::Instance()->setFirstColor(getColor);
    }
}

void PaintInstruments::rect(bool isSecondColor)
{
    QPainter painter(mPImageArea->getImage());
    painter.setPen(QPen(DataSingleton::Instance()->getFirstColor(),
                        DataSingleton::Instance()->getPenSize(),
                        Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
    if(isSecondColor)
    {
        painter.setBrush(QBrush(DataSingleton::Instance()->getSecondColor()));
    }
    if(mStartPoint != mEndPoint)
    {
        painter.drawRect(QRect(mStartPoint, mEndPoint));
    }
    mPImageArea->setEdited(true);
//    int rad(DataSingleton::Instance()->getPenSize() + round(sqrt((mStartPoint.x() - mEndPoint.x()) *
//                                                                 (mStartPoint.x() - mEndPoint.x()) +
//                                                                 (mStartPoint.y() - mEndPoint.y()) *
//                                                                 (mStartPoint.y() - mEndPoint.y()))));
//    mPImageArea->update(QRect(mStartPoint, mEndPoint).normalized().adjusted(-rad, -rad, +rad, +rad));
    painter.end();
    mPImageArea->update();
}

void PaintInstruments::ellipse(bool isSecondColor)
{
    QPainter painter(mPImageArea->getImage());
    painter.setPen(QPen(DataSingleton::Instance()->getFirstColor(),
                        DataSingleton::Instance()->getPenSize(),
                        Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
    if(isSecondColor)
    {
        painter.setBrush(QBrush(DataSingleton::Instance()->getSecondColor()));
    }
    if(mStartPoint != mEndPoint)
    {
        painter.drawEllipse(QRect(mStartPoint, mEndPoint));
    }
    mPImageArea->setEdited(true);
//    int rad(DataSingleton::Instance()->getPenSize() + round(sqrt((mStartPoint.x() - mEndPoint.x()) *
//                                                                 (mStartPoint.x() - mEndPoint.x()) +
//                                                                 (mStartPoint.y() - mEndPoint.y()) *
//                                                                 (mStartPoint.y() - mEndPoint.y()))));
//    mPImageArea->update(QRect(mStartPoint, mEndPoint).normalized().adjusted(-rad, -rad, +rad, +rad));
    painter.end();
    mPImageArea->update();
}

void PaintInstruments::spray(bool isSecondColor)
{
    QPainter painter(mPImageArea->getImage());
    if(isSecondColor)
    {
        painter.setPen(QPen(DataSingleton::Instance()->getSecondColor(),
                            sqrt(DataSingleton::Instance()->getPenSize()),
                            Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
    }
    else
    {
        painter.setPen(QPen(DataSingleton::Instance()->getFirstColor(),
                            sqrt(DataSingleton::Instance()->getPenSize()),
                            Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
    }

    int x, y;
    for(int i(0); i < 12; i++)
    {
        switch(i) {
        case 0: case 1: case 2: case 3:
            x = (qrand() % 5 - 2)
                    * sqrt(DataSingleton::Instance()->getPenSize());
            y = (qrand() % 5 - 2)
                    * sqrt(DataSingleton::Instance()->getPenSize());
            break;
        case 4: case 5: case 6: case 7:
            x = (qrand() % 10 - 4)
                    * sqrt(DataSingleton::Instance()->getPenSize());
            y = (qrand() % 10 - 4)
                    * sqrt(DataSingleton::Instance()->getPenSize());
            break;
        case 8: case 9: case 10: case 11:
            x = (qrand() % 15 - 7)
                    * sqrt(DataSingleton::Instance()->getPenSize());
            y = (qrand() % 15 - 7)
                    * sqrt(DataSingleton::Instance()->getPenSize());
            break;
        }
        painter.drawPoint(mEndPoint.x() + x,
                         mEndPoint.y() + y);
    }
    mPImageArea->setEdited(true);
    painter.end();
    mPImageArea->update();
}

void PaintInstruments::fill(bool isSecondColor)
{
    QColor switchColor;
    if(!isSecondColor)
    {
        switchColor = DataSingleton::Instance()->getFirstColor();
    }
    else
    {
        switchColor = DataSingleton::Instance()->getSecondColor();
    }

    QRgb pixel(mPImageArea->getImage()->pixel(mStartPoint));
    QColor oldColor(pixel);

    if(switchColor != oldColor)
    {
        fillRecurs(mStartPoint.x(), mStartPoint.y(),
                       switchColor, oldColor,
                       *mPImageArea->getImage());
    }

    mPImageArea->setEdited(true);
    mPImageArea->update();
}

void PaintInstruments::fillRecurs(int x, int y, QColor switchColor, QColor oldColor, QImage &tempImage)
{
    int temp_x(x), left_x(0);
    while(1)
    {
        QRgb pixsel(tempImage.pixel(temp_x, y));
        QColor currentColor;
        currentColor.setRgb(pixsel);
        if(currentColor != oldColor)
            break;
        pixsel = switchColor.rgb();
        tempImage.setPixel(temp_x, y, pixsel);
        if(temp_x > 0)
        {
            temp_x--;
            left_x = temp_x;
        }
        else
            break;
    }

    int right_x(0);
    temp_x = x + 1;
    while(1)
    {
        QRgb pixsel(tempImage.pixel(temp_x, y));
        QColor currentColor;
        currentColor.setRgb(pixsel);
        if(currentColor != oldColor)
            break;
        pixsel = switchColor.rgb();
        tempImage.setPixel(temp_x, y, pixsel);
        if(temp_x < tempImage.width() - 1)
        {
            temp_x++;
            right_x = temp_x;
        }
        else
            break;
    }

    for(int x_(left_x+1); x_ < right_x; x_++)
    {
        if(y < 1)
            break;
        if(right_x > tempImage.width())
            break;
        QRgb pixsel(tempImage.pixel(x_, y-1));
        QColor currentColor;
        currentColor.setRgb(pixsel);
        if(currentColor == oldColor && currentColor != switchColor)
            fillRecurs(x_, y-1, switchColor, oldColor, tempImage);
    }
    for(int x_(left_x+1); x_ < right_x; x_++)
    {
        if(y >= tempImage.height() - 1)
            break;
        if(right_x > tempImage.width())
            break;
        QRgb pixsel(tempImage.pixel(x_, y+1));
        QColor currentColor;
        currentColor.setRgb(pixsel);
        if(currentColor == oldColor && currentColor != switchColor)
            fillRecurs(x_, y+1, switchColor, oldColor, tempImage);
    }
}
<|endoftext|>


<commit_before>#include "ModelEditor.hpp"

#include <Engine/Geometry/Model.hpp>
#include "../FileSelector.hpp"
#include <functional>
#include <Engine/Hymn.hpp>
#include <Engine/Util/FileSystem.hpp>
#include <imgui.h>
#include "Util/AssetMetaData.hpp"
#include <Utility/Log.hpp>
#include "../../Resources.hpp"
#include <Engine/Manager/Managers.hpp>
#include <Engine/Manager/ResourceManager.hpp>
#include <Engine/Entity/Entity.hpp>
#include <Engine/Component/Mesh.hpp>

using namespace GUI;

ModelEditor::ModelEditor() {
    name[0] = '\0';
}

void ModelEditor::Show() {
    if (ImGui::Begin(("Model: " + model->name + "###" + std::to_string(reinterpret_cast<uintptr_t>(model))).c_str(), &visible, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_ShowBorders)) {
        if (ImGui::InputText("Name", name, 128, ImGuiInputTextFlags_EnterReturnsTrue)) {
            model->name = name;

            // Rename all the files.
            if (FileSystem::FileExists((destination + ".fbx").c_str())) {
                FileSystem::Rename(destination + ".fbx", std::string(name) + ".fbx");

                if (FileSystem::FileExists((destination + ".asset").c_str()))
                    FileSystem::Rename(destination + ".asset", std::string(name) + ".asset");

                if (FileSystem::FileExists((destination + ".asset.meta").c_str()))
                    FileSystem::Rename(destination + ".asset.meta", std::string(name) + ".asset.meta");

                destination = Hymn().GetPath() + FileSystem::DELIMITER + "Models" + FileSystem::DELIMITER + name;
            }
        }

        if (ImGui::Button("Open model")) {
            // Currently only fbx is tested.
            fileSelector.AddExtensions("fbx");

            // Set the initial path to the models directory.
            fileSelector.SetInitialPath((Hymn().GetPath() + FileSystem::DELIMITER + "Models").c_str());
            fileSelector.SetFileSelectedCallback(std::bind(&ModelEditor::FileSelected, this, std::placeholders::_1));
            fileSelector.SetVisible(true);
        }

        if (hasSourceFile) {
            ImGui::Text("Mesh Data");
            ImGui::Checkbox("Uniform Scaling", &uniformScaling);

            if (uniformScaling) {
                float uniScale = scale.x;
                ImGui::DragFloat("Scale", &uniScale, 0.01f);
                scale = glm::vec3(uniScale);
            } else
                ImGui::DragFloat3("Scale", &scale[0], 0.01f);

            ImGui::Checkbox("Triangulate", &triangulate);
            ImGui::Checkbox("Import Normals", &importNormals);
            ImGui::Checkbox("Import Tangents", &importTangents);
            ImGui::Checkbox("Import Textures", &importTextures);
            ImGui::Checkbox("Flip UVs", &flipUVs);
            ImGui::Checkbox("Create scene", &createScene);

            std::string button = isImported ? "Re-import" : "Import";

            if (ImGui::Button(button.c_str())) {
                AssetConverter::Materials materials;

                // Convert to .asset format.
                AssetConverter asset;
                asset.Convert(source.c_str(), (destination + ".asset").c_str(), scale, triangulate, importNormals, importTangents, flipUVs, importTextures, materials);
                model->Load(destination.c_str());
                msgString = asset.Success() ? "Success\n" : asset.GetErrorString();
                isImported = true;

                // Generate meta data.
                AssetMetaData::MeshImportData* importData = new AssetMetaData::MeshImportData;
                importData->triangulate = triangulate;
                importData->importNormals = importNormals;
                importData->importTangents = importTangents;
                AssetMetaData::GenerateMetaData((destination + ".asset.meta").c_str(), importData);

                // Import textures.
                if (importTextures) {
                    LoadTexture(materials.albedo, "Albedo");
                    LoadTexture(materials.normal, "Normal");
                    LoadTexture(materials.roughness, "Roughness");
                    LoadTexture(materials.metallic, "Metallic");
                }

                delete importData;

                // Create scene containing an entity with the model and textures.
                if (createScene) {
                    // Create resource.
                    ResourceList::Resource resource;
                    resource.type = ResourceList::Resource::SCENE;
                    resource.scene = model->name + "Scene";
                    folder->resources.push_back(resource);

                    // Create and save scene.
                    World* world = new World();
                    world->CreateRoot();
                    Entity* entity = world->GetRoot()->AddChild(model->name);

                    Component::Mesh* mesh = entity->AddComponent<Component::Mesh>();
                    mesh->geometry = model;

                    world->Save(Hymn().GetPath() + "/" + model->path + model->name + "Scene.json");

                    // Cleanup.
                    mesh->geometry = nullptr;
                    mesh->Kill();
                    delete world;
                }
            }

            if (isImported)
                ImGui::Text(msgString.c_str());
        }
    }
    ImGui::End();

    if (fileSelector.IsVisible())
        fileSelector.Show();
}

const Geometry::Model* ModelEditor::GetModel() const {
    return model;
}

void ModelEditor::SetModel(ResourceList::ResourceFolder* folder, Geometry::Model* model) {
    this->folder = folder;
    this->model = model;

    strcpy(name, model->name.c_str());

    destination = Hymn().GetPath() + "/" + model->path + name;

    RefreshImportSettings();
}

bool ModelEditor::IsVisible() const {
    return visible;
}

void ModelEditor::SetVisible(bool visible) {
    this->visible = visible;
}

void ModelEditor::FileSelected(const std::string& file) {
    std::string name = FileSystem::GetName(file).c_str();

    // Checking so that the file isn't imported twice.
    /// @todo Overwrite option?
    /// @todo Reimplement this.
    /*for (int i = 0; i < Resources().models.size(); ++i) {
        if (Resources().models[i]->name == name) {
            Log() << "File " << name << " is already added to project.\n";
            isImported = false;
            hasSourceFile = false;
            return;
        }
    }*/

    source = file;

    // Rename the model to the name of the source file.
    strcpy(this->name, name.c_str());
    model->name = this->name;

    destination = Hymn().GetPath() + "/" + model->path + name;

    // Check if source file is in proper directory, otherwise, copy it.
    if (!FileSystem::FileExists((destination + "." + FileSystem::GetExtension(source)).c_str()))
        FileSystem::Copy(source.c_str(), (destination + "." + FileSystem::GetExtension(source)).c_str());

    hasSourceFile = true;

    RefreshImportSettings();
}

void ModelEditor::RefreshImportSettings() {
    // Check if the source file exist, currently only .fbx is supported.
    if (!FileSystem::FileExists((destination + ".fbx").c_str())) {
        hasSourceFile = false;
        isImported = false;
        return;
    }

    // Check if meta file already exists. If it does import the metadata.
    std::string filePath(destination + ".asset.meta");
    if (FileSystem::FileExists(filePath.c_str())) {
        AssetMetaData::MeshImportData * importData = AssetMetaData::GetMetaData(filePath.c_str());
        triangulate = importData->triangulate;
        importNormals = importData->importNormals;
        importTangents = importData->importTangents;

        delete importData;
        isImported = true;
    } else {
        isImported = false;
    }
}

void ModelEditor::LoadTexture(const std::string& path, const std::string& name) {
    if (!path.empty()) {
        std::string textureName = model->name + name;
        std::string src = FileSystem::GetDirectory(source) + path;
        std::string dest = model->path + textureName;

        // Copy file.
        FileSystem::Copy(src.c_str(), (Hymn().GetPath() + "/" + dest + ".png").c_str());

        // Add texture asset.
        ResourceList::Resource resource;
        resource.type = ResourceList::Resource::TEXTURE;
        resource.texture = Managers().resourceManager->CreateTextureAsset(dest);
        folder->resources.push_back(resource);
    }
}
<commit_msg>Add material to component<commit_after>#include "ModelEditor.hpp"

#include <Engine/Geometry/Model.hpp>
#include "../FileSelector.hpp"
#include <functional>
#include <Engine/Hymn.hpp>
#include <Engine/Util/FileSystem.hpp>
#include <imgui.h>
#include "Util/AssetMetaData.hpp"
#include <Utility/Log.hpp>
#include "../../Resources.hpp"
#include <Engine/Manager/Managers.hpp>
#include <Engine/Manager/ResourceManager.hpp>
#include <Engine/Entity/Entity.hpp>
#include <Engine/Component/Mesh.hpp>
#include <Engine/Component/Material.hpp>

using namespace GUI;

ModelEditor::ModelEditor() {
    name[0] = '\0';
}

void ModelEditor::Show() {
    if (ImGui::Begin(("Model: " + model->name + "###" + std::to_string(reinterpret_cast<uintptr_t>(model))).c_str(), &visible, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_ShowBorders)) {
        if (ImGui::InputText("Name", name, 128, ImGuiInputTextFlags_EnterReturnsTrue)) {
            model->name = name;

            // Rename all the files.
            if (FileSystem::FileExists((destination + ".fbx").c_str())) {
                FileSystem::Rename(destination + ".fbx", std::string(name) + ".fbx");

                if (FileSystem::FileExists((destination + ".asset").c_str()))
                    FileSystem::Rename(destination + ".asset", std::string(name) + ".asset");

                if (FileSystem::FileExists((destination + ".asset.meta").c_str()))
                    FileSystem::Rename(destination + ".asset.meta", std::string(name) + ".asset.meta");

                destination = Hymn().GetPath() + FileSystem::DELIMITER + "Models" + FileSystem::DELIMITER + name;
            }
        }

        if (ImGui::Button("Open model")) {
            // Currently only fbx is tested.
            fileSelector.AddExtensions("fbx");

            // Set the initial path to the models directory.
            fileSelector.SetInitialPath((Hymn().GetPath() + FileSystem::DELIMITER + "Models").c_str());
            fileSelector.SetFileSelectedCallback(std::bind(&ModelEditor::FileSelected, this, std::placeholders::_1));
            fileSelector.SetVisible(true);
        }

        if (hasSourceFile) {
            ImGui::Text("Mesh Data");
            ImGui::Checkbox("Uniform Scaling", &uniformScaling);

            if (uniformScaling) {
                float uniScale = scale.x;
                ImGui::DragFloat("Scale", &uniScale, 0.01f);
                scale = glm::vec3(uniScale);
            } else
                ImGui::DragFloat3("Scale", &scale[0], 0.01f);

            ImGui::Checkbox("Triangulate", &triangulate);
            ImGui::Checkbox("Import Normals", &importNormals);
            ImGui::Checkbox("Import Tangents", &importTangents);
            ImGui::Checkbox("Import Textures", &importTextures);
            ImGui::Checkbox("Flip UVs", &flipUVs);
            ImGui::Checkbox("Create scene", &createScene);

            std::string button = isImported ? "Re-import" : "Import";

            if (ImGui::Button(button.c_str())) {
                AssetConverter::Materials materials;

                // Convert to .asset format.
                AssetConverter asset;
                asset.Convert(source.c_str(), (destination + ".asset").c_str(), scale, triangulate, importNormals, importTangents, flipUVs, importTextures, materials);
                model->Load(destination.c_str());
                msgString = asset.Success() ? "Success\n" : asset.GetErrorString();
                isImported = true;

                // Generate meta data.
                AssetMetaData::MeshImportData* importData = new AssetMetaData::MeshImportData;
                importData->triangulate = triangulate;
                importData->importNormals = importNormals;
                importData->importTangents = importTangents;
                AssetMetaData::GenerateMetaData((destination + ".asset.meta").c_str(), importData);

                // Import textures.
                if (importTextures) {
                    LoadTexture(materials.albedo, "Albedo");
                    LoadTexture(materials.normal, "Normal");
                    LoadTexture(materials.roughness, "Roughness");
                    LoadTexture(materials.metallic, "Metallic");
                }

                delete importData;

                // Create scene containing an entity with the model and textures.
                if (createScene) {
                    // Create resource.
                    ResourceList::Resource resource;
                    resource.type = ResourceList::Resource::SCENE;
                    resource.scene = model->name + "Scene";
                    folder->resources.push_back(resource);

                    // Create and save scene.
                    World* world = new World();
                    world->CreateRoot();
                    Entity* entity = world->GetRoot()->AddChild(model->name);

                    Component::Mesh* mesh = entity->AddComponent<Component::Mesh>();
                    mesh->geometry = model;

                    Component::Material* material = entity->AddComponent<Component::Material>();

                    world->Save(Hymn().GetPath() + "/" + model->path + model->name + "Scene.json");

                    // Cleanup.
                    mesh->geometry = nullptr;
                    mesh->Kill();
                    material->Kill();
                    delete world;
                }
            }

            if (isImported)
                ImGui::Text(msgString.c_str());
        }
    }
    ImGui::End();

    if (fileSelector.IsVisible())
        fileSelector.Show();
}

const Geometry::Model* ModelEditor::GetModel() const {
    return model;
}

void ModelEditor::SetModel(ResourceList::ResourceFolder* folder, Geometry::Model* model) {
    this->folder = folder;
    this->model = model;

    strcpy(name, model->name.c_str());

    destination = Hymn().GetPath() + "/" + model->path + name;

    RefreshImportSettings();
}

bool ModelEditor::IsVisible() const {
    return visible;
}

void ModelEditor::SetVisible(bool visible) {
    this->visible = visible;
}

void ModelEditor::FileSelected(const std::string& file) {
    std::string name = FileSystem::GetName(file).c_str();

    // Checking so that the file isn't imported twice.
    /// @todo Overwrite option?
    /// @todo Reimplement this.
    /*for (int i = 0; i < Resources().models.size(); ++i) {
        if (Resources().models[i]->name == name) {
            Log() << "File " << name << " is already added to project.\n";
            isImported = false;
            hasSourceFile = false;
            return;
        }
    }*/

    source = file;

    // Rename the model to the name of the source file.
    strcpy(this->name, name.c_str());
    model->name = this->name;

    destination = Hymn().GetPath() + "/" + model->path + name;

    // Check if source file is in proper directory, otherwise, copy it.
    if (!FileSystem::FileExists((destination + "." + FileSystem::GetExtension(source)).c_str()))
        FileSystem::Copy(source.c_str(), (destination + "." + FileSystem::GetExtension(source)).c_str());

    hasSourceFile = true;

    RefreshImportSettings();
}

void ModelEditor::RefreshImportSettings() {
    // Check if the source file exist, currently only .fbx is supported.
    if (!FileSystem::FileExists((destination + ".fbx").c_str())) {
        hasSourceFile = false;
        isImported = false;
        return;
    }

    // Check if meta file already exists. If it does import the metadata.
    std::string filePath(destination + ".asset.meta");
    if (FileSystem::FileExists(filePath.c_str())) {
        AssetMetaData::MeshImportData * importData = AssetMetaData::GetMetaData(filePath.c_str());
        triangulate = importData->triangulate;
        importNormals = importData->importNormals;
        importTangents = importData->importTangents;

        delete importData;
        isImported = true;
    } else {
        isImported = false;
    }
}

void ModelEditor::LoadTexture(const std::string& path, const std::string& name) {
    if (!path.empty()) {
        std::string textureName = model->name + name;
        std::string src = FileSystem::GetDirectory(source) + path;
        std::string dest = model->path + textureName;

        // Copy file.
        FileSystem::Copy(src.c_str(), (Hymn().GetPath() + "/" + dest + ".png").c_str());

        // Add texture asset.
        ResourceList::Resource resource;
        resource.type = ResourceList::Resource::TEXTURE;
        resource.texture = Managers().resourceManager->CreateTextureAsset(dest);
        folder->resources.push_back(resource);
    }
}
<|endoftext|>