<commit_before>//////////////////////////////////////////////////////////////////////////
// Author		:	Michał Bednarek
// Email		:	michal.gr.bednarek@doctorate.put.poznan.pl
// Organization	:	Poznan University of Technology
// Date			:	2017
//////////////////////////////////////////////////////////////////////////

#include "include/KpMatcher.h"
#include "include/Reconstructor.h"
#include "include/Utilities.h"
#include "include/SimulatedAnnealing.h"

#include <memory>
#include <cstdlib>

/*shared variables*/
string modelPath;
string framePath;
Ptr<Feature2D> detector;
Ptr<Feature2D> descriptor;
NormTypes xFeatureNorm;
float ratio1;
float ratio2;

int main(int argc, char** argv)
{
    if(argc < 7 || !SetupInputParameters(argv))
    {
        cerr << "Usage: ./affineDSC path_to_model.png path_to_frame.png detector descriptor ratio1% ratio2% isPointCloudSaved(0 / 1)" << endl;
        return EXIT_FAILURE;
    }

    /*describe & detect model keypoints*/
    unique_ptr<KpMatcher> kpm (new KpMatcher(detector, descriptor));
    cv::Mat img = kpm->ReadImage(modelPath, cv::IMREAD_ANYCOLOR );
    kpm->Init(img);

    /*describe & detect frame keypoints*/
    cv::Mat frame = kpm->ReadImage(framePath, cv::IMREAD_ANYCOLOR );
    kpm->DescribeAndDetectFrameKeypoints(frame);

    /*matching*/
    kpm->FindCurrentMatches(xFeatureNorm, ratio1);
    float seconds;
    clock_t t;
    t = clock();
    kpm->ImproveBadMatches(xFeatureNorm, ratio2);
    t = clock() - t;
    seconds = (float)t / CLOCKS_PER_SEC;

    /*~~~~~~~~~~~~~~~~~~~~~ 3D reconstruction (EPFL) ~~~~~~~~~~~~~~~~~~~~~~~~~*/
    unique_ptr<Reconstructor> rec (new Reconstructor());

    rec->init(img);

    std::vector<DMatch> matches = kpm->GetMatches();
    std::vector<KeyPoint> kp1 = kpm->GetModelMatchedKeypoints();
    std::vector<KeyPoint> kp2 = kpm->GetFrameMatchedKeypoints();

    rec->prepareMatches(matches, kp1, kp2);
    rec->deform();
    rec->SetUseTemporal(true);
    rec->SetUsePrevFrameToInit(true);

    if(argv[7] == std::string("1"))
    {
        /*prepare name*/
        std::stringstream ss;
        ss << "PC_" << GetFrameNumber() << "_" << argv[5] << "_" << argv[6] << "_" << argv[3] << "_" << argv[4];

        /*save images*/
        kpm->DrawFoundMatches(img, frame, false, ss.str() + "_all");
        kpm->DrawFoundMatches(img, frame, true, ss.str() + "_imp");
        kpm->DrawKeypointsDisplacement(img, frame, ss.str() + "_disp");

        /*save 3d info*/
        rec->savePointCloud(ss.str());
        rec->drawMesh(frame, rec->resMesh, ss.str() );

        /*save matches*/
        std::ofstream outfile;
        outfile.open("matches.txt", std::ios_base::app);
        outfile << ss.str() << " " << kpm->GetMatches().size() << " " << seconds << endl;
        outfile.close();
    }

    return EXIT_SUCCESS;
}
<commit_msg>test commit<commit_after>//////////////////////////////////////////////////////////////////////////
// Author		:	Michał Bednarek
// Email		:	michal.gr.bednarek@doctorate.put.poznan.pl
// Organization	:	Poznan University of Technology
// Date			:	2017
//////////////////////////////////////////////////////////////////////////

#include "include/KpMatcher.h"
#include "include/Reconstructor.h"
#include "include/Utilities.h"
#include "include/SimulatedAnnealing.h"

#include <memory>
#include <cstdlib>

/*shared variables  */
string modelPath;
string framePath;
Ptr<Feature2D> detector;
Ptr<Feature2D> descriptor;
NormTypes xFeatureNorm;
float ratio1;
float ratio2;

int main(int argc, char** argv)
{
    if(argc < 7 || !SetupInputParameters(argv))
    {
        cerr << "Usage: ./affineDSC path_to_model.png path_to_frame.png detector descriptor ratio1% ratio2% isPointCloudSaved(0 / 1)" << endl;
        return EXIT_FAILURE;
    }

    /*describe & detect model keypoints*/
    unique_ptr<KpMatcher> kpm (new KpMatcher(detector, descriptor));
    cv::Mat img = kpm->ReadImage(modelPath, cv::IMREAD_ANYCOLOR );
    kpm->Init(img);

    /*describe & detect frame keypoints*/
    cv::Mat frame = kpm->ReadImage(framePath, cv::IMREAD_ANYCOLOR );
    kpm->DescribeAndDetectFrameKeypoints(frame);

    /*matching*/
    kpm->FindCurrentMatches(xFeatureNorm, ratio1);
    float seconds;
    clock_t t;
    t = clock();
    kpm->ImproveBadMatches(xFeatureNorm, ratio2);
    t = clock() - t;
    seconds = (float)t / CLOCKS_PER_SEC;

    /*~~~~~~~~~~~~~~~~~~~~~ 3D reconstruction (EPFL) ~~~~~~~~~~~~~~~~~~~~~~~~~*/
    unique_ptr<Reconstructor> rec (new Reconstructor());

    rec->init(img);

    std::vector<DMatch> matches = kpm->GetMatches();
    std::vector<KeyPoint> kp1 = kpm->GetModelMatchedKeypoints();
    std::vector<KeyPoint> kp2 = kpm->GetFrameMatchedKeypoints();

    rec->prepareMatches(matches, kp1, kp2);
    rec->deform();
    rec->SetUseTemporal(true);
    rec->SetUsePrevFrameToInit(true);

    if(argv[7] == std::string("1"))
    {
        /*prepare name*/
        std::stringstream ss;
        ss << "PC_" << GetFrameNumber() << "_" << argv[5] << "_" << argv[6] << "_" << argv[3] << "_" << argv[4];

        /*save images*/
        kpm->DrawFoundMatches(img, frame, false, ss.str() + "_all");
        kpm->DrawFoundMatches(img, frame, true, ss.str() + "_imp");
        kpm->DrawKeypointsDisplacement(img, frame, ss.str() + "_disp");

        /*save 3d info*/
        rec->savePointCloud(ss.str());
        rec->drawMesh(frame, rec->resMesh, ss.str() );

        /*save matches*/
        std::ofstream outfile;
        outfile.open("matches.txt", std::ios_base::app);
        outfile << ss.str() << " " << kpm->GetMatches().size() << " " << seconds << endl;
        outfile.close();
    }

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*
    This file is part of KMail.
    Copyright (c) 2003 Andreas Gungl <a.gungl@gmx.de>

    KMail is free software; you can redistribute it and/or modify it
    under the terms of the GNU General Public License, version 2, as
    published by the Free Software Foundation.

    KMail 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, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "redirectdialog.h"

#include "kmkernel.h"
#include "kmlineeditspell.h"

#include <kpimutils/email.h>
#include <addressesdialog.h>
using KPIM::AddressesDialog;
#include "recentaddresses.h"
using KPIM::RecentAddresses;

#include <kiconloader.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kvbox.h>

#include <QLabel>
#include <QPushButton>
#include <QStringList>
#include <QFrame>

using namespace KMail;

RedirectDialog::RedirectDialog( QWidget *parent, bool immediate )
  : KDialog( parent )
{
  setCaption( i18n( "Redirect Message" ) );
  setButtons( User1|User2|Cancel );
  setDefaultButton( immediate ? User1 : User2 );
  QFrame *vbox = new KVBox( this );
  setMainWidget( vbox );
  mLabelTo = new QLabel( i18n( "Select the recipient &addresses "
                               "to redirect to:" ), vbox );

  KHBox *hbox = new KHBox( vbox );
  hbox->setSpacing(4);
  mEditTo = new KMLineEdit( true, hbox, "toLine" );
  mEditTo->setMinimumWidth( 300 );

  mBtnTo = new QPushButton( QString(), hbox );
  mBtnTo->setObjectName( "toBtn" );
  mBtnTo->setIcon( KIcon( "help-contents" ) );
  mBtnTo->setIconSize( QSize( KIconLoader::SizeSmall, KIconLoader::SizeSmall ) );
  mBtnTo->setMinimumSize( mBtnTo->sizeHint() * 1.2 );
  mBtnTo->setToolTip( i18n("Use the Address-Selection Dialog") );
  mBtnTo->setWhatsThis( i18n("This button opens a separate dialog "
                                 "where you can select recipients out "
                                 "of all available addresses." ) );

  connect( mBtnTo, SIGNAL(clicked()), SLOT(slotAddrBook()) );

  mLabelTo->setBuddy( mBtnTo );
  mEditTo->setFocus();

  setButtonGuiItem( User1, KGuiItem( i18n("&Send Now"), "mail-send" ) );
  setButtonGuiItem( User2, KGuiItem( i18n("Send &Later"), "queue" ) );
  connect(this,SIGNAL(user1Clicked()),this, SLOT(slotUser1()));
  connect(this,SIGNAL(user2Clicked()),this, SLOT(slotUser2()));
}

//-----------------------------------------------------------------------------
void RedirectDialog::slotUser1()
{
  mImmediate = true;
  accept();
}

//-----------------------------------------------------------------------------
void RedirectDialog::slotUser2()
{
  mImmediate = false;
  accept();
}

//-----------------------------------------------------------------------------
void RedirectDialog::accept()
{
  mResentTo = mEditTo->text();
  if ( mResentTo.isEmpty() ) {
    KMessageBox::sorry( this,
        i18n("You cannot redirect the message without an address."),
        i18n("Empty Redirection Address") );
  }
  else done( Ok );
}

//-----------------------------------------------------------------------------
void RedirectDialog::slotAddrBook()
{
  AddressesDialog dlg( this );

  mResentTo = mEditTo->text();
  if ( !mResentTo.isEmpty() ) {
      QStringList lst = KPIMUtils::splitAddressList( mResentTo );
      dlg.setSelectedTo( lst );
  }

  dlg.setRecentAddresses(
      RecentAddresses::self( KMKernel::config() )->kabcAddresses() );

  // Make it impossible to specify Cc or Bcc addresses as we support
  // only the Redirect-To header!
  dlg.setShowCC( false );
  dlg.setShowBCC( false );

  if (dlg.exec()==KDialog::Rejected) return;

  mEditTo->setText( dlg.to().join(", ") );
  mEditTo->setModified( true );
}

#include "redirectdialog.moc"
<commit_msg>Backport r917880 by tmcguire from trunk to the 4.2 branch:<commit_after>/*
    This file is part of KMail.
    Copyright (c) 2003 Andreas Gungl <a.gungl@gmx.de>

    KMail is free software; you can redistribute it and/or modify it
    under the terms of the GNU General Public License, version 2, as
    published by the Free Software Foundation.

    KMail 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, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "redirectdialog.h"

#include "kmkernel.h"
#include "kmlineeditspell.h"

#include <kpimutils/email.h>
#include <addressesdialog.h>
using KPIM::AddressesDialog;
#include "recentaddresses.h"
using KPIM::RecentAddresses;

#include <kiconloader.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kvbox.h>

#include <QLabel>
#include <QPushButton>
#include <QStringList>
#include <QFrame>

using namespace KMail;

RedirectDialog::RedirectDialog( QWidget *parent, bool immediate )
  : KDialog( parent )
{
  setCaption( i18n( "Redirect Message" ) );
  setButtons( User1|User2|Cancel );
  setDefaultButton( immediate ? User1 : User2 );
  QFrame *vbox = new KVBox( this );
  setMainWidget( vbox );
  mLabelTo = new QLabel( i18n( "Select the recipient &addresses "
                               "to redirect to:" ), vbox );

  KHBox *hbox = new KHBox( vbox );
  hbox->setSpacing(4);
  mEditTo = new KMLineEdit( true, hbox, "toLine" );
  mEditTo->setMinimumWidth( 300 );

  mBtnTo = new QPushButton( QString(), hbox );
  mBtnTo->setObjectName( "toBtn" );
  mBtnTo->setIcon( KIcon( "help-contents" ) );
  mBtnTo->setIconSize( QSize( KIconLoader::SizeSmall, KIconLoader::SizeSmall ) );
  mBtnTo->setMinimumSize( mBtnTo->sizeHint() * 1.2 );
  mBtnTo->setToolTip( i18n("Use the Address-Selection Dialog") );
  mBtnTo->setWhatsThis( i18n("This button opens a separate dialog "
                                 "where you can select recipients out "
                                 "of all available addresses." ) );

  connect( mBtnTo, SIGNAL(clicked()), SLOT(slotAddrBook()) );

  mLabelTo->setBuddy( mBtnTo );
  mEditTo->setFocus();

  setButtonGuiItem( User1, KGuiItem( i18n("&Send Now"), "mail-send" ) );
  setButtonGuiItem( User2, KGuiItem( i18n("Send &Later"), "mail-queue" ) );
  connect(this,SIGNAL(user1Clicked()),this, SLOT(slotUser1()));
  connect(this,SIGNAL(user2Clicked()),this, SLOT(slotUser2()));
}

//-----------------------------------------------------------------------------
void RedirectDialog::slotUser1()
{
  mImmediate = true;
  accept();
}

//-----------------------------------------------------------------------------
void RedirectDialog::slotUser2()
{
  mImmediate = false;
  accept();
}

//-----------------------------------------------------------------------------
void RedirectDialog::accept()
{
  mResentTo = mEditTo->text();
  if ( mResentTo.isEmpty() ) {
    KMessageBox::sorry( this,
        i18n("You cannot redirect the message without an address."),
        i18n("Empty Redirection Address") );
  }
  else done( Ok );
}

//-----------------------------------------------------------------------------
void RedirectDialog::slotAddrBook()
{
  AddressesDialog dlg( this );

  mResentTo = mEditTo->text();
  if ( !mResentTo.isEmpty() ) {
      QStringList lst = KPIMUtils::splitAddressList( mResentTo );
      dlg.setSelectedTo( lst );
  }

  dlg.setRecentAddresses(
      RecentAddresses::self( KMKernel::config() )->kabcAddresses() );

  // Make it impossible to specify Cc or Bcc addresses as we support
  // only the Redirect-To header!
  dlg.setShowCC( false );
  dlg.setShowBCC( false );

  if (dlg.exec()==KDialog::Rejected) return;

  mEditTo->setText( dlg.to().join(", ") );
  mEditTo->setModified( true );
}

#include "redirectdialog.moc"
<|endoftext|>


<commit_before>#include "cfg.hpp"
#include "cfg_builder.hpp"
#include "cfg_json_writer.hpp"

#include "ast_pretty_printer.hpp"
#include "unit_navigator.hpp"

#include <clang/Lex/Preprocessor.h>
#include <clang/Basic/SourceManager.h>
#include <clang/Basic/FileManager.h>
#include <clang/Basic/TargetInfo.h>
#include <clang/Lex/HeaderSearch.h>
#include <clang/AST/ASTContext.h>
#include <clang/Frontend/CompilerInvocation.h>
#include <clang/AST/ASTConsumer.h>
#include <clang/AST/Decl.h>
#include <clang/AST/Stmt.h>
#include <clang/AST/DeclTemplate.h>
#include <clang/AST/DeclCXX.h>
#include <clang/Analysis/CFG.h>
#include <clang/Frontend/Utils.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Frontend/FrontendActions.h>
#include <clang/Frontend/TextDiagnosticBuffer.h>
#include <clang/Sema/Sema.h>

#include <iostream>
#include <set>

#include <boost/utility.hpp>
#include <boost/assert.hpp>

struct config
{
	int printJsonCfg;
	bool printReadableAST;
	bool printUnitAST;
	bool buildCfg;
	bool debugCFG;

	bool showFnNames;
	bool dump_progress;
	std::string filter;

	std::string static_prefix;
};

struct cfg_build_visitor
	: default_build_visitor
{
	cfg_build_visitor(clang::CompilerInstance & ci, config const & c)
		: m_ci(ci), m_c(c)
	{
	}

	bool function_started(std::string const & name)
	{
		if (!m_c.filter.empty() && name.substr(0, m_c.filter.size()) != m_c.filter)
			return false;

		if (m_c.showFnNames)
			std::cerr << name << std::endl;

		return true;
	}

	void statement_visited(clang::Stmt const * stmt)
	{
		if (m_c.dump_progress)
		{
			stmt->getLocStart().dump(m_ci.getSourceManager());
			std::cerr << '\n';
		}
	}

	clang::CompilerInstance & m_ci;
	config const & m_c;
};

class MyConsumer
	: public clang::ASTConsumer
{
public:
	MyConsumer(clang::CompilerInstance & ci, config const & c, std::string const & filename)
		: m_ci(ci), m_c(c), m_filename(filename)
	{
	}

	void HandleTranslationUnit(clang::ASTContext &ctx)
	{
		if (m_ci.getDiagnostics().hasErrorOccurred())
		{
			std::cerr << "Errors were found, serialization of AST and CFGs is disabled." << std::endl;
			return;
		}

#if 0
		std::vector<clang::CXXRecordDecl *> structure_decls;
		for (clang::ASTContext::type_iterator it = ctx.types_begin(); it != ctx.types_end(); ++it)
		{
			clang::Type * type = *it;
			if (type->isDependentType() || !type->isStructureOrClassType())
				continue;

			structure_decls.push_back(type->getAsCXXRecordDecl());
		}

		// Instantiate all special member functions
		for (std::size_t i = 0; i != structure_decls.size(); ++i)
		{
			clang::CXXRecordDecl * recdecl = structure_decls[i];
			for (clang::CXXRecordDecl::method_iterator mit = recdecl->method_begin(); mit != recdecl->method_end(); ++mit)
			{
				clang::CXXMethodDecl * method = *mit;
				m_ci.getSema().MarkDeclarationReferenced(method->getLocation(), method);
			}
		}
#endif

		unit_navigator un(ctx.getTranslationUnitDecl());
		if (!m_c.filter.empty())
			un.filter(m_c.filter);

		if (m_c.printReadableAST)
		{
			for (unit_navigator::fns_const_iterator ci = un.fns_begin(); ci != un.fns_end(); ++ci)
				pretty_print_decl(*ci, std::cout);
		}

		if (m_c.buildCfg)
			build_program(un, m_ci.getSourceManager(), cfg_build_visitor(m_ci, m_c), m_c.static_prefix);

		if (m_c.printJsonCfg)
		{
			program prog = build_program(un, m_ci.getSourceManager(), cfg_build_visitor(m_ci, m_c), m_c.static_prefix);
			cfg_json_write(std::cout, prog, m_c.printJsonCfg == 1);
		}

		if (m_c.printUnitAST)
			pretty_print_decl(ctx.getTranslationUnitDecl(), std::cout, 0);

		if (m_c.debugCFG)
		{
			program prog = build_program(un, m_ci.getSourceManager(), cfg_build_visitor(m_ci, m_c), m_c.static_prefix);
			prog.pretty_print(std::cerr);
		}
	}

private:
	clang::CompilerInstance & m_ci;
	config m_c;
	std::string m_filename;
};

class MyASTDumpAction : public clang::ASTFrontendAction
{
public:
	MyASTDumpAction(config const & c)
		: m_c(c)
	{
	}

	clang::ASTContext * ctx;

protected:
	virtual clang::ASTConsumer *CreateASTConsumer(clang::CompilerInstance &CI,
		llvm::StringRef InFile)
	{
		return new MyConsumer(CI, m_c, InFile.str());
	}

private:
	config m_c;
};

class MyDiagClient : public clang::DiagnosticClient
{
public:
	virtual void HandleDiagnostic(clang::Diagnostic::Level DiagLevel, const clang::DiagnosticInfo &Info)
	{
	}
};

int main(int argc, char * argv[])
{
	try
	{
		static char const * additional_args[] = {
			"-triple", "i686-pc-win32",
			"-ferror-limit", "19",
			"-fmessage-length", "300",
			"-fexceptions",
			"-fms-extensions",
			"-fgnu-runtime",
			"-fdiagnostics-show-option",
			"-fcolor-diagnostics",
			"-x", "c++",
			"-nobuiltininc",
		};

		std::vector<char const *> args(additional_args, additional_args + sizeof additional_args / sizeof additional_args[0]);

		config c = {};
		c.static_prefix = "__unique";

		// Parse the arguments
		for (int i = 1; i < argc; ++i)
		{
			std::string arg = argv[i];
			if (arg == "-a")
				c.printReadableAST = true;
			else if (arg == "-j")
				c.printJsonCfg = 1;
			else if (arg == "-J")
				c.printJsonCfg = 2;
			else if (arg == "-u")
				c.printUnitAST = true;
			else if (arg == "-c")
				c.buildCfg = true;
			else if (arg == "--debugcfg")
				c.debugCFG = true;
			else if (arg == "--showfnnames")
				c.showFnNames = true;
			else if (arg == "--dumpprogress")
				c.dump_progress = true;
			else if (arg == "--staticprefix" && i + 1 < argc)
				c.static_prefix = argv[++i];
			else if (arg == "--filter" && i + 1 < argc)
				c.filter = argv[++i];
			else
				args.push_back(argv[i]);
		}

		clang::CompilerInstance comp_inst;

		llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> diagIds;
		clang::Diagnostic argDiag(diagIds);

		clang::CompilerInvocation & ci = comp_inst.getInvocation();
		clang::CompilerInvocation::CreateFromArgs(ci, &args.front(), &args.back() + 1, argDiag);

		comp_inst.createDiagnostics(args.size(), (char **)&args[0]);

		if (!c.printJsonCfg && !c.printReadableAST && !c.debugCFG && !c.printUnitAST && !c.buildCfg)
			c.printJsonCfg = 2;

		MyASTDumpAction act(c);
		comp_inst.ExecuteAction(act);

		return comp_inst.getDiagnostics().hasErrorOccurred();
	}
	catch (std::exception const & e)
	{
		std::cerr << "error: " << e.what() << std::endl;
		return 1;
	}
	catch (...)
	{
		std::cerr << "error: unexpected error occured" << std::endl;
		return 1;
	}
}
<commit_msg>Added --help option.<commit_after>#include "cfg.hpp"
#include "cfg_builder.hpp"
#include "cfg_json_writer.hpp"

#include "ast_pretty_printer.hpp"
#include "unit_navigator.hpp"

#include <clang/Lex/Preprocessor.h>
#include <clang/Basic/SourceManager.h>
#include <clang/Basic/FileManager.h>
#include <clang/Basic/TargetInfo.h>
#include <clang/Lex/HeaderSearch.h>
#include <clang/AST/ASTContext.h>
#include <clang/Frontend/CompilerInvocation.h>
#include <clang/AST/ASTConsumer.h>
#include <clang/AST/Decl.h>
#include <clang/AST/Stmt.h>
#include <clang/AST/DeclTemplate.h>
#include <clang/AST/DeclCXX.h>
#include <clang/Analysis/CFG.h>
#include <clang/Frontend/Utils.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Frontend/FrontendActions.h>
#include <clang/Frontend/TextDiagnosticBuffer.h>
#include <clang/Sema/Sema.h>

#include <iostream>
#include <set>

#include <boost/utility.hpp>
#include <boost/assert.hpp>

struct config
{
	int printJsonCfg;
	bool printReadableAST;
	bool printUnitAST;
	bool buildCfg;
	bool debugCFG;

	bool showFnNames;
	bool dump_progress;
	std::string filter;

	std::string static_prefix;
};

struct cfg_build_visitor
	: default_build_visitor
{
	cfg_build_visitor(clang::CompilerInstance & ci, config const & c)
		: m_ci(ci), m_c(c)
	{
	}

	bool function_started(std::string const & name)
	{
		if (!m_c.filter.empty() && name.substr(0, m_c.filter.size()) != m_c.filter)
			return false;

		if (m_c.showFnNames)
			std::cerr << name << std::endl;

		return true;
	}

	void statement_visited(clang::Stmt const * stmt)
	{
		if (m_c.dump_progress)
		{
			stmt->getLocStart().dump(m_ci.getSourceManager());
			std::cerr << '\n';
		}
	}

	clang::CompilerInstance & m_ci;
	config const & m_c;
};

class MyConsumer
	: public clang::ASTConsumer
{
public:
	MyConsumer(clang::CompilerInstance & ci, config const & c, std::string const & filename)
		: m_ci(ci), m_c(c), m_filename(filename)
	{
	}

	void HandleTranslationUnit(clang::ASTContext &ctx)
	{
		if (m_ci.getDiagnostics().hasErrorOccurred())
		{
			std::cerr << "Errors were found, serialization of AST and CFGs is disabled." << std::endl;
			return;
		}

#if 0
		std::vector<clang::CXXRecordDecl *> structure_decls;
		for (clang::ASTContext::type_iterator it = ctx.types_begin(); it != ctx.types_end(); ++it)
		{
			clang::Type * type = *it;
			if (type->isDependentType() || !type->isStructureOrClassType())
				continue;

			structure_decls.push_back(type->getAsCXXRecordDecl());
		}

		// Instantiate all special member functions
		for (std::size_t i = 0; i != structure_decls.size(); ++i)
		{
			clang::CXXRecordDecl * recdecl = structure_decls[i];
			for (clang::CXXRecordDecl::method_iterator mit = recdecl->method_begin(); mit != recdecl->method_end(); ++mit)
			{
				clang::CXXMethodDecl * method = *mit;
				m_ci.getSema().MarkDeclarationReferenced(method->getLocation(), method);
			}
		}
#endif

		unit_navigator un(ctx.getTranslationUnitDecl());
		if (!m_c.filter.empty())
			un.filter(m_c.filter);

		if (m_c.printReadableAST)
		{
			for (unit_navigator::fns_const_iterator ci = un.fns_begin(); ci != un.fns_end(); ++ci)
				pretty_print_decl(*ci, std::cout);
		}

		if (m_c.buildCfg)
			build_program(un, m_ci.getSourceManager(), cfg_build_visitor(m_ci, m_c), m_c.static_prefix);

		if (m_c.printJsonCfg)
		{
			program prog = build_program(un, m_ci.getSourceManager(), cfg_build_visitor(m_ci, m_c), m_c.static_prefix);
			cfg_json_write(std::cout, prog, m_c.printJsonCfg == 1);
		}

		if (m_c.printUnitAST)
			pretty_print_decl(ctx.getTranslationUnitDecl(), std::cout, 0);

		if (m_c.debugCFG)
		{
			program prog = build_program(un, m_ci.getSourceManager(), cfg_build_visitor(m_ci, m_c), m_c.static_prefix);
			prog.pretty_print(std::cerr);
		}
	}

private:
	clang::CompilerInstance & m_ci;
	config m_c;
	std::string m_filename;
};

class MyASTDumpAction : public clang::ASTFrontendAction
{
public:
	MyASTDumpAction(config const & c)
		: m_c(c)
	{
	}

	clang::ASTContext * ctx;

protected:
	virtual clang::ASTConsumer *CreateASTConsumer(clang::CompilerInstance &CI,
		llvm::StringRef InFile)
	{
		return new MyConsumer(CI, m_c, InFile.str());
	}

private:
	config m_c;
};

class MyDiagClient : public clang::DiagnosticClient
{
public:
	virtual void HandleDiagnostic(clang::Diagnostic::Level DiagLevel, const clang::DiagnosticInfo &Info)
	{
	}
};

int main(int argc, char * argv[])
{
	try
	{
		static char const * additional_args[] = {
			"-triple", "i686-pc-win32",
			"-ferror-limit", "19",
			"-fmessage-length", "300",
			"-fexceptions",
			"-fms-extensions",
			"-fgnu-runtime",
			"-fdiagnostics-show-option",
			"-fcolor-diagnostics",
			"-x", "c++",
			"-nobuiltininc",
		};

		std::vector<char const *> args(additional_args, additional_args + sizeof additional_args / sizeof additional_args[0]);

		config c = {};
		c.static_prefix = "__unique";

		// Parse the arguments
		bool print_help = false;
		for (int i = 1; i < argc; ++i)
		{
			std::string arg = argv[i];
			if (arg == "-a")
				c.printReadableAST = true;
			if (arg == "-h" || arg == "--help")
				print_help = true;
			else if (arg == "-j")
				c.printJsonCfg = 1;
			else if (arg == "-J")
				c.printJsonCfg = 2;
			else if (arg == "-u")
				c.printUnitAST = true;
			else if (arg == "-c")
				c.buildCfg = true;
			else if (arg == "--debugcfg")
				c.debugCFG = true;
			else if (arg == "--showfnnames")
				c.showFnNames = true;
			else if (arg == "--dumpprogress")
				c.dump_progress = true;
			else if (arg == "--unitid" && i + 1 < argc)
				c.static_prefix = argv[++i];
			else if (arg == "--filter" && i + 1 < argc)
				c.filter = argv[++i];
			else
				args.push_back(argv[i]);
		}

		if (print_help)
		{
			std::cout << "Usage: " << argv[0] << "[-Jjuca] [--unitid <id>] [<clang options>] <filename>" << std::endl;
			return 0;
		}

		clang::CompilerInstance comp_inst;

		llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> diagIds;
		clang::Diagnostic argDiag(diagIds);

		clang::CompilerInvocation & ci = comp_inst.getInvocation();
		clang::CompilerInvocation::CreateFromArgs(ci, &args.front(), &args.back() + 1, argDiag);

		comp_inst.createDiagnostics(args.size(), (char **)&args[0]);

		if (!c.printJsonCfg && !c.printReadableAST && !c.debugCFG && !c.printUnitAST && !c.buildCfg)
			c.printJsonCfg = 2;

		MyASTDumpAction act(c);
		comp_inst.ExecuteAction(act);

		return comp_inst.getDiagnostics().hasErrorOccurred();
	}
	catch (std::exception const & e)
	{
		std::cerr << "error: " << e.what() << std::endl;
		return 1;
	}
	catch (...)
	{
		std::cerr << "error: unexpected error occured" << std::endl;
		return 1;
	}
}
<|endoftext|>


<commit_before>76fb3da8-4b02-11e5-ba8a-28cfe9171a43<commit_msg>Stuff changed<commit_after>77082868-4b02-11e5-b5f8-28cfe9171a43<|endoftext|>


<commit_before>84b9e4f5-ad5b-11e7-bfa7-ac87a332f658<commit_msg>fixed bug<commit_after>85323eb8-ad5b-11e7-8f54-ac87a332f658<|endoftext|>


<commit_before>// Get rid of tons of warnings.
#pragma warning(push,1)
#include <foobar2000/SDK/foobar2000.h>
#pragma warning(pop)

#define FOO_CAD_VERSION     "1.0"
#define FOO_PLUGIN_RELEASE  "1"
#define FOO_PLUGIN_NAME     _T("foo_cdartdisplay")
#define FOO_CLASS_NAME      _T("THeliumMainForm")

DECLARE_COMPONENT_VERSION(
    "CD Art Display Interface",
    FOO_CAD_VERSION " release " FOO_PLUGIN_RELEASE,
    "Message handling plug-in to interface with CD Art Display <http://www.closetosoftware.com/?s=cdartdisplay>.\n"
    "Compiled on " __DATE__ ", copyright 2007 by eyebex <eyebex@threekings.tk>."
);

enum {
    IPC_PLAY                        = 100,
    IPC_PLAYPAUSE                        ,
    IPC_FORCEPAUSE                       ,
    IPC_STOP                             ,
    IPC_NEXT                             ,
    IPC_PREVIOUS                         ,

    IPC_SET_VOLUME                  = 108,
    IPC_GET_VOLUME                       ,
    IPC_GET_CURRENT_TRACK                ,

    IPC_GET_DURATION                = 113,
    IPC_SET_POSITION                     ,
    IPC_IS_PLAYING                       ,
    IPC_IS_PAUSED                        ,
    IPC_GET_LIST_LENGTH                  ,
    IPC_SET_LIST_POS                     ,
    IPC_GET_LIST_ITEM                    ,
    IPC_SET_CALLBACK_HWND                ,
    IPC_GET_LIST_POS                     ,
    IPC_GET_POSITION                     ,
    IPC_TRACK_CHANGED_NOTIFICATION       ,
    IPC_SHOW_PLAYER_WINDOW               ,
    IPC_GET_PLAYER_STATE                 ,

    IPC_RATING_CHANGED_NOTIFICATION = 639
};

class CDArtDisplayInterface:public initquit,public play_callback
{
  public:

    void on_init() {
        if (!s_atom) {
            // Register a minimal window class.
            WNDCLASS cls;
            memset(&cls,0,sizeof(cls));
            cls.style=CS_OWNDC|CS_SAVEBITS;
            cls.lpfnWndProc=WindowProc;
            cls.hInstance=core_api::get_my_instance();
            cls.hCursor=LoadCursor(NULL,IDC_ARROW);
            cls.lpszClassName=FOO_CLASS_NAME;

            s_atom=RegisterClass(&cls);
            if (!s_atom) {
#ifndef NDEBUG
                MessageBox(core_api::get_main_window(),_T("Unable to register the window class."),FOO_PLUGIN_NAME,MB_OK|MB_ICONERROR);
#endif
                return;
            }
        }

        // Create a dummy window.
        m_dummy_window=CreateWindow(
        /* lpClassName  */ MAKEINTATOM(s_atom),
        /* lpWindowName */ FOO_PLUGIN_NAME,
        /* dwStyle      */ 0,
        /* x            */ 0,
        /* y            */ 0,
        /* nWidth       */ 0,
        /* nHeight      */ 0,
        /* hWndParent   */ core_api::get_main_window(),
        /* hMenu        */ NULL,
        /* hInstance    */ core_api::get_my_instance(),
        /* lpParam      */ this
        );
        if (!m_dummy_window) {
#ifndef NDEBUG
            MessageBox(core_api::get_main_window(),_T("Unable to create the dummy window."),FOO_PLUGIN_NAME,MB_OK|MB_ICONERROR);
#endif
            return;
        }

        m_cda_window=NULL;
        ++s_instances;

#ifndef NDEBUG
        MessageBox(core_api::get_main_window(),_T("Construction was successful."),FOO_PLUGIN_NAME,MB_OK|MB_ICONINFORMATION);
#endif
    }

    void on_quit() {
        if (!DestroyWindow(m_dummy_window)) {
#ifndef NDEBUG
            MessageBox(core_api::get_main_window(),_T("Unable to destroy the dummy window."),FOO_PLUGIN_NAME,MB_OK|MB_ICONERROR);
#endif
            return;
        }

        if (--s_instances<=0) {
            if (!UnregisterClass(MAKEINTATOM(s_atom),NULL)) {
#ifndef NDEBUG
                MessageBox(core_api::get_main_window(),_T("Unable to unregister the window class."),FOO_PLUGIN_NAME,MB_OK|MB_ICONERROR);
#endif
                return;
            }

            s_atom=0;
        }

#ifndef NDEBUG
        MessageBox(core_api::get_main_window(),_T("Destruction was successful."),FOO_PLUGIN_NAME,MB_OK|MB_ICONINFORMATION);
#endif
    }

    // warning C4100: unreferenced formal parameter
    #pragma warning(disable:4100)

    void on_playback_starting(play_control::t_track_command p_command,bool p_paused) {}
    void on_playback_stop(play_control::t_stop_reason p_reason) {}
    void on_playback_seek(double p_time) {}
    void on_playback_pause(bool p_state) {}
    void on_playback_dynamic_info(const file_info & p_info) {}
    void on_playback_dynamic_info_track(const file_info & p_info) {}
    void on_playback_time(double p_time) {}
    void on_volume_change(float p_new_val) {}

    #pragma warning(default:4100)

    void on_playback_new_track(metadb_handle_ptr p_track) {
        SendMessage(m_cda_window,WM_USER,0,IPC_TRACK_CHANGED_NOTIFICATION);
    }

    void on_playback_edited(metadb_handle_ptr p_track) {
        file_info_impl info;
        if (p_track->get_info(info)) {
            // TODO: Find out how to get the rating.
            int rating=atoi(info.meta_get("RATING",0));
            SendMessage(m_cda_window,WM_USER,static_cast<WPARAM>(rating),IPC_RATING_CHANGED_NOTIFICATION);
        }
    }

  private:

    static ATOM s_atom;
    static int s_instances;

    HWND m_dummy_window;
    HWND m_cda_window;

    static LRESULT CALLBACK WindowProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam);
};

LRESULT CALLBACK CDArtDisplayInterface::WindowProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam) {
    // Using a dynamic_cast here would be safer, but that requires RTTI support.
    CDArtDisplayInterface *_this=reinterpret_cast<CDArtDisplayInterface*>(GetWindowLong(hWnd,GWL_USERDATA));

    if (uMsg==WM_CREATE) {
        LPVOID params=reinterpret_cast<CREATESTRUCT*>(lParam)->lpCreateParams;
        _this=static_cast<CDArtDisplayInterface*>(params);
        SetWindowLongA(hWnd,GWL_USERDATA,(LONG)_this);

        static_api_ptr_t<play_callback_manager> pcm;
        pcm->register_callback(_this,play_callback::flag_on_playback_new_track|play_callback::flag_on_playback_edited,false);
    }
    else if (uMsg==WM_DESTROY) {
        static_api_ptr_t<play_callback_manager> pcm;
        pcm->unregister_callback(_this);
    }
    else if (uMsg==WM_USER) {
        static_api_ptr_t<playback_control> pbc;
        static_api_ptr_t<playlist_manager> plm;

        switch (lParam) {
            case IPC_PLAY: {
                pbc->start();
                return 1;
            }
            case IPC_PLAYPAUSE: {
                pbc->play_or_pause();
                return 1;
            }
            case IPC_FORCEPAUSE: {
                pbc->pause(true);
                return 1;
            }
            case IPC_STOP: {
                pbc->stop();
                return 1;
            }
            case IPC_NEXT: {
                pbc->start(playback_control::track_command_next);
                return 1;
            }
            case IPC_PREVIOUS: {
                pbc->start(playback_control::track_command_prev);
                return 1;
            }

            case IPC_SET_VOLUME: {
                // Get the volume scale factor in range ]0,100].
                double scale=static_cast<double>(wParam)/100.0;

                // Clamp the volume to valid input for log10().
                if (scale<=0.0) {
                    scale=1.0e-5;
                } else if (scale>1.0) {
                    scale=1.0;
                }

                pbc->set_volume(static_cast<float>(20.0*log10(scale)));
                return 1;
            }
            case IPC_GET_VOLUME: {
                // Get volume gain in dB in range [-100,0].
                float db=pbc->get_volume();
                return static_cast<LONG>(audio_math::gain_to_scale(db)*100.0);
            }
            case IPC_GET_CURRENT_TRACK: {
                if (!_this) {
                    return 0;
                }

                // Copy the information to a buffer.
                static char buffer[4096];
                ZeroMemory(buffer,sizeof(buffer));

                metadb_handle_ptr track;
                if (pbc->get_now_playing(track)) {
                    file_info_impl info;
                    if (track->get_info(info)) {
                        char const* title=info.meta_get("TITLE",0);
                        char const* artist=info.meta_get("ARTIST",0);
                        char const* album=info.meta_get("ALBUM",0);
                        char const* genre=info.meta_get("GENRE",0);
                        char const* year=info.meta_get("DATE",0);
                        char const* comment=info.meta_get("COMMENT",0);

                        // TODO: Think about making this an option in the GUI.
                        int number=atoi(info.meta_get("TRACKNUMBER",0));

                        int length=static_cast<int>(pbc->playback_get_length());
                        char const* path=track->get_path()+sizeof("file://")-1;

                        // TODO: Find out how to get the rating.
                        char const* rating=info.meta_get("RATING",0);

                        // TODO: Think about making this an option in the GUI.
                        char const* covers="";

                        _snprintf_s(
                            buffer,
                            _TRUNCATE,
                            "%s\t%s\t%s\t%s\t%s\t%s\t%d\t%d\t%s\t%s\t%s",
                            title,artist,album,genre,
                            year,comment,number,length,
                            path,
                            rating,
                            covers
                        );
                    }
                }

                // Pass the buffer to CDA.
                static COPYDATASTRUCT cds;
                cds.dwData=IPC_GET_CURRENT_TRACK;
                cds.cbData=sizeof(buffer);
                cds.lpData=buffer;

                return SendMessage(_this->m_cda_window,WM_COPYDATA,reinterpret_cast<WPARAM>(hWnd),reinterpret_cast<LPARAM>(&cds));
            }

            case IPC_GET_DURATION: {
                return static_cast<LONG>(pbc->playback_get_length());
            }
            case IPC_SET_POSITION: {
                pbc->playback_seek(static_cast<double>(wParam));
                return static_cast<LONG>(pbc->playback_get_position());
            }
            case IPC_IS_PLAYING: {
                return pbc->is_playing();
            }
            case IPC_IS_PAUSED: {
                return pbc->is_paused();
            }
            case IPC_GET_LIST_LENGTH: {
                return plm->activeplaylist_get_item_count();
            }
            case IPC_SET_LIST_POS: {
                // TODO: Find a way to make this work if playback is not the default action.
                plm->activeplaylist_execute_default_action(static_cast<t_size>(wParam));
                return 1;
            }
            case IPC_GET_LIST_ITEM: {
                if (!_this) {
                    return 0;
                }

                // Copy the information to a buffer.
                static char buffer[4096];
                ZeroMemory(buffer,sizeof(buffer));

                // TODO: Copy song information to buffer.

                // Pass the buffer to CDA.
                static COPYDATASTRUCT cds;
                cds.dwData=IPC_GET_LIST_ITEM;
                cds.cbData=sizeof(buffer);
                cds.lpData=buffer;

                return SendMessage(_this->m_cda_window,WM_COPYDATA,reinterpret_cast<WPARAM>(hWnd),reinterpret_cast<LPARAM>(&cds));
            }
            case IPC_SET_CALLBACK_HWND: {
                if (!_this) {
                    return 0;
                }
                _this->m_cda_window=reinterpret_cast<HWND>(wParam);
                return 1;
            }
            case IPC_GET_LIST_POS: {
                return static_cast<LONG>(plm->activeplaylist_get_focus_item());
            }
            case IPC_GET_POSITION: {
                return static_cast<LONG>(pbc->playback_get_position());
            }

            // IPC_TRACK_CHANGED_NOTIFICATION gets handled by a virtual method.

            case IPC_SHOW_PLAYER_WINDOW: {
                static_api_ptr_t<user_interface>()->activate();
                return 1;
            }
            case IPC_GET_PLAYER_STATE: {
                if (pbc->is_paused()) {
                    return 2;
                }
                if (pbc->is_playing()) {
                    return 1;
                }
                return 0;
            }

            // IPC_RATING_CHANGED_NOTIFICATION gets handled by a virtual method

            default: {
                return 0;
            }
        }
    }

    return DefWindowProc(hWnd,uMsg,wParam,lParam);
}

ATOM CDArtDisplayInterface::s_atom=0;
int CDArtDisplayInterface::s_instances=0;

static initquit_factory_t<CDArtDisplayInterface> foo_initquit;
<commit_msg>Implemented IPC_PLAYER_STATE_CHANGED_NOTIFICATION.<commit_after>// Get rid of tons of warnings.
#pragma warning(push,1)
#include <foobar2000/SDK/foobar2000.h>
#pragma warning(pop)

#define FOO_CAD_VERSION     "1.0"
#define FOO_PLUGIN_RELEASE  "1"
#define FOO_PLUGIN_NAME     _T("foo_cdartdisplay")
#define FOO_CLASS_NAME      _T("THeliumMainForm")

DECLARE_COMPONENT_VERSION(
    "CD Art Display Interface",
    FOO_CAD_VERSION " release " FOO_PLUGIN_RELEASE,
    "Message handling plug-in to interface with CD Art Display <http://www.closetosoftware.com/?s=cdartdisplay>.\n"
    "Compiled on " __DATE__ ", copyright 2007 by eyebex <eyebex@threekings.tk>."
);

enum HeliumMessage {
    IPC_PLAY                              = 100,
    IPC_PLAYPAUSE                              ,
    IPC_FORCEPAUSE                             ,
    IPC_STOP                                   ,
    IPC_NEXT                                   ,
    IPC_PREVIOUS                               ,

    IPC_SET_VOLUME                        = 108,
    IPC_GET_VOLUME                             ,
    IPC_GET_CURRENT_TRACK                      ,

    IPC_GET_DURATION                      = 113,
    IPC_SET_POSITION                           ,
    IPC_IS_PLAYING                             ,
    IPC_IS_PAUSED                              ,
    IPC_GET_LIST_LENGTH                        ,
    IPC_SET_LIST_POS                           ,
    IPC_GET_LIST_ITEM                          ,
    IPC_SET_CALLBACK_HWND                      ,
    IPC_GET_LIST_POS                           ,
    IPC_GET_POSITION                           ,
    IPC_TRACK_CHANGED_NOTIFICATION             , // Message to send to CAD.
    IPC_SHOW_PLAYER_WINDOW                     ,
    IPC_GET_PLAYER_STATE                       ,
    IPC_PLAYER_STATE_CHANGED_NOTIFICATION      , // Message to send to CAD.
    IPC_AUTOENQUEUE_OPTIONS                    , // Ignored.

    IPC_RATING_CHANGED_NOTIFICATION       = 639, // Message to send to CAD.

    IPC_NEW_COVER_NOTIFICATION            = 800  // Message to send to CAD (ignored).
};

enum HeliumState {
    HS_STOPPED    ,
    HS_PLAYING    ,
    HS_PAUSED
};

class CDArtDisplayInterface:public initquit,public play_callback
{
  public:

    void on_init() {
        if (!s_atom) {
            // Register a minimal window class.
            WNDCLASS cls;
            memset(&cls,0,sizeof(cls));
            cls.style=CS_OWNDC|CS_SAVEBITS;
            cls.lpfnWndProc=WindowProc;
            cls.hInstance=core_api::get_my_instance();
            cls.hCursor=LoadCursor(NULL,IDC_ARROW);
            cls.lpszClassName=FOO_CLASS_NAME;

            s_atom=RegisterClass(&cls);
            if (!s_atom) {
#ifndef NDEBUG
                MessageBox(core_api::get_main_window(),_T("Unable to register the window class."),FOO_PLUGIN_NAME,MB_OK|MB_ICONERROR);
#endif
                return;
            }
        }

        // Create a dummy window.
        m_dummy_window=CreateWindow(
        /* lpClassName  */ MAKEINTATOM(s_atom),
        /* lpWindowName */ FOO_PLUGIN_NAME,
        /* dwStyle      */ 0,
        /* x            */ 0,
        /* y            */ 0,
        /* nWidth       */ 0,
        /* nHeight      */ 0,
        /* hWndParent   */ core_api::get_main_window(),
        /* hMenu        */ NULL,
        /* hInstance    */ core_api::get_my_instance(),
        /* lpParam      */ this
        );
        if (!m_dummy_window) {
#ifndef NDEBUG
            MessageBox(core_api::get_main_window(),_T("Unable to create the dummy window."),FOO_PLUGIN_NAME,MB_OK|MB_ICONERROR);
#endif
            return;
        }

        m_cda_window=NULL;
        ++s_instances;

#ifndef NDEBUG
        MessageBox(core_api::get_main_window(),_T("Construction was successful."),FOO_PLUGIN_NAME,MB_OK|MB_ICONINFORMATION);
#endif
    }

    void on_quit() {
        if (!DestroyWindow(m_dummy_window)) {
#ifndef NDEBUG
            MessageBox(core_api::get_main_window(),_T("Unable to destroy the dummy window."),FOO_PLUGIN_NAME,MB_OK|MB_ICONERROR);
#endif
            return;
        }

        if (--s_instances<=0) {
            if (!UnregisterClass(MAKEINTATOM(s_atom),NULL)) {
#ifndef NDEBUG
                MessageBox(core_api::get_main_window(),_T("Unable to unregister the window class."),FOO_PLUGIN_NAME,MB_OK|MB_ICONERROR);
#endif
                return;
            }

            s_atom=0;
        }

#ifndef NDEBUG
        MessageBox(core_api::get_main_window(),_T("Destruction was successful."),FOO_PLUGIN_NAME,MB_OK|MB_ICONINFORMATION);
#endif
    }

    // warning C4100: unreferenced formal parameter
    #pragma warning(disable:4100)

    void on_playback_seek(double p_time) {}
    void on_playback_dynamic_info(const file_info & p_info) {}
    void on_playback_dynamic_info_track(const file_info & p_info) {}
    void on_playback_time(double p_time) {}
    void on_volume_change(float p_new_val) {}

    #pragma warning(default:4100)

    void on_playback_starting(play_control::t_track_command p_command,bool p_paused) {
        if (p_paused) {
            SendMessage(m_cda_window,WM_USER,static_cast<WPARAM>(HS_PAUSED),IPC_PLAYER_STATE_CHANGED_NOTIFICATION);
        } else {
            if (p_command==play_control::track_command_play || p_command==play_control::track_command_resume) {
                SendMessage(m_cda_window,WM_USER,static_cast<WPARAM>(HS_PLAYING),IPC_PLAYER_STATE_CHANGED_NOTIFICATION);
            }
        }
    }

    void on_playback_stop(play_control::t_stop_reason p_reason) {
        if (p_reason==play_control::stop_reason_user || p_reason==play_control::stop_reason_shutting_down) {
            SendMessage(m_cda_window,WM_USER,static_cast<WPARAM>(HS_STOPPED),IPC_PLAYER_STATE_CHANGED_NOTIFICATION);
        }
    }

    void on_playback_pause(bool p_state) {
        HeliumState state=p_state?HS_PAUSED:HS_PLAYING;
        SendMessage(m_cda_window,WM_USER,static_cast<WPARAM>(state),IPC_PLAYER_STATE_CHANGED_NOTIFICATION);
    }

    void on_playback_new_track(metadb_handle_ptr p_track) {
        SendMessage(m_cda_window,WM_USER,0,IPC_TRACK_CHANGED_NOTIFICATION);
    }

    void on_playback_edited(metadb_handle_ptr p_track) {
        file_info_impl info;
        if (p_track->get_info(info)) {
            // TODO: Find out how to get the rating.
            int rating=atoi(info.meta_get("RATING",0));
            SendMessage(m_cda_window,WM_USER,static_cast<WPARAM>(rating),IPC_RATING_CHANGED_NOTIFICATION);
        }
    }

  private:

    static ATOM s_atom;
    static int s_instances;

    HWND m_dummy_window;
    HWND m_cda_window;

    static LRESULT CALLBACK WindowProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam);
};

LRESULT CALLBACK CDArtDisplayInterface::WindowProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam) {
    // Using a dynamic_cast here would be safer, but that requires RTTI support.
    CDArtDisplayInterface *_this=reinterpret_cast<CDArtDisplayInterface*>(GetWindowLong(hWnd,GWL_USERDATA));

    if (uMsg==WM_CREATE) {
        LPVOID params=reinterpret_cast<CREATESTRUCT*>(lParam)->lpCreateParams;
        _this=static_cast<CDArtDisplayInterface*>(params);
        SetWindowLongA(hWnd,GWL_USERDATA,(LONG)_this);

        static_api_ptr_t<play_callback_manager> pcm;
        pcm->register_callback(
            _this,
            play_callback::flag_on_playback_starting |
            play_callback::flag_on_playback_stop |
            play_callback::flag_on_playback_pause |
            play_callback::flag_on_playback_new_track |
            play_callback::flag_on_playback_edited,
            false
        );
    }
    else if (uMsg==WM_DESTROY) {
        static_api_ptr_t<play_callback_manager> pcm;
        pcm->unregister_callback(_this);
    }
    else if (uMsg==WM_USER) {
        static_api_ptr_t<playback_control> pbc;
        static_api_ptr_t<playlist_manager> plm;

        switch (lParam) {
            case IPC_PLAY: {
                pbc->start();
                return 1;
            }
            case IPC_PLAYPAUSE: {
                pbc->play_or_pause();
                return 1;
            }
            case IPC_FORCEPAUSE: {
                pbc->pause(true);
                return 1;
            }
            case IPC_STOP: {
                pbc->stop();
                return 1;
            }
            case IPC_NEXT: {
                pbc->start(playback_control::track_command_next);
                return 1;
            }
            case IPC_PREVIOUS: {
                pbc->start(playback_control::track_command_prev);
                return 1;
            }

            case IPC_SET_VOLUME: {
                // Get the volume scale factor in range ]0,100].
                double scale=static_cast<double>(wParam)/100.0;

                // Clamp the volume to valid input for log10().
                if (scale<=0.0) {
                    scale=1.0e-5;
                } else if (scale>1.0) {
                    scale=1.0;
                }

                pbc->set_volume(static_cast<float>(20.0*log10(scale)));
                return 1;
            }
            case IPC_GET_VOLUME: {
                // Get volume gain in dB in range [-100,0].
                float db=pbc->get_volume();
                return static_cast<LONG>(audio_math::gain_to_scale(db)*100.0);
            }
            case IPC_GET_CURRENT_TRACK: {
                if (!_this) {
                    return 0;
                }

                // Copy the information to a buffer.
                static char buffer[4096];
                ZeroMemory(buffer,sizeof(buffer));

                metadb_handle_ptr track;
                if (pbc->get_now_playing(track)) {
                    file_info_impl info;
                    if (track->get_info(info)) {
                        char const* title=info.meta_get("TITLE",0);
                        char const* artist=info.meta_get("ARTIST",0);
                        char const* album=info.meta_get("ALBUM",0);
                        char const* genre=info.meta_get("GENRE",0);
                        char const* year=info.meta_get("DATE",0);
                        char const* comment=info.meta_get("COMMENT",0);

                        // TODO: Think about making this an option in the GUI.
                        int number=atoi(info.meta_get("TRACKNUMBER",0));

                        int length=static_cast<int>(pbc->playback_get_length());
                        char const* path=track->get_path()+sizeof("file://")-1;

                        // TODO: Find out how to get the rating.
                        char const* rating=info.meta_get("RATING",0);

                        // TODO: Think about making this an option in the GUI.
                        char const* covers="";

                        _snprintf_s(
                            buffer,
                            _TRUNCATE,
                            "%s\t%s\t%s\t%s\t%s\t%s\t%d\t%d\t%s\t%s\t%s",
                            title,artist,album,genre,
                            year,comment,number,length,
                            path,
                            rating,
                            covers
                        );
                    }
                }

                // Pass the buffer to CDA.
                static COPYDATASTRUCT cds;
                cds.dwData=IPC_GET_CURRENT_TRACK;
                cds.cbData=sizeof(buffer);
                cds.lpData=buffer;

                return SendMessage(_this->m_cda_window,WM_COPYDATA,reinterpret_cast<WPARAM>(hWnd),reinterpret_cast<LPARAM>(&cds));
            }

            case IPC_GET_DURATION: {
                return static_cast<LONG>(pbc->playback_get_length());
            }
            case IPC_SET_POSITION: {
                pbc->playback_seek(static_cast<double>(wParam));
                return static_cast<LONG>(pbc->playback_get_position());
            }
            case IPC_IS_PLAYING: {
                return pbc->is_playing();
            }
            case IPC_IS_PAUSED: {
                return pbc->is_paused();
            }
            case IPC_GET_LIST_LENGTH: {
                return plm->activeplaylist_get_item_count();
            }
            case IPC_SET_LIST_POS: {
                // TODO: Find a way to make this work if playback is not the default action.
                plm->activeplaylist_execute_default_action(static_cast<t_size>(wParam));
                return 1;
            }
            case IPC_GET_LIST_ITEM: {
                if (!_this) {
                    return 0;
                }

                // Copy the information to a buffer.
                static char buffer[4096];
                ZeroMemory(buffer,sizeof(buffer));

                // TODO: Copy song information to buffer.

                // Pass the buffer to CDA.
                static COPYDATASTRUCT cds;
                cds.dwData=IPC_GET_LIST_ITEM;
                cds.cbData=sizeof(buffer);
                cds.lpData=buffer;

                return SendMessage(_this->m_cda_window,WM_COPYDATA,reinterpret_cast<WPARAM>(hWnd),reinterpret_cast<LPARAM>(&cds));
            }
            case IPC_SET_CALLBACK_HWND: {
                if (!_this) {
                    return 0;
                }
                _this->m_cda_window=reinterpret_cast<HWND>(wParam);
                return 1;
            }
            case IPC_GET_LIST_POS: {
                return static_cast<LONG>(plm->activeplaylist_get_focus_item());
            }
            case IPC_GET_POSITION: {
                return static_cast<LONG>(pbc->playback_get_position());
            }

            case IPC_SHOW_PLAYER_WINDOW: {
                static_api_ptr_t<user_interface>()->activate();
                return 1;
            }
            case IPC_GET_PLAYER_STATE: {
                if (pbc->is_paused()) {
                    return HS_PAUSED;
                }
                if (pbc->is_playing()) {
                    return HS_PLAYING;
                }
                return HS_STOPPED;
            }

            default: {
                return 0;
            }
        }
    }

    return DefWindowProc(hWnd,uMsg,wParam,lParam);
}

ATOM CDArtDisplayInterface::s_atom=0;
int CDArtDisplayInterface::s_instances=0;

static initquit_factory_t<CDArtDisplayInterface> foo_initquit;
<|endoftext|>


<commit_before>73e688ca-4b02-11e5-83ac-28cfe9171a43<commit_msg>add file<commit_after>73f16394-4b02-11e5-ba57-28cfe9171a43<|endoftext|>


<commit_before>#include <QtGui/QGuiApplication>
#include <QQuickItem>
#include <QDebug>
#include <QQmlContext>
#include <QSortFilterProxyModel>
#include "qtquick2applicationviewer.h"

#include "resource.h"

void populateResourceList(ListModel * model, QFile & resourceSaveFile);

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    QtQuick2ApplicationViewer viewer;

    // Get the file name
    QFile resourceSaveFile("C:\\Users\\jmbeck\\Desktop\\TaS Saves\\saves - Copy\\New Settlement\\re.sav");

    // Create a model that holds our resource data, and
    // add the data to it.
    ListModel * resourceModel = new ListModel(new Resource, qApp);
    populateResourceList(resourceModel, resourceSaveFile);

    // Create the proxy model that contains the results of the filter.
    QSortFilterProxyModel * proxyResourceModel = new QSortFilterProxyModel();
    proxyResourceModel->setSourceModel(resourceModel);
    proxyResourceModel->setFilterRole(Resource::FilterStringRole);

    // Enable the case insensitivity
    proxyResourceModel->setFilterCaseSensitivity(Qt::CaseInsensitive);

    // Setup sorting the resources
    proxyResourceModel->setSortRole(Resource::TypeRole);
    proxyResourceModel->sort(0);

    // Link the resource data to the GUI viewer
    viewer.rootContext()->setContextProperty("resourceModel", proxyResourceModel);

    viewer.setMainQmlFile(QStringLiteral("qml/AxeAndPick/main.qml"));

    // Show the GUI
    viewer.showExpanded();

    return app.exec();
}

void populateResourceList(ListModel * model, QFile & resourceSaveFile)
{
    // Pull the save file data in.
    if (resourceSaveFile.open(QIODevice::ReadWrite))
    {
        qDebug() << "Opened Save File: " << resourceSaveFile.fileName();
    }

    // Pull in the list of resource assets (name, group, etc)
    QFile assetFile(QCoreApplication::applicationDirPath() + "/resource_list.txt");

    if (assetFile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug() << "Opened Asset File: " << assetFile.fileName();

        QTextStream assetStream(&assetFile);

        while (!resourceSaveFile.atEnd())
        {
            // Grab the next section and decide the size, etc.
            QString resourceString;
            if (!assetStream.atEnd())
            {
                resourceString = assetStream.readLine();
            }
            else
            {
                resourceString = "unexpected data,unknown,resource-unknown.svg";
            }

            QStringList assetData;
            assetData = resourceString.split(',');

            QByteArray resourceQuantity;
            resourceQuantity = resourceSaveFile.read(2);
//            qDebug() << "Byte: " << resourceQuantity[0]
//                     << " and "  << resourceQuantity[1];

            // Create a new Resource with the quantity, and use the
            // data from the ResourceAssetList to flush it out.
            model->appendRow(new Resource(assetData[0],
                                          assetData[1],
                                          assetData[2],
                                          resourceQuantity[1]+128,
                                          0));
        }
    }
    else
    {
        qDebug() << "Could not open " << assetFile.fileName();
    }

    // Pull in the file that contains the saved-game resources

}
<commit_msg>Properly pull in Quantities from re.sav file<commit_after>#include <QtGui/QGuiApplication>
#include <QQuickItem>
#include <QDebug>
#include <QQmlContext>
#include <QSortFilterProxyModel>
#include "qtquick2applicationviewer.h"

#include "resource.h"

void populateResourceList(ListModel * model, QFile & resourceSaveFile);

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    QtQuick2ApplicationViewer viewer;

    // Get the file name
    QFile resourceSaveFile("C:\\Users\\jmbeck\\Desktop\\Timber and Stone pld1\\saves\\Test\\re.sav");

    // Create a model that holds our resource data, and
    // add the data to it.
    ListModel * resourceModel = new ListModel(new Resource, qApp);
    populateResourceList(resourceModel, resourceSaveFile);

    // Create the proxy model that contains the results of the filter.
    QSortFilterProxyModel * proxyResourceModel = new QSortFilterProxyModel();
    proxyResourceModel->setSourceModel(resourceModel);
    proxyResourceModel->setFilterRole(Resource::FilterStringRole);

    // Enable the case insensitivity
    proxyResourceModel->setFilterCaseSensitivity(Qt::CaseInsensitive);

    // Setup sorting the resources
    //proxyResourceModel->setSortRole(Resource::TypeRole);
    //proxyResourceModel->sort(0);

    // Link the resource data to the GUI viewer
    viewer.rootContext()->setContextProperty("resourceModel", proxyResourceModel);

    Resource * testResource = new Resource("Test Resource", "mytype", "icon.jpg", 0, 0);
    viewer.rootContext()->setContextProperty("testResource", testResource);

    viewer.setMainQmlFile(QStringLiteral("qml/AxeAndPick/main.qml"));

    // Show the GUI
    viewer.showExpanded();

    return app.exec();
}

void populateResourceList(ListModel * model, QFile & resourceSaveFile)
{
    // Mask for the quantity bytes
    const unsigned char MASK = 0x3F;

    // Pull the save file data in.
    if (resourceSaveFile.open(QIODevice::ReadWrite))
    {
        qDebug() << "Opened Save File: " << resourceSaveFile.fileName();
    }

    // Pull in the list of resource assets (name, group, etc)
    QFile assetFile(QCoreApplication::applicationDirPath() + "/resource_list.txt");

    if (assetFile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug() << "Opened Asset File: " << assetFile.fileName();

        QTextStream assetStream(&assetFile);

        while (!resourceSaveFile.atEnd())
        //for( int i=0; i<3; i++ )
        {
            // Grab the next section and decide the size, etc.
            QString resourceString;
            if (!assetStream.atEnd())
            {
                resourceString = assetStream.readLine();
            }
            else
            {
                resourceString = "unexpected data,unknown,resource-unknown.svg";
            }

            QStringList assetData;
            assetData = resourceString.split(',');

            // Temporary array to hold the bytes we read from the file.
            quint8 byteArray[4];

            char sigByte; // Most Significant Byte
            resourceSaveFile.read(&sigByte, 1);
            if( (unsigned char)sigByte >= 224)
            {
                // Pull in the middle byte, because they must be processed together.
                char middleByte;
                resourceSaveFile.read(&middleByte, 1);
                byteArray[1] = ((middleByte&MASK) | ((sigByte&MASK) << 6)) - 2;
            }
            else
            {
                byteArray[1] = sigByte - 0xC2;
            }

            char leastByte;
            resourceSaveFile.read(&leastByte, 1);
            byteArray[0] = leastByte - 0x80;

            // Build the quantity out of the read bytes.
            quint32 resourceQuantity;
            resourceQuantity = byteArray[0] & MASK;
            resourceQuantity |= byteArray[1] << 6;

            // Create a new Resource with the quantity, and use the
            // data from the ResourceAssetList to flush it out.
            model->appendRow(new Resource(assetData[0],
                                          assetData[1],
                                          assetData[2],
                                          resourceQuantity,
                                          0));
        }
    }
    else
    {
        qDebug() << "Could not open " << assetFile.fileName();
    }

    // Pull in the file that contains the saved-game resources

}
<|endoftext|>


<commit_before>#include <istream>
#include <ostream>
#include <iostream>
#include <vector>
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>

#include "./player.hpp"
#include "./lineartransition.hpp"

sf::Color operator-(const sf::Color &c1, const sf::Color &c2)
{
    return sf::Color(c1.r - c2.r,
                     c1.g - c2.g,
                     c1.b - c2.b,
                     c1.a - c2.a);
}

sf::Color operator*(const sf::Color &color, float f)
{
    return sf::Color(color.r * f,
                     color.g * f,
                     color.b * f);
}

sf::CircleShape playerToCircle(const Player &player)
{
    sf::CircleShape circle(player.radius.value());
    circle.setFillColor(player.color.value());
    circle.setPosition(player.position.value());
    return circle;
}

int main()
{
    sf::RenderWindow App(sf::VideoMode(800, 600, 32), "Hello World - SFML");
    sf::SoundBuffer kickBuffer, snareBuffer, hihatBuffer;

    if (!kickBuffer.loadFromFile("data/kick.wav")) {
        std::cout << "[ERROR] Cannot load data/kick.wav" << std::endl;
        return 1;
    }

    if (!snareBuffer.loadFromFile("data/snare.wav")) {
        std::cout << "[ERROR] Cannot load data/snare.wav" << std::endl;
         return 1;
    }

    if (!hihatBuffer.loadFromFile("data/hihat.wav")) {
        std::cout << "[ERROR] Cannot load data/hihat.wav" << std::endl;
        return 1;
    }

    Player player(sf::Vector2<float>(200.0f, 200.0f),
                  50.0f,
                  sf::Color(255.0f, 255.0f, 255.0f));

    sf::Sound kickSound, snareSound , hihatSound;
    kickSound.setBuffer(kickBuffer);
    snareSound.setBuffer(snareBuffer);
    hihatSound.setBuffer(hihatBuffer);

    sf::Clock clock;

    while (App.isOpen())
    {
        // std::cout << state << std::endl;
        clock.restart();
        sf::Event Event;
        while (App.pollEvent(Event))
        {
            if (Event.type == sf::Event::Closed) {
                App.close();
            } else if (Event.type == sf::Event::JoystickButtonPressed) {
                switch (Event.joystickButton.button) {
                case 0:         // kick
                    player.radius.animate(moveTo(70.0f, 300, 50.0f));
                    player.color.animate(moveTo(sf::Color::Red, 300, sf::Color::White));
                    player.position.animate(moveBy(player.position.value(),
                                                   300,
                                                   sf::Vector2f(100.0f, 0.0f)));

                    kickSound.play();
                    break;

                case 1:         // snare
                    player.color.animate(moveTo(sf::Color::Green, 300, sf::Color::White));
                    snareSound.play();
                    break;

                case 2:         // hihat
                    player.radius.animate(moveTo(70.0f, 300, 50.0f));
                    player.color.animate(moveTo(sf::Color::Blue, 300, sf::Color::White));
                    hihatSound.play();
                    break;

                default: {}
                }
            }
        }

        App.clear(sf::Color(0, 0, 0));
        player.tick(clock.getElapsedTime().asMilliseconds());
        App.draw(playerToCircle(player));
        App.display();
    }

    return 0;
}
<commit_msg>Remap actions to keyboard. Tweak animations. (#3)<commit_after>#include <istream>
#include <ostream>
#include <iostream>
#include <vector>
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>

#include "./player.hpp"
#include "./lineartransition.hpp"

sf::Color operator-(const sf::Color &c1, const sf::Color &c2)
{
    return sf::Color(c1.r - c2.r,
                     c1.g - c2.g,
                     c1.b - c2.b,
                     c1.a - c2.a);
}

sf::Color operator*(const sf::Color &color, float f)
{
    return sf::Color(color.r * f,
                     color.g * f,
                     color.b * f);
}

sf::CircleShape playerToCircle(const Player &player)
{
    const float radius = player.radius.value();
    sf::CircleShape circle(player.radius.value());
    circle.setFillColor(player.color.value());
    circle.setPosition(player.position.value() - sf::Vector2f(radius, radius));
    return circle;
}

int main()
{
    sf::RenderWindow App(sf::VideoMode(1024, 768, 32), "Hello World - SFML");
    sf::SoundBuffer kickBuffer, snareBuffer, hihatBuffer;

    if (!kickBuffer.loadFromFile("data/kick.wav")) {
        std::cout << "[ERROR] Cannot load data/kick.wav" << std::endl;
        return 1;
    }

    if (!snareBuffer.loadFromFile("data/snare.wav")) {
        std::cout << "[ERROR] Cannot load data/snare.wav" << std::endl;
         return 1;
    }

    if (!hihatBuffer.loadFromFile("data/hihat.wav")) {
        std::cout << "[ERROR] Cannot load data/hihat.wav" << std::endl;
        return 1;
    }

    Player player(sf::Vector2<float>(200.0f, 200.0f),
                  50.0f,
                  sf::Color(255.0f, 255.0f, 255.0f));

    sf::Sound kickSound, snareSound , hihatSound;
    kickSound.setBuffer(kickBuffer);
    snareSound.setBuffer(snareBuffer);
    hihatSound.setBuffer(hihatBuffer);

    sf::Clock clock;

    const sf::Int32 moveTime = 150;
    const sf::Int32 colorTime = 700;

    while (App.isOpen())
    {
        // std::cout << state << std::endl;
        clock.restart();
        sf::Event Event;
        while (App.pollEvent(Event))
        {
            if (Event.type == sf::Event::Closed) {
                App.close();
            } else if (Event.type == sf::Event::KeyPressed) {
                switch (Event.key.code) {
                case sf::Keyboard::Space:         // kick
                    player.radius.animate(moveTo(70.0f, colorTime, 50.0f));
                    player.color.animate(moveTo(sf::Color::Red, colorTime, sf::Color::White));
                    player.position.animate(moveBy(player.position.value(),
                                                   moveTime,
                                                   sf::Vector2f(100.0f, 0.0f)));

                    kickSound.play();
                    break;

                case sf::Keyboard::S:         // snare
                    player.radius.animate(moveTo(70.0f, colorTime, 50.0f));
                    player.color.animate(moveTo(sf::Color::Green, colorTime, sf::Color::White));
                    player.position.animate(moveBy(player.position.value(),
                                                   moveTime,
                                                   sf::Vector2f(0.0f, 100.0f)));

                    snareSound.play();
                    break;

                case sf::Keyboard::P:         // hihat
                    player.radius.animate(moveTo(70.0f, colorTime, 50.0f));
                    player.color.animate(moveTo(sf::Color::Blue, colorTime, sf::Color::White));
                    player.position.animate(moveBy(player.position.value(),
                                                   moveTime,
                                                   sf::Vector2f(0.0f, -100.0f)));
                    hihatSound.play();
                    break;

                default: {}
                }
            }
        }

        App.clear(sf::Color(0, 0, 0));
        player.tick(clock.getElapsedTime().asMilliseconds());
        App.draw(playerToCircle(player));
        App.display();
    }

    return 0;
}
<|endoftext|>


<commit_before>c691bacc-4b02-11e5-a53e-28cfe9171a43<commit_msg>Bug fixes and performance improvements<commit_after>c6a233ae-4b02-11e5-8b4d-28cfe9171a43<|endoftext|>


<commit_before>#include <iostream>
#include <ctime>
#include <cstdlib>
#include <cmath>
#include <cv.h>
#include <highgui.h>
#include <opencv2/opencv.hpp>

#define DEFAULT_INTERVAL 0.01
#define DEFAULT_HIGH 3.0
#define SAMPLING_RANGE 50
#define FILE_PATH "home.png"
#define MIN_RANGE 50
#define MIN_HIGH 1.0
#define INTERVAL(interval, x)  interval * abs(x) / pow(SAMPLING_RANGE, 2)

using namespace std;
using namespace cv;

class Way {
public:
    Way() {
        vertical = 0;
        horizontal = 0;
    }
    int vertical;
    int horizontal;
};
void check(Mat &, Way &);
void move(const Way &, double);
void landing();
void flyDown(double);
void flyFront(double);
void flyBack(double);
void flyRight(double);
void flyLeft(double);

int main() {
    string path = FILE_PATH;
    double high = DEFAULT_HIGH;
    Mat image = imread(path, CV_LOAD_IMAGE_UNCHANGED);
    Way w;
    w.vertical = 0;
    w.horizontal = 0;
    check(image, w);
    move(w, high);
    return 0;
}

void check(Mat &I, Way &W) {
    int w = I.cols;
    int h = I.rows;
    int ox = w / 2;
    int oy = h / 2;
    for(int i = ox - SAMPLING_RANGE; i < ox + SAMPLING_RANGE; i++) {
        for(int j = oy - SAMPLING_RANGE; j < oy + SAMPLING_RANGE; j++) {
            int r = I.at<Vec3b>(j, i)[2];
            int g = I.at<Vec3b>(j, i)[1];
            int b = I.at<Vec3b>(j, i)[0];
            if(r > 200 && g > 200 && b < 50)
                W.horizontal++;
            else if(r > 128 && g < 50 && b < 50)
                W.horizontal--;
            else if(r < 50 && g < 50 && b > 128)
                W.vertical++;
            else if(r < 50 && g > 128 && b < 50)
                W.vertical--;
        }
    }
}

void move(const Way &W, double high) {
    cout << "vertical " << W.vertical << " horizontal " << W.horizontal << endl;
    cout << pow(SAMPLING_RANGE, 2) << endl;
    double interval = DEFAULT_INTERVAL;
    interval += high / 100;
    if(abs(W.vertical) < MIN_RANGE && abs(W.horizontal) < MIN_RANGE){
        if(high < MIN_HIGH)
            landing();
        else
            flyDown(MIN_HIGH);
    } else {
        double dVer = INTERVAL(interval, W.vertical);
        double dHor = INTERVAL(interval, W.horizontal);
        if(W.vertical > MIN_RANGE)
            flyFront(dVer);
        else if(W.vertical < MIN_RANGE * -1)
            flyBack(dVer);
        if(W.horizontal > MIN_RANGE)
            flyRight(dHor);
        else if(W.horizontal < MIN_RANGE * -1)
            flyLeft(dHor);
    }
}

//TODO:封裝在drone
void landing() {
    cout << "landing " << endl;
}

void flyDown(double distance) {
    cout << "fly down " << distance << endl;
}

void flyFront(double distance) {
    cout << "fly front " << distance << endl;
}

void flyBack(double distance) {
    cout << "fly back " << distance << endl;
}

void flyRight(double distance) {
    cout << "fly right " << distance << endl;
}

void flyLeft(double distance) {
    cout << "fly doleftwn " << distance << endl;
}<commit_msg>beautify<commit_after>#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <cv.h>
#include <highgui.h>
#include <opencv2/opencv.hpp>

#define INTERVAL(interval, x) interval * abs(x) / pow(SAMPLING_RANGE, 2)
#define FILE_PATH             "home.png"
#define DEFAULT_INTERVAL      0.01
#define DEFAULT_HIGH          3.0
#define SAMPLING_RANGE        50
#define MIN_RANGE             50
#define MIN_HIGH              1.0

using namespace std;
using namespace cv;

class Way {
public:
    Way() {
        vertical   = 0;
        horizontal = 0;
    }
    int vertical;
    int horizontal;
};

void flyFront(double);
void flyRight(double);
void flyBack(double);
void flyLeft(double);
void landing();
void flyDown(double);
void check(Mat &, Way &);
void move(const Way &, double);

int main() {
    string path  = FILE_PATH;
    double high  = DEFAULT_HIGH;
    Mat    image = imread(path, CV_LOAD_IMAGE_UNCHANGED);
    Way    w;

    w.vertical   = 0;
    w.horizontal = 0;

    check(image, w);
    move(w, high);

    return 0;
}

void check(Mat &I, Way &W) {
    int w  = I.cols;
    int h  = I.rows;
    int ox = w / 2;
    int oy = h / 2;

    for(int i = ox - SAMPLING_RANGE; i < ox + SAMPLING_RANGE; i++) {
        for(int j = oy - SAMPLING_RANGE; j < oy + SAMPLING_RANGE; j++) {
            int r = I.at<Vec3b>(j, i)[2];
            int g = I.at<Vec3b>(j, i)[1];
            int b = I.at<Vec3b>(j, i)[0];

            if(     r > 200 && g > 200 && b < 50 ) W.horizontal++;
            else if(r > 128 && g < 50  && b < 50 ) W.horizontal--;
            else if(r < 50  && g < 50  && b > 128) W.vertical++;
            else if(r < 50  && g > 128 && b < 50 ) W.vertical--;
        }
    }
}

void move(const Way &W, double high) {
    cout << "vertical " << W.vertical << " horizontal " << W.horizontal << endl;
    cout << pow(SAMPLING_RANGE, 2) << endl;

    double interval = DEFAULT_INTERVAL;

    interval += high / 100;

    if(abs(W.vertical) < MIN_RANGE && abs(W.horizontal) < MIN_RANGE){
        if(high < MIN_HIGH)
            landing();
        else
            flyDown(MIN_HIGH);
    } else {
        double dVer = INTERVAL(interval, W.vertical);
        double dHor = INTERVAL(interval, W.horizontal);

        if(W.vertical > MIN_RANGE)
            flyFront(dVer);
        else if(W.vertical < MIN_RANGE * -1)
            flyBack(dVer);

        if(W.horizontal > MIN_RANGE)
            flyRight(dHor);
        else if(W.horizontal < MIN_RANGE * -1)
            flyLeft(dHor);
    }
}

//TODO:封裝在drone
void landing() {
    cout << "landing " << endl;
}

void flyDown(double distance) {
    cout << "fly down " << distance << endl;
}

void flyFront(double distance) {
    cout << "fly front " << distance << endl;
}

void flyBack(double distance) {
    cout << "fly back " << distance << endl;
}

void flyRight(double distance) {
    cout << "fly right " << distance << endl;
}

void flyLeft(double distance) {
    cout << "fly doleftwn " << distance << endl;
}<|endoftext|>


<commit_before>77e784d7-4b02-11e5-911a-28cfe9171a43<commit_msg>Nope, didn't work, now it does<commit_after>77f2c442-4b02-11e5-8951-28cfe9171a43<|endoftext|>


<commit_before>710e199e-ad5a-11e7-bd16-ac87a332f658<commit_msg>fixed bug<commit_after>718f56ba-ad5a-11e7-8b94-ac87a332f658<|endoftext|>


<commit_before>#include "defines.h"

#include "connection-manager.h"

#include <telepathy-glib/run.h>

int main(int argc, char *argv[])
{
	return tp_run_connection_manager(TP_CM_ID, TP_STEAM_VERSION, []()
	{
		return static_cast<TpBaseConnectionManager*>(g_object_new(steam_connection_manager_get_type(), NULL));
	}, argc, argv);
}
<commit_msg>main: add STEAM_PERSIST env variable<commit_after>#include "defines.h"

#include "connection-manager.h"

#include <cstdlib>

#include <telepathy-glib/debug.h>
#include <telepathy-glib/run.h>

int main(int argc, char *argv[])
{
	if (std::getenv("STEAM_PERSIST") != nullptr)
	{
		tp_debug_set_persistent(true);
	}

	return tp_run_connection_manager(TP_CM_ID, TP_STEAM_VERSION, []()
	{
		return static_cast<TpBaseConnectionManager*>(g_object_new(steam_connection_manager_get_type(), NULL));
	}, argc, argv);
}
<|endoftext|>


<commit_before>#include "MainWindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}
<commit_msg>Add app info<commit_after>#include "MainWindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QApplication::setApplicationName("ofProjectGenerator");
    QApplication::setApplicationVersion("1.0.1");
    QApplication::setOrganizationName("Furkanzmc");

    MainWindow w;
    w.show();

    return a.exec();
}
<|endoftext|>


<commit_before>#include <iostream>
#include <utility>
#include <tuple>

template <unsigned ...Args>
struct Mapper
{
  template <unsigned Value, bool Dummy = false>
  struct get
  {
    static_assert(Dummy == true, "List overflow, mate");
  };
};

template <unsigned First, unsigned ...Others>
struct Mapper<First, Others...> : Mapper<Others...>
{
  template <unsigned Value, bool Dummy = false>
  struct get;
};

template <unsigned First, unsigned ...Others>
template <unsigned Value, bool Dummy>
struct Mapper<First, Others...>::get
{
  constexpr get() = default;
  constexpr operator unsigned() const
  {
    return value;
  }
  static const unsigned value = Mapper<Others...>::template get<Value>::value + 1;
};

template <unsigned First, unsigned ...Others>
template <bool Dummy>
struct Mapper<First, Others...>::get<First, Dummy>
{
  constexpr get() = default;
  constexpr operator unsigned() const
  {
    return value;
  }
  static const unsigned value = 0;
};

int main()
{
    std::cout << Mapper<8, 41>::get<41>() << std::endl;
}
<commit_msg>naive FIX parser/mapper<commit_after>#include <exception>
#include <iostream>
#include <utility>
#include <tuple>
#include <cassert>

// TODO: change the return type for get_new (something that could tell if there is a non-valid index, instead of -1)

template <unsigned ...Args>
struct Mapper
{
  template <unsigned Value, bool Dummy = false>
  struct get
  {
    static_assert(Dummy == true, "List overflow, mate");
  };

  static constexpr unsigned get_new(unsigned)
  {
    return (-1);
  }
};

template <unsigned First, unsigned ...Others>
struct Mapper<First, Others...> : Mapper<Others...>
{
  template <unsigned Value, bool Dummy = false>
  struct get;
  static constexpr unsigned get_new(unsigned index_to_map)
  {
    return (index_to_map == First) ? 0 : Mapper<Others...>::get_new(index_to_map) + 1;
  }
};

template <unsigned First, unsigned ...Others>
template <unsigned Value, bool Dummy>
struct Mapper<First, Others...>::get
{
  constexpr get() = default;
  constexpr operator unsigned() const
  {
    return value;
  }
  static const unsigned value = Mapper<Others...>::template get<Value>::value + 1;
};

template <unsigned First, unsigned ...Others>
template <bool Dummy>
struct Mapper<First, Others...>::get<First, Dummy>
{
  constexpr get() = default;
  constexpr operator unsigned() const
  {
    return value;
  }
  static const unsigned value = 0;
};

template <unsigned ...Args>
struct UniqueList;

template <unsigned First, unsigned Second, unsigned ...Args>
struct UniqueList<First, Second, Args...>
{
  static const bool value = First != Second && UniqueList<First, Args...>::value && UniqueList<Second, Args...>::value;
};

template <unsigned Last>
struct UniqueList<Last>
{
  static const bool value = true;
};

template <unsigned ...Args>
struct unique_sequence
{
  static_assert(UniqueList<Args...>::value, "Sequence should be composed of unique elements.");
};

template <typename T, unsigned ...Args>
class translated_array : public unique_sequence<Args...>, private std::array<T, sizeof...(Args)>
{
  typedef std::array<T, sizeof...(Args)> Dad;
public:
  const T& operator[](unsigned index_to_map) const
  {
    return Dad::operator[](Mapper<Args...>::get_new(index_to_map));
  }

  T& operator[](unsigned index_to_map)
  {
    return const_cast<T&>(const_cast<const translated_array&>(*this)[index_to_map]);
  }

  static constexpr bool outofbound(unsigned index_to_map)
  {
    return (-1 == Mapper<Args...>::get_new(index_to_map));
  }

  using Dad::begin;
  using Dad::end;
  using Dad::size;
};

template <typename T>
struct ZeroInitialized
{
  ZeroInitialized() = default;
  ZeroInitialized(const ZeroInitialized&) = delete;
  ZeroInitialized(const T& t) : t_(t)
  {}

  operator const T&() const
  {
    return t_;
  }

  operator T&()
  {
    return const_cast<const ZeroInitialized&>(this);
  }

private:
  T t_{};
};

int main()
{
    std::cout << Mapper<8, 41>::get<41>() << std::endl;
    std::cout << Mapper<8, 41>::get_new(41) << std::endl;
    translated_array<
      ZeroInitialized<
	const char*>
      , 1, 2, 3> arr;

    const char *message =
      "8=foo\x01"
      "41=baz\x01"
      "23=bar\x01";

    {
      enum class State
      {
	Key,
	Value
      };

      State s = State::Key;
      while (*message)
	{
	  if (*message != '=' && *message != '\x01' && *message != '\0')
	    {
	      unsigned key = 0;
	      while ('0' <= *message && *message <= '9')
		{
		  key = key * 10 + *message - '0';
		  ++message;
		}
	      if (*message != '=' || !key)
		{
		  throw std::runtime_error("invalid value for key");
		}
	      if (!arr.outofbound(key))
		{
		  arr[key] = message + 1;
		}
	      while (*message != '\x01' && *message != '\0')
		{
		  ++message;
		}
	      if (*message == '\x01')
		{
		  ++message;
		}
	    }
	  else
	    {
	      throw std::runtime_error("parse key error");
	    }
	}
    }
    std::cout << arr.size() << std::endl;
    for (const auto &field : arr)
      {
	if (field)
	  {
	    std::cout << "field inserted:" << field << std::endl;
	  }
      }
}
<|endoftext|>


<commit_before>#include <iostream>
#include <math.h>
#include <vector>
#include <random>
#include <functional>

//random generator
std::random_device rd;
std::mt19937 generator(rd());
std::uniform_real_distribution<double> uniform_distr(-1, 1);

int 	population 		= 50;
double	elitism 		= 0.2;
double 	randomBehaviour = 0.2;
double 	mutationRate 	= 0.1;
double 	mutationRange 	= 0.5;

double Sigmoid(double in)
{
	return  1.0/(1.0 + exp(-in));
}

struct Neuron
{
	std::vector<double> weights;
	double value;

	void Populate(int nInputs)
	{
		for(int i=0; i<nInputs; i++)
		{
			weights.push_back(uniform_distr(generator));
		}
	}

	Neuron(){}
	Neuron(int nInputs)
	{
		Populate(nInputs);
	}

};

struct Layer
{
	int index;
	std::vector<Neuron> neurons;

	void Populate(int nNeurons, int nInputs)
	{
		for(int i=0; i < nNeurons; i++)
		{
			Neuron newNeuron;
			newNeuron.Populate(nInputs);

			neurons.push_back(newNeuron);
		}
	}

	Layer(){}
	Layer(int nNeurons, int nInputs)
	{
		Populate(nNeurons,nInputs);
	}
	Layer(int ind, int nNeurons, int nInputs)
	{
		index = ind;
		Populate(nNeurons,nInputs);
	}
};

struct Network
{
	std::vector<Layer> layers;

	void perceptronGeneration(int nInputs, std::vector<int> nHiddens, int nOutputs)
	{
		int previousNeurons = 0;
		int ind = 0;

		Layer firstLayer(ind, nInputs, previousNeurons);
		layers.push_back(firstLayer);

		ind++;
		previousNeurons = nInputs;

		//for(int i=0; i<nHiddens.size(); i++)
		for(auto nHidden : nHiddens)
		{
			Layer Hlayer(ind, nHidden, previousNeurons);
			previousNeurons = nHidden;
			layers.push_back(Hlayer);
			ind++;
		}

		Layer lastLayer(ind, nOutputs, previousNeurons);
		layers.push_back(lastLayer);
	}

	std::vector<double> FeedForward(std::vector<double> Inputs)
	{
		for(int i=0; i<Inputs.size(); i++)
			layers[0].neurons[i].value = Inputs[i];

		Layer previousLayer = layers[0];

		for(int i=1; i<layers.size(); i++)
		{
			//for(auto currentNeuron : layers[i].neurons)
			for(int j=0; j<layers[i].neurons.size(); j++)
			{
				double sum = 0;
				//for(auto previousNeuron : previousLayer.neurons)
				for(int k=0; k<previousLayer.neurons.size(); k++)
				{
					sum += previousLayer.neurons[k].value*layers[i].neurons[j].weights[k];
				}
				layers[i].neurons[j].value = Sigmoid(sum);
			}

			previousLayer = layers[i];
		}

		std::vector<double> output;

		Layer lastLayer = layers.back();
		for(auto neuron : lastLayer.neurons)
			output.push_back(neuron.value);

		return output;
	}

	void print()
	{
		std::cout << "hello world, i am a neural network and my layers are = " << std::endl;
		for(auto l : layers)
		{
			//skip input layer that has no weights
			if(l.index == 0) continue;

			std::cout << "hello world, i am layer number " << l.index << " and my neurons are = " << std::endl;
			int j=0;
			for(auto n : l.neurons)
			{
				std::cout << "hello world, i am neuron number " << j << " and my weights are = " << std::endl;
				j++;
				for(auto w : n.weights)
					std::cout << w << std::endl;
			}
		}
	}

	Network(){}
	Network(int nInputs, std::vector<int> nHiddens, int nOutputs)
	{
		perceptronGeneration(nInputs, nHiddens, nOutputs);
	}
};

struct Genome
{
	Network network;
	double score;

	Genome(){}
	Genome(Network n, double s) : network(n), score(s) {}
};

struct Generation
{
	std::vector<Genome> networks;

	void addGenome(){} //TODO add genome and sort score

	Genome breed(Genome g1, Genome g2)
	{
		Genome child = g1;

		for(int i=0; i<g2.network.layers.size(); i++)
			for(int j=0; j<g2.network.layers[i].neurons.size(); j++)
				for(int k=0; k<g2.network.layers[i].neurons[j].weights.size(); k++)
				{
					double r = uniform_distr(generator);
					//std::cout << r << std::endl;

					if(r < 0.5)
						child.network.layers[i].neurons[j].weights[k] = g2.network.layers[i].neurons[j].weights[k];

					r = uniform_distr(generator);
					if(r < mutationRate)
						child.network.layers[i].neurons[j].weights[k] = uniform_distr(generator)*mutationRange*2.0 - mutationRange;

				}

		return child;
	}

	Generation(){}
};

int main()
{
	Network n1(2,{2},2);
	Network n2(2,{2},2);

	//n1.print();
	//n2.print();

	Genome g1(n1,0), g2(n2,0);

	g1.network.print();
	g2.network.print();

	Generation X;

	auto xman = X.breed(g1,g2);

	xman.network.print();

	/*
	Neuron neuron;
	neuron.Populate(2);

	for(auto weight : neuron.weights)
		std::cout << "hello world, i am a neuron and my weights are = " << weight << std::endl;

	Neuron anotherNeuron;
	anotherNeuron.Populate(2);

	for(auto weight : anotherNeuron.weights)
		std::cout << "hello world, i am a another neuron and my weight is = " << weight << std::endl;

	std::cout << std::endl;

	Layer layer(0,5,2);
	//layer.Populate(5,2);

	std::cout << "hello world, i am a layer " << layer.index << " and my neurons are = " << std::endl;

	int j = 0;
	for(auto n : layer.neurons)
	{
		std::cout << "hello world, i am neuron number " << j << " and my weights are = " << std::endl;
		j++;
		for(auto w : n.weights)
			std::cout << w << std::endl;
	}
	j=0;

	std::cout << std::endl;

	std::vector<int> nHiddens = {3};
	Network network(3,nHiddens,3);

	std::cout << "hello world, i am a neural network and my layers are = " << std::endl;

	std::cout << std::endl;

	std::vector<double> input = {1,1,1};
	std::cout << "here is my list of inputs = " << std::endl;
	for(auto in : input) std::cout << in << std::endl;

	auto output = network.FeedForward(input);

	std::cout << "and here is my result = " << std::endl;
	for(auto out : output) std::cout << out << std::endl;
	*/
	return 0;
}<commit_msg>xor example<commit_after>#include <iostream>
#include <math.h>
#include <vector>
#include <random>
#include <algorithm>    // std::sort
#include <fstream>

//random generator
std::random_device rd;
std::mt19937 generator(rd());
std::uniform_real_distribution<double> uniform_distr(-1, 1);

#define population 		 50
#define	elitism 		 0.2
#define randomBehaviour  0.2
#define mutationRate 	 0.1
#define mutationRange 	 0.2

double Sigmoid(double in)
{
	return  1.0/(1.0 + exp(-in));
}

struct Neuron
{
	std::vector<double> weights;
	double value;

	void Populate(int nInputs)
	{
		for(int i=0; i<nInputs; i++)
		{
			weights.push_back(uniform_distr(generator));
		}
	}

	Neuron(){}
	Neuron(int nInputs)
	{
		Populate(nInputs);
	}

};

struct Layer
{
	int index;
	std::vector<Neuron> neurons;

	void Populate(int nNeurons, int nInputs)
	{
		for(int i=0; i < nNeurons; i++)
		{
			Neuron newNeuron;
			newNeuron.Populate(nInputs);

			neurons.push_back(newNeuron);
		}
	}

	Layer(){}
	Layer(int nNeurons, int nInputs)
	{
		Populate(nNeurons,nInputs);
	}
	Layer(int ind, int nNeurons, int nInputs)
	{
		index = ind;
		Populate(nNeurons,nInputs);
	}
};

struct Network
{
	std::vector<Layer> layers;

	void perceptronGeneration(int nInputs, std::vector<int> nHiddens, int nOutputs)
	{
		int previousNeurons = 0;
		int ind = 0;

		Layer firstLayer(ind, nInputs, previousNeurons);
		layers.push_back(firstLayer);

		ind++;
		previousNeurons = nInputs;

		//for(int i=0; i<nHiddens.size(); i++)
		for(auto nHidden : nHiddens)
		{
			Layer Hlayer(ind, nHidden, previousNeurons);
			previousNeurons = nHidden;
			layers.push_back(Hlayer);
			ind++;
		}

		Layer lastLayer(ind, nOutputs, previousNeurons);
		layers.push_back(lastLayer);
	}

	std::vector<double> FeedForward(std::vector<double> Inputs)
	{
		for(int i=0; i<Inputs.size(); i++)
			layers[0].neurons[i].value = Inputs[i];

		Layer previousLayer = layers[0];

		for(int i=1; i<layers.size(); i++)
		{
			//for(auto currentNeuron : layers[i].neurons)
			for(int j=0; j<layers[i].neurons.size(); j++)
			{
				double sum = 0;
				//for(auto previousNeuron : previousLayer.neurons)
				for(int k=0; k<previousLayer.neurons.size(); k++)
				{
					sum += previousLayer.neurons[k].value*layers[i].neurons[j].weights[k];
				}
				layers[i].neurons[j].value = Sigmoid(sum);
			}

			previousLayer = layers[i];
		}

		std::vector<double> output;

		Layer lastLayer = layers.back();
		for(auto neuron : lastLayer.neurons)
			output.push_back(neuron.value);

		return output;
	}

	void Randomize()
	{
		for(auto &l : layers)
		{
			//skip input layer that has no weights
			if(l.index == 0) continue;

			for(auto &n : l.neurons)
				for(auto &w : n.weights)
					w = uniform_distr(generator);
		}
	}

	void print()
	{
		std::cout << "hello world, i am a neural network and my layers are = " << std::endl;
		for(auto l : layers)
		{
			//skip input layer that has no weights
			if(l.index == 0) continue;

			std::cout << "hello world, i am layer number " << l.index << " and my neurons are = " << std::endl;
			int j=0;
			for(auto n : l.neurons)
			{
				std::cout << "hello world, i am neuron number " << j << " and my weights are = " << std::endl;
				j++;
				for(auto w : n.weights)
					std::cout << w << std::endl;
			}
		}
	}

	Network(){}
	Network(int nInputs, std::vector<int> nHiddens, int nOutputs)
	{
		perceptronGeneration(nInputs, nHiddens, nOutputs);
	}
};

struct Genome
{
	Network network;
	double score;

	//to sort a vector of genomes
	bool operator < (const Genome& g) const
	{
		return (score < g.score);
	}

	Genome(){}
	Genome(Network n, double s) : network(n), score(s) {}
};

struct Generation
{
	std::vector<Genome> genomes;

	//void addGenome(){} //TODO add genome and sort score

	Genome breed(Genome g1, Genome g2)
	{
		Genome child = g1;

		for(int i=0; i<g2.network.layers.size(); i++)
			for(int j=0; j<g2.network.layers[i].neurons.size(); j++)
				for(int k=0; k<g2.network.layers[i].neurons[j].weights.size(); k++)
				{
					double r = uniform_distr(generator);
					//std::cout << r << std::endl;

					if(r < 0.5)
						child.network.layers[i].neurons[j].weights[k] = g2.network.layers[i].neurons[j].weights[k];

					r = uniform_distr(generator);
					if(r < mutationRate)
						child.network.layers[i].neurons[j].weights[k] = uniform_distr(generator)*mutationRange*2.0 - mutationRange;

				}

		return child;
	}

	void nextGeneration()
	{
		std::vector<Genome> nextG;

		for (int i=0; i < floor(elitism*population); i++)
			nextG.push_back(genomes[i]);

		for (int i=0; i < floor(randomBehaviour*population); i++)
		{
			Genome g = genomes[0];
			g.network.Randomize();

			nextG.push_back(g);
		}

		int max = 0;
		while(nextG.size() < genomes.size())
		{
			for(int i=0; i<max; i++)
				nextG.push_back(breed(genomes[i],genomes[max]));

			max++;
			if(max >= genomes.size()) max = 0;
		}

		//reset scores
		for(auto &genome : nextG)
		{
			genome.score = 0;
		}

		genomes = nextG;
	}

	void Sort()
	{
		std::sort(genomes.begin(), genomes.end());
		std::reverse(genomes.begin(),genomes.end());
	}

	double avgScore()
	{
		double avg = 0;
		for(auto &genome : genomes)
			avg += genome.score;
		return avg/population;
	}

	Generation(){}
	Generation(int nInputs, std::vector<int> nHiddens, int nOutputs)
	{
		for (int i=0; i < population; i++)
		{
			Network n(nInputs,nHiddens,nOutputs);
			Genome g(n,0);
			genomes.push_back(g);
		}
	}
};

int main()
{
	//XOR TEST
	Generation X(2,{3},1);

	std::vector<std::vector<double>> dataset = {{1,0},{1,1},{0,1},{0,0}};

	std::vector<double> truth = {1,0,1,0};

	int count = 0;
	std::vector<double> avgscore;

	while(1)
	{
		count++;
		for(auto &genome : X.genomes)
		{
			std::vector<double> output;
			for(auto input : dataset)
			{
				auto c = genome.network.FeedForward(input);
				output.push_back(c[0]>0.5);
			}

			for(int i=0; i<4; i++)
				if(output[i] == truth[i]) genome.score++;
		}

		X.Sort();

		if(!(count%100))
		{
			avgscore.push_back(X.avgScore());
		}

		if(X.genomes[0].score == 4) break;

		X.nextGeneration();
	}

	std::cout << "number of generations = " << count << std::endl;

	/*
	std::ofstream output;
	output.open("scores.txt");

	for(int i=0; i<avgscore.size(); i++)
	{
		output << i << "\t" << avgscore[i] << std::endl;
	}

	output.close();
	*/

	return 0;
}<|endoftext|>


<commit_before>24c32be1-2748-11e6-bd1d-e0f84713e7b8<commit_msg>Introduced random NullPointerException bug<commit_after>24d10059-2748-11e6-b74f-e0f84713e7b8<|endoftext|>


<commit_before>4c45777a-ad5c-11e7-aad9-ac87a332f658<commit_msg>NO CHANGES<commit_after>4cc2ead7-ad5c-11e7-8a32-ac87a332f658<|endoftext|>


<commit_before>#ifndef ALGORITHM_HPP
# define ALGORUTHM_HPP
# pragma once

#include <cstddef>

#include <type_traits>

#include <utility>

#include "meta.hpp"

namespace generic
{

// min, max
template <typename T>
constexpr inline T const& max(T const& a, T const& b) noexcept
{
  return a > b ? a : b;
}

template <typename T, typename ...A>
constexpr inline typename ::std::enable_if<
  bool(sizeof...(A)) &&
  all_of<
    ::std::is_same<
      typename ::std::decay<T>::type,
      typename ::std::decay<A>::type
    >...
  >{},
  T
>::type
max(T const a, T const b, A&& ...args) noexcept
{
  return a > b ?
    max(a, ::std::forward<A>(args)...) :
    max(b, ::std::forward<A>(args)...);
}

template <typename T>
constexpr inline T const& min(T const& a, T const& b) noexcept
{
  return a < b ? a : b;
}

template <typename T, typename ...A>
constexpr inline typename ::std::enable_if<
  bool(sizeof...(A)) &&
  all_of<
    ::std::is_same<
      typename ::std::decay<T>::type,
      typename ::std::decay<A>::type
    >...
  >{},
  T
>::type
min(T const a, T const b, A&& ...args) noexcept
{
  return a < b ?
    min(a, ::std::forward<A>(args)...) :
    min(b, ::std::forward<A>(args)...);
}

template <typename ...A>
constexpr inline typename ::std::enable_if<
  bool(sizeof...(A)) &&
  all_of<
    ::std::is_same<
      typename ::std::decay<typename front<A...>::type>::type,
      typename ::std::decay<A>::type
    >...
  >{},
  ::std::pair<
    typename ::std::decay<typename front<A...>::type>::type,
    typename ::std::decay<typename front<A...>::type>::type
  >
>::type
minmax(A&& ...args) noexcept
{
  return {
    min(::std::forward<A>(args)...),
    max(::std::forward<A>(args)...)
  };
}

}

#endif // ALGORITHM_HPP
<commit_msg>some fixes<commit_after>#ifndef ALGORITHM_HPP
# define ALGORUTHM_HPP
# pragma once

#include <cstddef>

#include <type_traits>

#include <utility>

#include "meta.hpp"

namespace generic
{

// min, max
template <typename T>
constexpr inline T const& max(T const& a, T const& b) noexcept
{
  return a > b ? a : b;
}

template <typename T>
constexpr inline T const& min(T const& a, T const& b) noexcept
{
  return a < b ? a : b;
}

template <typename T, typename ...A>
constexpr inline typename ::std::enable_if<
  bool(sizeof...(A)) &&
  all_of<
    ::std::is_same<
      typename ::std::decay<T>::type,
      typename ::std::decay<A>::type
    >...
  >{},
  T
>::type
max(T const& a, T const& b, A&& ...args) noexcept
{
  return a > b ?
    max(a, ::std::forward<A>(args)...) :
    max(b, ::std::forward<A>(args)...);
}

template <typename T, typename ...A>
constexpr inline typename ::std::enable_if<
  bool(sizeof...(A)) &&
  all_of<
    ::std::is_same<
      typename ::std::decay<T>::type,
      typename ::std::decay<A>::type
    >...
  >{},
  T
>::type
min(T const& a, T const& b, A&& ...args) noexcept
{
  return a < b ?
    min(a, ::std::forward<A>(args)...) :
    min(b, ::std::forward<A>(args)...);
}

template <typename ...A>
constexpr inline typename ::std::enable_if<
  bool(sizeof...(A)) &&
  all_of<
    ::std::is_same<
      typename ::std::decay<typename front<A...>::type>::type,
      typename ::std::decay<A>::type
    >...
  >{},
  ::std::pair<
    typename ::std::decay<typename front<A...>::type>::type,
    typename ::std::decay<typename front<A...>::type>::type
  >
>::type
minmax(A&& ...args) noexcept
{
  return {
    min(::std::forward<A>(args)...),
    max(::std::forward<A>(args)...)
  };
}

}

#endif // ALGORITHM_HPP
<|endoftext|>


<commit_before>5310ae17-ad58-11e7-9d66-ac87a332f658<commit_msg>Made changes so it will hopefully compile by the next commit<commit_after>537b637a-ad58-11e7-8690-ac87a332f658<|endoftext|>