<commit_before>/* -*- mode: c++; c-basic-offset:4 -*-
    test_keylistmodels.cpp

    This file is part of Kleopatra's test suite.
    Copyright (c) 2007 Klarälvdalens Datakonsult AB

    Kleopatra is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    Kleopatra 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 <models/keylistmodel.h>
#include <models/keylistsortfilterproxymodel.h>

#include <kapplication.h>
#include <kaboutdata.h>
#include <kcmdlineargs.h>

#include <QTreeView>
#include <QLineEdit>
#include <QLayout>
#include <QTimer>
#include <QEventLoop>
#include <QDateTime>
#include <QDebug>

#include <qgpgme/eventloopinteractor.h>

#include <gpgme++/context.h>
#include <gpgme++/error.h>
#include <gpgme++/key.h>

#include <memory>
#include <vector>
#include <string>
#include <cassert>

class Relay : public QObject {
    Q_OBJECT
public:
    explicit Relay( QObject * p=0 ) : QObject( p ) {}

public Q_SLOTS:
    void slotNextKeyEvent( GpgME::Context *, const GpgME::Key & key ) {
        qDebug( "next key" );
        mKeys.push_back( key );
        // push out keys in chunks of 1..16 keys
        if ( mKeys.size() > qrand() % 16U ) {
            emit nextKeys( mKeys );
            mKeys.clear();
        }
    }

    void slotOperationDoneEvent( GpgME::Context* , const GpgME::Error& error ) {
        qDebug( "listing done error: %d", static_cast<int>( error ) );
    }

Q_SIGNALS:
    void nextKeys( const std::vector<GpgME::Key> & keys );

private:
    std::vector<GpgME::Key> mKeys;
};

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

    KAboutData aboutData( "test_flatkeylistmodel", 0, ki18n("FlatKeyListModel Test"), "0.2" );
    KCmdLineArgs::init( argc, argv, &aboutData );

    KCmdLineOptions options;
    options.add( "flat",         ki18n("Perform flat key listing") );
    options.add( "hierarchical", ki18n("Perform hierarchical key listing") );
    options.add( "disable-smime", ki18n("Do not list SMIME keys") );

    KCmdLineArgs::addCmdLineOptions( options );

    KApplication app;

    KCmdLineArgs * args = KCmdLineArgs::parsedArgs();

    const bool showFlat = args->isSet( "flat" ) || !args->isSet( "hierarchical" );
   const bool showHier = args->isSet( "hierarchical" ) || !args->isSet( "flat" );
    const bool disablesmime = args->isSet( "disable-smime" );

    qsrand( QDateTime::currentDateTime().toTime_t() );

    QWidget flatWidget, hierarchicalWidget;
    QVBoxLayout flatLay( &flatWidget ), hierarchicalLay( &hierarchicalWidget );
    QLineEdit flatLE( &flatWidget ), hierarchicalLE( &hierarchicalWidget );
    QTreeView flat( &flatWidget ), hierarchical( &hierarchicalWidget );

    flat.setSortingEnabled( true );
    flat.sortByColumn( Kleo::AbstractKeyListModel::Fingerprint, Qt::AscendingOrder );
    hierarchical.setSortingEnabled( true );
    hierarchical.sortByColumn( Kleo::AbstractKeyListModel::Fingerprint, Qt::AscendingOrder );

    flatLay.addWidget( &flatLE );
    flatLay.addWidget( &flat );

    hierarchicalLay.addWidget( &hierarchicalLE );
    hierarchicalLay.addWidget( &hierarchical );

    flatWidget.setWindowTitle( QLatin1String( "Flat Key Listing" ) );
    hierarchicalWidget.setWindowTitle( QLatin1String( "Hierarchical Key Listing" ) );

    Kleo::KeyListSortFilterProxyModel flatProxy, hierarchicalProxy;

    QObject::connect( &flatLE, SIGNAL(textChanged(QString)), &flatProxy, SLOT(setFilterFixedString(QString)) );
    QObject::connect( &hierarchicalLE, SIGNAL(textChanged(QString)), &hierarchicalProxy, SLOT(setFilterFixedString(QString)) );

    Relay relay;
    QObject::connect( QGpgME::EventLoopInteractor::instance(), SIGNAL(nextKeyEventSignal(GpgME::Context*,GpgME::Key)),
                      &relay, SLOT(slotNextKeyEvent(GpgME::Context*,GpgME::Key)) );
    QObject::connect( QGpgME::EventLoopInteractor::instance(), SIGNAL(operationDoneEventSignal(GpgME::Context*,GpgME::Error)),
                      &relay, SLOT(slotOperationDoneEvent(GpgME::Context*,GpgME::Error)) );

    if ( showFlat )
        if ( Kleo::AbstractKeyListModel * const model = Kleo::AbstractKeyListModel::createFlatKeyListModel( &flat ) ) {
            QObject::connect( &relay, SIGNAL(nextKeys(std::vector<GpgME::Key>)), model, SLOT(addKeys(std::vector<GpgME::Key>)) );
            flatProxy.setSourceModel( model );
            flat.setModel( &flatProxy );

            flatWidget.show();
        }

    if ( showHier )
        if ( Kleo::AbstractKeyListModel * const model = Kleo::AbstractKeyListModel::createHierarchicalKeyListModel( &hierarchical ) ) {
            QObject::connect( &relay, SIGNAL(nextKeys(std::vector<GpgME::Key>)), model, SLOT(addKeys(std::vector<GpgME::Key>)) );
            hierarchicalProxy.setSourceModel( model );
            hierarchical.setModel( &hierarchicalProxy );

            hierarchicalWidget.show();
        }

    const std::auto_ptr<GpgME::Context> pgp( GpgME::Context::createForProtocol( GpgME::OpenPGP ) );
    pgp->setManagedByEventLoopInteractor( true );
    pgp->setKeyListMode( GpgME::Local );

    if ( const GpgME::Error e = pgp->startKeyListing() )
        qDebug() << "pgp->startKeyListing() ->" << e.asString();

    if ( !disablesmime ) {
        const std::auto_ptr<GpgME::Context> cms( GpgME::Context::createForProtocol( GpgME::CMS ) );
        cms->setManagedByEventLoopInteractor( true );
        cms->setKeyListMode( GpgME::Local );

        if ( const GpgME::Error e = cms->startKeyListing() )
            qDebug() << "cms" << e.asString();

       QEventLoop loop;
       QTimer::singleShot( 2000, &loop, SLOT(quit()) );
       loop.exec();

       const std::auto_ptr<GpgME::Context> cms2( GpgME::Context::createForProtocol( GpgME::CMS ) );
       cms2->setManagedByEventLoopInteractor( true );
       cms2->setKeyListMode( GpgME::Local );

       if ( const GpgME::Error e = cms2->startKeyListing() )
          qDebug() << "cms2" << e.asString();
    }

    return app.exec();
}

#include "test_flatkeylistmodel.moc"
<commit_msg>update for the API change in GpgMe::Error<commit_after>/* -*- mode: c++; c-basic-offset:4 -*-
    test_keylistmodels.cpp

    This file is part of Kleopatra's test suite.
    Copyright (c) 2007 Klarälvdalens Datakonsult AB

    Kleopatra is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    Kleopatra 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 <models/keylistmodel.h>
#include <models/keylistsortfilterproxymodel.h>

#include <kapplication.h>
#include <kaboutdata.h>
#include <kcmdlineargs.h>

#include <QTreeView>
#include <QLineEdit>
#include <QLayout>
#include <QTimer>
#include <QEventLoop>
#include <QDateTime>
#include <QDebug>

#include <qgpgme/eventloopinteractor.h>

#include <gpgme++/context.h>
#include <gpgme++/error.h>
#include <gpgme++/key.h>

#include <memory>
#include <vector>
#include <string>
#include <cassert>

class Relay : public QObject {
    Q_OBJECT
public:
    explicit Relay( QObject * p=0 ) : QObject( p ) {}

public Q_SLOTS:
    void slotNextKeyEvent( GpgME::Context *, const GpgME::Key & key ) {
        qDebug( "next key" );
        mKeys.push_back( key );
        // push out keys in chunks of 1..16 keys
        if ( mKeys.size() > qrand() % 16U ) {
            emit nextKeys( mKeys );
            mKeys.clear();
        }
    }

    void slotOperationDoneEvent( GpgME::Context* , const GpgME::Error& error ) {
        qDebug( "listing done error: %d", error.encodedError() );
    }

Q_SIGNALS:
    void nextKeys( const std::vector<GpgME::Key> & keys );

private:
    std::vector<GpgME::Key> mKeys;
};

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

    KAboutData aboutData( "test_flatkeylistmodel", 0, ki18n("FlatKeyListModel Test"), "0.2" );
    KCmdLineArgs::init( argc, argv, &aboutData );

    KCmdLineOptions options;
    options.add( "flat",         ki18n("Perform flat key listing") );
    options.add( "hierarchical", ki18n("Perform hierarchical key listing") );
    options.add( "disable-smime", ki18n("Do not list SMIME keys") );

    KCmdLineArgs::addCmdLineOptions( options );

    KApplication app;

    KCmdLineArgs * args = KCmdLineArgs::parsedArgs();

    const bool showFlat = args->isSet( "flat" ) || !args->isSet( "hierarchical" );
   const bool showHier = args->isSet( "hierarchical" ) || !args->isSet( "flat" );
    const bool disablesmime = args->isSet( "disable-smime" );

    qsrand( QDateTime::currentDateTime().toTime_t() );

    QWidget flatWidget, hierarchicalWidget;
    QVBoxLayout flatLay( &flatWidget ), hierarchicalLay( &hierarchicalWidget );
    QLineEdit flatLE( &flatWidget ), hierarchicalLE( &hierarchicalWidget );
    QTreeView flat( &flatWidget ), hierarchical( &hierarchicalWidget );

    flat.setSortingEnabled( true );
    flat.sortByColumn( Kleo::AbstractKeyListModel::Fingerprint, Qt::AscendingOrder );
    hierarchical.setSortingEnabled( true );
    hierarchical.sortByColumn( Kleo::AbstractKeyListModel::Fingerprint, Qt::AscendingOrder );

    flatLay.addWidget( &flatLE );
    flatLay.addWidget( &flat );

    hierarchicalLay.addWidget( &hierarchicalLE );
    hierarchicalLay.addWidget( &hierarchical );

    flatWidget.setWindowTitle( QLatin1String( "Flat Key Listing" ) );
    hierarchicalWidget.setWindowTitle( QLatin1String( "Hierarchical Key Listing" ) );

    Kleo::KeyListSortFilterProxyModel flatProxy, hierarchicalProxy;

    QObject::connect( &flatLE, SIGNAL(textChanged(QString)), &flatProxy, SLOT(setFilterFixedString(QString)) );
    QObject::connect( &hierarchicalLE, SIGNAL(textChanged(QString)), &hierarchicalProxy, SLOT(setFilterFixedString(QString)) );

    Relay relay;
    QObject::connect( QGpgME::EventLoopInteractor::instance(), SIGNAL(nextKeyEventSignal(GpgME::Context*,GpgME::Key)),
                      &relay, SLOT(slotNextKeyEvent(GpgME::Context*,GpgME::Key)) );
    QObject::connect( QGpgME::EventLoopInteractor::instance(), SIGNAL(operationDoneEventSignal(GpgME::Context*,GpgME::Error)),
                      &relay, SLOT(slotOperationDoneEvent(GpgME::Context*,GpgME::Error)) );

    if ( showFlat )
        if ( Kleo::AbstractKeyListModel * const model = Kleo::AbstractKeyListModel::createFlatKeyListModel( &flat ) ) {
            QObject::connect( &relay, SIGNAL(nextKeys(std::vector<GpgME::Key>)), model, SLOT(addKeys(std::vector<GpgME::Key>)) );
            flatProxy.setSourceModel( model );
            flat.setModel( &flatProxy );

            flatWidget.show();
        }

    if ( showHier )
        if ( Kleo::AbstractKeyListModel * const model = Kleo::AbstractKeyListModel::createHierarchicalKeyListModel( &hierarchical ) ) {
            QObject::connect( &relay, SIGNAL(nextKeys(std::vector<GpgME::Key>)), model, SLOT(addKeys(std::vector<GpgME::Key>)) );
            hierarchicalProxy.setSourceModel( model );
            hierarchical.setModel( &hierarchicalProxy );

            hierarchicalWidget.show();
        }

    const std::auto_ptr<GpgME::Context> pgp( GpgME::Context::createForProtocol( GpgME::OpenPGP ) );
    pgp->setManagedByEventLoopInteractor( true );
    pgp->setKeyListMode( GpgME::Local );

    if ( const GpgME::Error e = pgp->startKeyListing() )
        qDebug() << "pgp->startKeyListing() ->" << e.asString();

    if ( !disablesmime ) {
        const std::auto_ptr<GpgME::Context> cms( GpgME::Context::createForProtocol( GpgME::CMS ) );
        cms->setManagedByEventLoopInteractor( true );
        cms->setKeyListMode( GpgME::Local );

        if ( const GpgME::Error e = cms->startKeyListing() )
            qDebug() << "cms" << e.asString();

       QEventLoop loop;
       QTimer::singleShot( 2000, &loop, SLOT(quit()) );
       loop.exec();

       const std::auto_ptr<GpgME::Context> cms2( GpgME::Context::createForProtocol( GpgME::CMS ) );
       cms2->setManagedByEventLoopInteractor( true );
       cms2->setKeyListMode( GpgME::Local );

       if ( const GpgME::Error e = cms2->startKeyListing() )
          qDebug() << "cms2" << e.asString();
    }

    return app.exec();
}

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


<commit_before>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software;  you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/

#include <string>
#include <vector>
#include "bzfio.h"
#include "common.h"
#include "TextUtils.h"
#include <vector>

#include "commands.h"
#include "bzfsAPI.h"

typedef struct
{
	std::string plugin;

#ifdef _WIN32
	HINSTANCE	handle;
#else
	void*		handle;
#endif
}trPluginRecord;

std::vector<trPluginRecord>	vPluginList;

void unload1Plugin ( int iPluginID );

#ifdef _WIN32
#include <windows.h>

int getPluginVersion ( HINSTANCE hLib )
{
	int (*lpProc)(void);
	lpProc = (int (__cdecl *)(void))GetProcAddress(hLib, "bz_GetVersion");
	if (lpProc)
		return lpProc();
	return 0;
}

void loadPlugin ( std::string plugin, std::string config )
{
	int (*lpProc)(const char*);

	HINSTANCE	hLib = LoadLibrary(plugin.c_str());
	if (hLib)
	{
		if (getPluginVersion(hLib) < BZ_API_VERSION)
		{
			DEBUG1("Plugin:%s found but expects an older API version (%d), upgrade it\n",plugin.c_str(),getPluginVersion(hLib));
			FreeLibrary(hLib);
		}
		else
		{
			lpProc = (int (__cdecl *)(const char*))GetProcAddress(hLib, "bz_Load");
			if (lpProc)
			{
				int ret =lpProc(config.c_str());
				DEBUG1("Plugin:%s loaded\n",plugin.c_str());

				trPluginRecord pluginRecord;
				pluginRecord.handle = hLib;
				pluginRecord.plugin = plugin;
				vPluginList.push_back(pluginRecord);
			}
			else
			{
				DEBUG1("Plugin:%s found but does not contain bz_Load method\n",plugin.c_str());
				FreeLibrary(hLib);
			}
		}
	}
	else
		DEBUG1("Plugin:%s not found\n",plugin.c_str());
}

void unload1Plugin ( int iPluginID )
{
	int (*lpProc)(void);

	trPluginRecord &plugin = vPluginList[iPluginID];

	lpProc = (int (__cdecl *)(void))GetProcAddress(plugin.handle, "bz_Unload");
	if (lpProc)
		int ret =lpProc();
	else
		DEBUG1("Plugin does not contain bz_UnLoad method\n");

	FreeLibrary(plugin.handle);
	plugin.handle = NULL;
}
#else

#include <dlfcn.h>
std::vector<void*>	vLibHandles;

int getPluginVersion ( void* hLib )
{
	int (*lpProc)(void);
	*(void**) &lpProc = dlsym(hLib,"bz_GetVersion");
	if (lpProc)
		return (*lpProc)();
	return 0;
}

void loadPlugin ( std::string plugin, std::string config )
{
	int (*lpProc)(const char*);

	void*	hLib = dlopen(plugin.c_str(),RTLD_LAZY);
	if (hLib)
	{
		if (getPluginVersion(hLib) < BZ_API_VERSION)
		{
			DEBUG1("Plugin:%s found but expects an older API version (%d), upgrade it\n",plugin.c_str(),getPluginVersion(hLib));
			dlclose(hLib);
		}
		else
		{
			*(void**) &lpProc = dlsym(hLib,"bz_Load");
			if (lpProc)
			{
				(*lpProc)(config.c_str());
				DEBUG1("Plugin:%s loaded\n",plugin.c_str());
				trPluginRecord pluginRecord;
				pluginRecord.handle = hLib;
				pluginRecord.plugin = plugin;
				vPluginList.push_back(pluginRecord);
			}
			else
			{
				DEBUG1("Plugin:%s found but does not contain bz_Load method, error %s\n",plugin.c_str(),dlerror());
				dlclose(hLib);
			}
		}
	}
	else
		DEBUG1("Plugin:%s not found, error %s\n",plugin.c_str(), dlerror());
}

void unload1Plugin ( int iPluginID )
{
	int (*lpProc)(void);
	trPluginRecord &plugin = vPluginList[iPluginID];

	*(void**) &lpProc = dlsym(plugin.handle, "bz_Unload");
	if (lpProc)
		(*lpProc)();
	else
		DEBUG1("Plugin does not contain bz_UnLoad method, error %s\n",dlerror());

	dlclose(plugin.handle);
	plugin.handle = NULL;
}
#endif

void unloadPlugin ( std::string plugin )
{
	// unload the first one of the name we find
	for (unsigned int i = 0; i < vPluginList.size();i++)
	{
		if ( vPluginList[i].plugin == plugin )
		{
			unload1Plugin(i);
			vPluginList.erase(vPluginList.begin()+i);
			return;
		}
	}
}

void unloadPlugins ( void )
{
	for (unsigned int i = 0; i < vPluginList.size();i++)
		unload1Plugin(i);
	vPluginList.clear();

	removeCustomSlashCommand("loadplugin");
	removeCustomSlashCommand("unloadplugin");
	removeCustomSlashCommand("listplugins");
}

std::vector<std::string> getPluginList ( void )
{
	std::vector<std::string> plugins;
	for (unsigned int i = 0; i < vPluginList.size();i++)
		plugins.push_back(vPluginList[i].plugin);

	return plugins;
}

void parseServerCommand(const char *message, int dstPlayerId);

class DynamicPluginCommands : public CustomSlashCommandHandler
{
public:
	virtual ~DynamicPluginCommands(){};
	virtual bool handle ( int playerID, std::string command, std::string message )
	{
		bz_PlayerRecord	record;

		bz_getPlayerByIndex(playerID,&record);

		if ( !record.admin )
		{
			bz_sendTextMessage(BZ_SERVER,playerID,"Permision denied: ADMIN");
			return true;
		}

		if ( !message.size() )
		{
			bz_sendTextMessage(BZ_SERVER,playerID,"Error: Command must have a plugin name");
			return true;
		}

		if ( TextUtils::tolower(command) == "loadplugin" )
		{
			std::vector<std::string> params = TextUtils::tokenize(message,std::string(","));

			std::string config;
			if ( params.size() >1)
				config = params[1];

			loadPlugin(params[0],config);

			bz_sendTextMessage(BZ_SERVER,playerID,"Plug-in loaded");
			return true;
		}

		if ( TextUtils::tolower(command) == "unloadplugin" )
		{
			unloadPlugin(message);

			bz_sendTextMessage(BZ_SERVER,playerID,"Plug-in unloaded");
			return true;
		}

		if ( TextUtils::tolower(command) == "listplugins" )
		{
			std::vector<std::string>	plugins = getPluginList();

			if (!plugins.size())
				bz_sendTextMessage(BZ_SERVER,playerID,"No Plug-ins loaded;");
			else
			{
				bz_sendTextMessage(BZ_SERVER,playerID,"Plug-isn loaded;");

				for ( unsigned int i = 0; i < plugins.size(); i++)
					bz_sendTextMessage(BZ_SERVER,playerID,plugins[i].c_str());
			}
			return true;
		}
		return true;
	}
};

DynamicPluginCommands	command;

void initPlugins ( void )
{
	registerCustomSlashCommand("loadplugin",&command);
	registerCustomSlashCommand("unloadplugin",&command);
	registerCustomSlashCommand("listplugins",&command);
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>Unused vars warning<commit_after>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software;  you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/

#include <string>
#include <vector>
#include "bzfio.h"
#include "common.h"
#include "TextUtils.h"
#include <vector>

#include "commands.h"
#include "bzfsAPI.h"

typedef struct
{
	std::string plugin;

#ifdef _WIN32
	HINSTANCE	handle;
#else
	void*		handle;
#endif
}trPluginRecord;

std::vector<trPluginRecord>	vPluginList;

void unload1Plugin ( int iPluginID );

#ifdef _WIN32
#include <windows.h>

int getPluginVersion ( HINSTANCE hLib )
{
	int (*lpProc)(void);
	lpProc = (int (__cdecl *)(void))GetProcAddress(hLib, "bz_GetVersion");
	if (lpProc)
		return lpProc();
	return 0;
}

void loadPlugin ( std::string plugin, std::string config )
{
	int (*lpProc)(const char*);

	HINSTANCE	hLib = LoadLibrary(plugin.c_str());
	if (hLib)
	{
		if (getPluginVersion(hLib) < BZ_API_VERSION)
		{
			DEBUG1("Plugin:%s found but expects an older API version (%d), upgrade it\n",plugin.c_str(),getPluginVersion(hLib));
			FreeLibrary(hLib);
		}
		else
		{
			lpProc = (int (__cdecl *)(const char*))GetProcAddress(hLib, "bz_Load");
			if (lpProc)
			{
				lpProc(config.c_str());
				DEBUG1("Plugin:%s loaded\n",plugin.c_str());

				trPluginRecord pluginRecord;
				pluginRecord.handle = hLib;
				pluginRecord.plugin = plugin;
				vPluginList.push_back(pluginRecord);
			}
			else
			{
				DEBUG1("Plugin:%s found but does not contain bz_Load method\n",plugin.c_str());
				FreeLibrary(hLib);
			}
		}
	}
	else
		DEBUG1("Plugin:%s not found\n",plugin.c_str());
}

void unload1Plugin ( int iPluginID )
{
	int (*lpProc)(void);

	trPluginRecord &plugin = vPluginList[iPluginID];

	lpProc = (int (__cdecl *)(void))GetProcAddress(plugin.handle, "bz_Unload");
	if (lpProc)
		lpProc();
	else
		DEBUG1("Plugin does not contain bz_UnLoad method\n");

	FreeLibrary(plugin.handle);
	plugin.handle = NULL;
}
#else

#include <dlfcn.h>
std::vector<void*>	vLibHandles;

int getPluginVersion ( void* hLib )
{
	int (*lpProc)(void);
	*(void**) &lpProc = dlsym(hLib,"bz_GetVersion");
	if (lpProc)
		return (*lpProc)();
	return 0;
}

void loadPlugin ( std::string plugin, std::string config )
{
	int (*lpProc)(const char*);

	void*	hLib = dlopen(plugin.c_str(),RTLD_LAZY);
	if (hLib)
	{
		if (getPluginVersion(hLib) < BZ_API_VERSION)
		{
			DEBUG1("Plugin:%s found but expects an older API version (%d), upgrade it\n",plugin.c_str(),getPluginVersion(hLib));
			dlclose(hLib);
		}
		else
		{
			*(void**) &lpProc = dlsym(hLib,"bz_Load");
			if (lpProc)
			{
				(*lpProc)(config.c_str());
				DEBUG1("Plugin:%s loaded\n",plugin.c_str());
				trPluginRecord pluginRecord;
				pluginRecord.handle = hLib;
				pluginRecord.plugin = plugin;
				vPluginList.push_back(pluginRecord);
			}
			else
			{
				DEBUG1("Plugin:%s found but does not contain bz_Load method, error %s\n",plugin.c_str(),dlerror());
				dlclose(hLib);
			}
		}
	}
	else
		DEBUG1("Plugin:%s not found, error %s\n",plugin.c_str(), dlerror());
}

void unload1Plugin ( int iPluginID )
{
	int (*lpProc)(void);
	trPluginRecord &plugin = vPluginList[iPluginID];

	*(void**) &lpProc = dlsym(plugin.handle, "bz_Unload");
	if (lpProc)
		(*lpProc)();
	else
		DEBUG1("Plugin does not contain bz_UnLoad method, error %s\n",dlerror());

	dlclose(plugin.handle);
	plugin.handle = NULL;
}
#endif

void unloadPlugin ( std::string plugin )
{
	// unload the first one of the name we find
	for (unsigned int i = 0; i < vPluginList.size();i++)
	{
		if ( vPluginList[i].plugin == plugin )
		{
			unload1Plugin(i);
			vPluginList.erase(vPluginList.begin()+i);
			return;
		}
	}
}

void unloadPlugins ( void )
{
	for (unsigned int i = 0; i < vPluginList.size();i++)
		unload1Plugin(i);
	vPluginList.clear();

	removeCustomSlashCommand("loadplugin");
	removeCustomSlashCommand("unloadplugin");
	removeCustomSlashCommand("listplugins");
}

std::vector<std::string> getPluginList ( void )
{
	std::vector<std::string> plugins;
	for (unsigned int i = 0; i < vPluginList.size();i++)
		plugins.push_back(vPluginList[i].plugin);

	return plugins;
}

void parseServerCommand(const char *message, int dstPlayerId);

class DynamicPluginCommands : public CustomSlashCommandHandler
{
public:
	virtual ~DynamicPluginCommands(){};
	virtual bool handle ( int playerID, std::string command, std::string message )
	{
		bz_PlayerRecord	record;

		bz_getPlayerByIndex(playerID,&record);

		if ( !record.admin )
		{
			bz_sendTextMessage(BZ_SERVER,playerID,"Permision denied: ADMIN");
			return true;
		}

		if ( !message.size() )
		{
			bz_sendTextMessage(BZ_SERVER,playerID,"Error: Command must have a plugin name");
			return true;
		}

		if ( TextUtils::tolower(command) == "loadplugin" )
		{
			std::vector<std::string> params = TextUtils::tokenize(message,std::string(","));

			std::string config;
			if ( params.size() >1)
				config = params[1];

			loadPlugin(params[0],config);

			bz_sendTextMessage(BZ_SERVER,playerID,"Plug-in loaded");
			return true;
		}

		if ( TextUtils::tolower(command) == "unloadplugin" )
		{
			unloadPlugin(message);

			bz_sendTextMessage(BZ_SERVER,playerID,"Plug-in unloaded");
			return true;
		}

		if ( TextUtils::tolower(command) == "listplugins" )
		{
			std::vector<std::string>	plugins = getPluginList();

			if (!plugins.size())
				bz_sendTextMessage(BZ_SERVER,playerID,"No Plug-ins loaded;");
			else
			{
				bz_sendTextMessage(BZ_SERVER,playerID,"Plug-isn loaded;");

				for ( unsigned int i = 0; i < plugins.size(); i++)
					bz_sendTextMessage(BZ_SERVER,playerID,plugins[i].c_str());
			}
			return true;
		}
		return true;
	}
};

DynamicPluginCommands	command;

void initPlugins ( void )
{
	registerCustomSlashCommand("loadplugin",&command);
	registerCustomSlashCommand("unloadplugin",&command);
	registerCustomSlashCommand("listplugins",&command);
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// File Stimulus.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description: Stimulus base class.
//
///////////////////////////////////////////////////////////////////////////////

#include <LibUtilities/BasicUtils/VmathArray.hpp>

#include <CardiacEPSolver/Stimuli/Stimulus.h>

#include <StdRegions/StdNodalTriExp.h>
//#include <LibUtilities/LinearAlgebra/Blas.hpp>

namespace Nektar
{
    StimulusFactory& GetStimulusFactory()
    {
        typedef Loki::SingletonHolder<StimulusFactory,
        Loki::CreateUsingNew,
        Loki::NoDestroy > Type;
        return Type::Instance();
    }

    /**
     * @class Stimulus
     *
     * The Stimulus class and derived classes implement a range of stimuli.
     * The stimulus contains input stimuli that can be applied throughout the
     * domain, on specified regions determined by the derived classes of Stimulus,
     * at specified frequencies determined by the derived classes of Protocol.
     *
     */

    /**
     * Stimulus base class constructor.
     */
    Stimulus::Stimulus(const LibUtilities::SessionReaderSharedPtr& pSession,
                         const MultiRegions::ExpListSharedPtr& pField)
    {
        m_session = pSession;
        m_field = pField;
        m_nq = pField->GetTotPoints();

    }

    /**
     * Initialise the stimulus. Allocate workspace and variable storage.
     */
    void Stimulus::Initialise()
    {

    }

}
<commit_msg>Edited Stimulus.cpp<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// File Stimulus.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description: Stimulus base class.
//
///////////////////////////////////////////////////////////////////////////////

#include <LibUtilities/BasicUtils/VmathArray.hpp>

#include <CardiacEPSolver/Stimuli/Stimulus.h>

#include <StdRegions/StdNodalTriExp.h>
//#include <LibUtilities/LinearAlgebra/Blas.hpp>

namespace Nektar
{
    StimulusFactory& GetStimulusFactory()
    {
        typedef Loki::SingletonHolder<StimulusFactory,
        Loki::CreateUsingNew,
        Loki::NoDestroy > Type;
        return Type::Instance();
    }

    /**
     * @class Stimulus
     *
     * The Stimulus class and derived classes implement a range of stimuli.
     * The stimulus contains input stimuli that can be applied throughout the
     * domain, on specified regions determined by the derived classes of Stimulus,
     * at specified frequencies determined by the derived classes of Protocol.
     *
     */

    /**
     * Stimulus base class constructor.
     */
    Stimulus::Stimulus(const LibUtilities::SessionReaderSharedPtr& pSession,
                         const MultiRegions::ExpListSharedPtr& pField,
                        const TiXmlElement* pXml)
    {
        m_session = pSession;
        m_field = pField;
        m_nq = pField->GetTotPoints();

    }

    /**
     * Initialise the stimulus. Allocate workspace and variable storage.
     */
    void Stimulus::Initialise()
    {

    }

}
<|endoftext|>


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

#include "JsonUtil.hxx"

#include <sstream>

Json::Value
ParseJson(std::string &&s) noexcept
{
	Json::Value root;
	std::stringstream(std::move(s)) >> root;
	return root;
}
<commit_msg>certdb/JsonUtil: use std::ios_base::in<commit_after>/*
 * Copyright 2007-2020 CM4all GmbH
 * All rights reserved.
 *
 * author: Max Kellermann <mk@cm4all.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the
 * distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "JsonUtil.hxx"

#include <sstream>

Json::Value
ParseJson(std::string &&s) noexcept
{
	Json::Value root;
	std::stringstream(std::move(s), std::ios_base::in) >> root;
	return root;
}
<|endoftext|>


<commit_before>#ifndef VTKLINESETEXPORTER_HPP_
#define VTKLINESETEXPORTER_HPP_

#include <vtkAlgorithm.h>
#include <vtkSmartPointer.h>
#include "FAST/ProcessObject.hpp"

class vtkPolyData;

namespace fast {

class VTKLineSetExporter : public vtkAlgorithm, public ProcessObject {
    public:
        static VTKLineSetExporter *New();
        vtkTypeRevisionMacro(VTKLineSetExporter,vtkAlgorithm);
        std::string getNameOfClass() const { return "VTKLineSetExporter"; };
        vtkSmartPointer<vtkPolyData> GetOutput();
        vtkSmartPointer<vtkPolyData> GetOutput(int portID);
        int ProcessRequest(vtkInformation* request,
                                     vtkInformationVector** inputVector,
                                     vtkInformationVector* outputVector);
    private:
        VTKLineSetExporter();
        int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *);
        int FillOutputPortInformation(int vtkNotUsed(port), vtkInformation* info);
        void execute() {};

};

} // end namespace fast

#endif /* VTKLINESETEXPORTER_HPP_ */
<commit_msg>use another vtk macro to ensure vtk 6.3 compatability<commit_after>#ifndef VTKLINESETEXPORTER_HPP_
#define VTKLINESETEXPORTER_HPP_

#include <vtkAlgorithm.h>
#include <vtkSmartPointer.h>
#include "FAST/ProcessObject.hpp"

class vtkPolyData;

namespace fast {

class VTKLineSetExporter : public vtkAlgorithm, public ProcessObject {
    public:
        static VTKLineSetExporter *New();
        vtkTypeMacro(VTKLineSetExporter,vtkAlgorithm);
        std::string getNameOfClass() const { return "VTKLineSetExporter"; };
        vtkSmartPointer<vtkPolyData> GetOutput();
        vtkSmartPointer<vtkPolyData> GetOutput(int portID);
        int ProcessRequest(vtkInformation* request,
                                     vtkInformationVector** inputVector,
                                     vtkInformationVector* outputVector);
    private:
        VTKLineSetExporter();
        int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *);
        int FillOutputPortInformation(int vtkNotUsed(port), vtkInformation* info);
        void execute() {};

};

} // end namespace fast

#endif /* VTKLINESETEXPORTER_HPP_ */
<|endoftext|>


<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin Core developers
// Copyright (c) 2015 The Hivemind Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "chainparamsbase.h"

#include "util.h"

#include <assert.h>

/**
 * Main network
 */
class CBaseMainParams : public CBaseChainParams
{
public:
    CBaseMainParams()
    {
        nRPCPort = 59532;
    }
};
static CBaseMainParams mainParams;

/**
 * Testnet (v3)
 */
class CBaseTestNetParams : public CBaseMainParams
{
public:
    CBaseTestNetParams()
    {
        nRPCPort = 64532;
        strDataDir = "testnet3";
    }
};
static CBaseTestNetParams testNetParams;

/*
 * Regression test
 */
class CBaseRegTestParams : public CBaseTestNetParams
{
public:
    CBaseRegTestParams()
    {
        strDataDir = "regtest";
    }
};
static CBaseRegTestParams regTestParams;

/*
 * Unit test
 */
class CBaseUnitTestParams : public CBaseMainParams
{
public:
    CBaseUnitTestParams()
    {
        strDataDir = "unittest";
    }
};
static CBaseUnitTestParams unitTestParams;

static CBaseChainParams* pCurrentBaseParams = 0;

const CBaseChainParams& BaseParams()
{
    assert(pCurrentBaseParams);
    return *pCurrentBaseParams;
}

void SelectBaseParams(CBaseChainParams::Network network)
{
    switch (network) {
    case CBaseChainParams::MAIN:
        pCurrentBaseParams = &mainParams;
        break;
    case CBaseChainParams::TESTNET:
        pCurrentBaseParams = &testNetParams;
        break;
    case CBaseChainParams::REGTEST:
        pCurrentBaseParams = &regTestParams;
        break;
    case CBaseChainParams::UNITTEST:
        pCurrentBaseParams = &unitTestParams;
        break;
    default:
        assert(false && "Unimplemented network");
        return;
    }
}

CBaseChainParams::Network NetworkIdFromCommandLine()
{
    bool fRegTest = GetBoolArg("-regtest", false);
    bool fTestNet = GetBoolArg("-testnet", false);

    if (fTestNet && fRegTest)
        return CBaseChainParams::MAX_NETWORK_TYPES;
    if (fRegTest)
        return CBaseChainParams::REGTEST;
    if (fTestNet)
        return CBaseChainParams::TESTNET;
    return CBaseChainParams::MAIN;
}

bool SelectBaseParamsFromCommandLine()
{
    CBaseChainParams::Network network = NetworkIdFromCommandLine();
    if (network == CBaseChainParams::MAX_NETWORK_TYPES)
        return false;

    SelectBaseParams(network);
    return true;
}

bool AreBaseParamsConfigured()
{
    return pCurrentBaseParams != NULL;
}
<commit_msg>Change testnet datadir<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin Core developers
// Copyright (c) 2015 The Hivemind Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "chainparamsbase.h"

#include "util.h"

#include <assert.h>

/**
 * Main network
 */
class CBaseMainParams : public CBaseChainParams
{
public:
    CBaseMainParams()
    {
        nRPCPort = 59532;
    }
};
static CBaseMainParams mainParams;

/**
 * Testnet (v3)
 */
class CBaseTestNetParams : public CBaseMainParams
{
public:
    CBaseTestNetParams()
    {
        nRPCPort = 64532;
        strDataDir = "testnet";
    }
};
static CBaseTestNetParams testNetParams;

/*
 * Regression test
 */
class CBaseRegTestParams : public CBaseTestNetParams
{
public:
    CBaseRegTestParams()
    {
        strDataDir = "regtest";
    }
};
static CBaseRegTestParams regTestParams;

/*
 * Unit test
 */
class CBaseUnitTestParams : public CBaseMainParams
{
public:
    CBaseUnitTestParams()
    {
        strDataDir = "unittest";
    }
};
static CBaseUnitTestParams unitTestParams;

static CBaseChainParams* pCurrentBaseParams = 0;

const CBaseChainParams& BaseParams()
{
    assert(pCurrentBaseParams);
    return *pCurrentBaseParams;
}

void SelectBaseParams(CBaseChainParams::Network network)
{
    switch (network) {
    case CBaseChainParams::MAIN:
        pCurrentBaseParams = &mainParams;
        break;
    case CBaseChainParams::TESTNET:
        pCurrentBaseParams = &testNetParams;
        break;
    case CBaseChainParams::REGTEST:
        pCurrentBaseParams = &regTestParams;
        break;
    case CBaseChainParams::UNITTEST:
        pCurrentBaseParams = &unitTestParams;
        break;
    default:
        assert(false && "Unimplemented network");
        return;
    }
}

CBaseChainParams::Network NetworkIdFromCommandLine()
{
    bool fRegTest = GetBoolArg("-regtest", false);
    bool fTestNet = GetBoolArg("-testnet", false);

    if (fTestNet && fRegTest)
        return CBaseChainParams::MAX_NETWORK_TYPES;
    if (fRegTest)
        return CBaseChainParams::REGTEST;
    if (fTestNet)
        return CBaseChainParams::TESTNET;
    return CBaseChainParams::MAIN;
}

bool SelectBaseParamsFromCommandLine()
{
    CBaseChainParams::Network network = NetworkIdFromCommandLine();
    if (network == CBaseChainParams::MAX_NETWORK_TYPES)
        return false;

    SelectBaseParams(network);
    return true;
}

bool AreBaseParamsConfigured()
{
    return pCurrentBaseParams != NULL;
}
<|endoftext|>


<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "chainparamsbase.h"

#include "tinyformat.h"
#include "util.h"

#include <assert.h>

const std::string CBaseChainParams::MAIN = "main";
const std::string CBaseChainParams::TESTNET = "test";
const std::string CBaseChainParams::REGTEST = "regtest";

void AppendParamsHelpMessages(std::string& strUsage, bool debugHelp)
{
    strUsage += HelpMessageGroup(_("Chain selection options:"));
    strUsage += HelpMessageOpt("-testnet", _("Use the test chain"));
    if (debugHelp) {
        strUsage += HelpMessageOpt("-regtest", "Enter regression test mode, which uses a special chain in which blocks can be solved instantly. "
                                   "This is intended for regression testing tools and app development.");
    }
}

/**
 * Main network
 */
class CBaseMainParams : public CBaseChainParams
{
public:
    CBaseMainParams()
    {
        nRPCPort = 8332;
    }
};
static CBaseMainParams mainParams;

/**
 * Testnet (v3)
 */
class CBaseTestNetParams : public CBaseChainParams
{
public:
    CBaseTestNetParams()
    {
        nRPCPort = 18332;
        strDataDir = "testnet3";
    }
};
static CBaseTestNetParams testNetParams;

/*
 * Regression test
 */
class CBaseRegTestParams : public CBaseChainParams
{
public:
    CBaseRegTestParams()
    {
        nRPCPort = 18332;
        strDataDir = "regtest";
    }
};
static CBaseRegTestParams regTestParams;

static CBaseChainParams* pCurrentBaseParams = 0;

const CBaseChainParams& BaseParams()
{
    assert(pCurrentBaseParams);
    return *pCurrentBaseParams;
}

CBaseChainParams& BaseParams(const std::string& chain)
{
    if (chain == CBaseChainParams::MAIN)
        return mainParams;
    else if (chain == CBaseChainParams::TESTNET)
        return testNetParams;
    else if (chain == CBaseChainParams::REGTEST)
        return regTestParams;
    else
        throw std::runtime_error(strprintf("%s: Unknown chain %s.", __func__, chain));
}

void SelectBaseParams(const std::string& chain)
{
    pCurrentBaseParams = &BaseParams(chain);
}

std::string ChainNameFromCommandLine()
{
    bool fRegTest = GetBoolArg("-regtest", false);
    bool fTestNet = GetBoolArg("-testnet", false);

    if (fTestNet && fRegTest)
        throw std::runtime_error("Invalid combination of -regtest and -testnet.");
    if (fRegTest)
        return CBaseChainParams::REGTEST;
    if (fTestNet)
        return CBaseChainParams::TESTNET;
    return CBaseChainParams::MAIN;
}

bool AreBaseParamsConfigured()
{
    return pCurrentBaseParams != NULL;
}
<commit_msg>Viacoin: Cbase RPC ports<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "chainparamsbase.h"

#include "tinyformat.h"
#include "util.h"

#include <assert.h>

const std::string CBaseChainParams::MAIN = "main";
const std::string CBaseChainParams::TESTNET = "test";
const std::string CBaseChainParams::REGTEST = "regtest";

void AppendParamsHelpMessages(std::string& strUsage, bool debugHelp)
{
    strUsage += HelpMessageGroup(_("Chain selection options:"));
    strUsage += HelpMessageOpt("-testnet", _("Use the test chain"));
    if (debugHelp) {
        strUsage += HelpMessageOpt("-regtest", "Enter regression test mode, which uses a special chain in which blocks can be solved instantly. "
                                   "This is intended for regression testing tools and app development.");
    }
}

/**
 * Main network
 */
class CBaseMainParams : public CBaseChainParams
{
public:
    CBaseMainParams()
    {
        nRPCPort = 5222;
    }
};
static CBaseMainParams mainParams;

/**
 * Testnet (v3)
 */
class CBaseTestNetParams : public CBaseChainParams
{
public:
    CBaseTestNetParams()
    {
        nRPCPort = 25222;
        strDataDir = "testnet3";
    }
};
static CBaseTestNetParams testNetParams;

/*
 * Regression test
 */
class CBaseRegTestParams : public CBaseChainParams
{
public:
    CBaseRegTestParams()
    {
        nRPCPort = 25222;
        strDataDir = "regtest";
    }
};
static CBaseRegTestParams regTestParams;

static CBaseChainParams* pCurrentBaseParams = 0;

const CBaseChainParams& BaseParams()
{
    assert(pCurrentBaseParams);
    return *pCurrentBaseParams;
}

CBaseChainParams& BaseParams(const std::string& chain)
{
    if (chain == CBaseChainParams::MAIN)
        return mainParams;
    else if (chain == CBaseChainParams::TESTNET)
        return testNetParams;
    else if (chain == CBaseChainParams::REGTEST)
        return regTestParams;
    else
        throw std::runtime_error(strprintf("%s: Unknown chain %s.", __func__, chain));
}

void SelectBaseParams(const std::string& chain)
{
    pCurrentBaseParams = &BaseParams(chain);
}

std::string ChainNameFromCommandLine()
{
    bool fRegTest = GetBoolArg("-regtest", false);
    bool fTestNet = GetBoolArg("-testnet", false);

    if (fTestNet && fRegTest)
        throw std::runtime_error("Invalid combination of -regtest and -testnet.");
    if (fRegTest)
        return CBaseChainParams::REGTEST;
    if (fTestNet)
        return CBaseChainParams::TESTNET;
    return CBaseChainParams::MAIN;
}

bool AreBaseParamsConfigured()
{
    return pCurrentBaseParams != NULL;
}
<|endoftext|>


<commit_before>//***************************************************************************************************************************************************
//* BSD 3-Clause License
//*
//* Copyright (c) 2016, Rene Thrane
//* All rights reserved.
//*
//* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//*
//* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
//*    documentation and/or other materials provided with the distribution.
//* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this
//*    software without specific prior written permission.
//*
//* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
//* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//***************************************************************************************************************************************************

#include <RAIIGen/Generator/VulkanGenerator.hpp>
#include <RAIIGen/Generator/FunctionNamePair.hpp>
#include <RAIIGen/Generator/MatchedFunctionPair.hpp>
#include <RAIIGen/Generator/RAIIClassCustomization.hpp>
#include <RAIIGen/Generator/RAIIClassMethodOverrides.hpp>
#include <RAIIGen/CaseUtil.hpp>
#include <RAIIGen/Capture.hpp>
#include <FslBase/Exceptions.hpp>
#include <FslBase/IO/File.hpp>
#include <FslBase/String/StringUtil.hpp>
#include <algorithm>
#include <array>
#include <iostream>
#include <string>
#include <unordered_map>
#include <unordered_set>

using namespace Fsl;

namespace MB
{

  namespace
  {
    // OpenCL
    //const auto VULKAN_CREATE_FUNCTION = "clCreate";
    //const auto VULKAN_DESTROY_FUNCTION = "clDestroy";
    //const auto VULKAN_ALLOCATE_FUNCTION = "clAllocate";
    //const auto VULKAN_FREE_FUNCTION = "clFree";

    const auto CREATE_FUNCTION = "vkCreate";
    const auto DESTROY_FUNCTION = "vkDestroy";
    const auto ALLOCATE_FUNCTION = "vkAllocate";
    const auto FREE_FUNCTION = "vkFree";

    const auto TYPE_NAME_PREFIX = "Vk";
    const auto FUNCTION_NAME_PREFIX = "vk";

    const auto DEFAULT_VALUE = "VK_NULL_HANDLE";

    const auto ERRORCODE_TYPE_NAME = "VkResult";

    const std::vector<FunctionNamePair> g_functionPairs
    {
      FunctionNamePair(CREATE_FUNCTION, DESTROY_FUNCTION),
      FunctionNamePair(ALLOCATE_FUNCTION, FREE_FUNCTION)
    };

    // Manual matches for methods that don't follow 'standard' patterns
    const std::vector<FunctionNamePair> g_manualFunctionMatches
    {
      // Pipelines are destroyed with vkDestroyPipeline
      FunctionNamePair("vkCreateGraphicsPipelines", "vkDestroyPipeline"),
      FunctionNamePair("vkCreateComputePipelines", "vkDestroyPipeline"),
      FunctionNamePair("vkCreateDisplayPlaneSurfaceKHR", "vkDestroySurfaceKHR"),
    };

    const std::vector<RAIIClassCustomization> g_arrayRAIIClassCustomization
    {
      RAIIClassCustomization("vkAllocateCommandBuffers", "CommandBuffer", "CommandBuffers", "commandBuffers", "commandBufferCount", ""),
      RAIIClassCustomization("vkAllocateDescriptorSets", "DescriptorSet", "DescriptorSets", "descriptorSets", "descriptorSetCount", ""),
      RAIIClassCustomization("vkCreateComputePipelines", "ComputePipeline", "ComputePipelines", "computePipelines", "", "createInfoCount", SourceTemplateType::ArrayAllocationButSingleInstanceDestroy),
      RAIIClassCustomization("vkCreateGraphicsPipelines", "GraphicsPipeline", "GraphicsPipelines", "graphicsPipelines", "", "createInfoCount", SourceTemplateType::ArrayAllocationButSingleInstanceDestroy),
    };

    const std::vector<ClassFunctionAbsorb> g_classFunctionAbsorbtion
    {
    };

    const std::unordered_map<std::string, RAIIClassMethodOverrides> g_classMethodOverride =
    {
      { "SwapchainKHR", RAIIClassMethodOverrides("TemplateSnippet_ResetMemberHeader_CustomSwapchain.txt") },
    };

    const std::vector<std::string> g_forceNullParameter
    {
      "VkAllocationCallbacks"
    };

    const std::vector<FunctionGuard> g_functionGuards
    {
      // FunctionGuard("vkGetSwapchainStatusKHR", "VK_HEADER_VERSION >= 49")
    };

    const std::vector<BlackListEntry> g_functionNameBlacklist
    {
      BlackListEntry("GetFenceStatus", BlackListMatch::Exact),
      BlackListEntry("EXT", BlackListMatch::PostfixNotEntityName),
      BlackListEntry("GOOGLE", BlackListMatch::PostfixNotEntityName),
      BlackListEntry("KHR", BlackListMatch::PostfixNotEntityName),
      BlackListEntry("KHX", BlackListMatch::PostfixNotEntityName),
      BlackListEntry("AMD", BlackListMatch::PostfixNotEntityName)
    };

    const std::vector<BlackListEntry> g_enumNameBlacklist
    {
      //BlackListEntry("AMD", BlackListMatch::Always),
      //BlackListEntry("EXT", BlackListMatch::Always),
      //BlackListEntry("GOOGLE", BlackListMatch::Always),
      //BlackListEntry("KHR", BlackListMatch::Always),
      //BlackListEntry("KHX", BlackListMatch::Always),
      //BlackListEntry("NV", BlackListMatch::Always),
      //BlackListEntry("NVX", BlackListMatch::Always),
    };

    const std::vector<BlackListEntry> g_enumMemberBlacklist
    {
      BlackListEntry("_BEGIN_RANGE", BlackListMatch::Postfix),
      BlackListEntry("_END_RANGE", BlackListMatch::Postfix),
      BlackListEntry("_RANGE_SIZE", BlackListMatch::Postfix),
      BlackListEntry("_MAX_ENUM", BlackListMatch::Postfix),

      BlackListEntry("_BEGIN_RANGE_", BlackListMatch::Contains),
      BlackListEntry("_END_RANGE_", BlackListMatch::Contains),
      BlackListEntry("_RANGE_SIZE_", BlackListMatch::Contains),
      BlackListEntry("_MAX_ENUM_", BlackListMatch::Contains),

      BlackListEntry("_AMD", "AMD", BlackListMatch::PostfixNotEntityNameEx),
      BlackListEntry("_EXT", "EXT", BlackListMatch::PostfixNotEntityNameEx),
      BlackListEntry("_GOOGLE", "GOOGLE", BlackListMatch::PostfixNotEntityNameEx),
      BlackListEntry("_KHR", "KHR", BlackListMatch::PostfixNotEntityNameEx),
      BlackListEntry("_KHX", "KHX", BlackListMatch::PostfixNotEntityNameEx),
      BlackListEntry("_NV", "NV", BlackListMatch::PostfixNotEntityNameEx),
      BlackListEntry("_NVX", "NVX", BlackListMatch::PostfixNotEntityNameEx),
    };

    //! Not necessary for the Vulkan header as it was properly constructed!
    const std::vector<FunctionParameterNameOverride> g_functionParameterNameOverride
    {
    };

    const std::vector<FunctionParameterTypeOverride> g_functionParameterTypeOverride
    {
    };

    const std::unordered_map<std::string, std::string> g_typeDefaultValues =
    {
      { "VkBuffer", DEFAULT_VALUE },
      { "VkBufferView", DEFAULT_VALUE },
      { "VkCommandBuffer", DEFAULT_VALUE },
      { "VkCommandPool", DEFAULT_VALUE },
      { "VkDebugReportCallbackEXT", DEFAULT_VALUE },
      { "VkDescriptorPool", DEFAULT_VALUE },
      { "VkDescriptorSet", DEFAULT_VALUE },
      { "VkDescriptorSetLayout", DEFAULT_VALUE },
      { "VkDevice", DEFAULT_VALUE },
      { "VkDeviceMemory", DEFAULT_VALUE },
      { "VkEvent", DEFAULT_VALUE },
      { "VkFence", DEFAULT_VALUE },
      { "VkFramebuffer", DEFAULT_VALUE },
      { "VkImage", DEFAULT_VALUE },
      { "VkImageView", DEFAULT_VALUE },
      { "VkInstance", DEFAULT_VALUE },
      { "VkPipeline", DEFAULT_VALUE },
      { "VkPipelineCache", DEFAULT_VALUE },
      { "VkPipelineLayout", DEFAULT_VALUE },
      { "VkQueryPool", DEFAULT_VALUE },
      { "VkRenderPass", DEFAULT_VALUE },
      { "VkSampler", DEFAULT_VALUE },
      { "VkSemaphore", DEFAULT_VALUE },
      { "VkShaderModule", DEFAULT_VALUE },
      { "VkSurfaceKHR", DEFAULT_VALUE },
      { "VkSwapchainKHR", DEFAULT_VALUE },
      { "VkSamplerYcbcrConversionKHR", DEFAULT_VALUE },
      { "VkDescriptorUpdateTemplateKHR", DEFAULT_VALUE },
      { "VkIndirectCommandsLayoutNVX", DEFAULT_VALUE },
      { "VkObjectTableNVX", DEFAULT_VALUE },
      { "VkValidationCacheEXT", DEFAULT_VALUE },
    };
  }

  VulkanGenerator::VulkanGenerator(const Capture& capture, const BasicConfig& basicConfig, const Fsl::IO::Path& templateRoot, const Fsl::IO::Path& dstPath)
    : SimpleGenerator(capture,
                      SimpleGeneratorConfig(basicConfig, g_functionPairs, g_manualFunctionMatches, g_arrayRAIIClassCustomization,
                                            g_classFunctionAbsorbtion, g_classMethodOverride, g_typeDefaultValues, g_forceNullParameter,
                                            g_functionGuards, g_functionNameBlacklist,
                                            g_enumNameBlacklist, g_enumMemberBlacklist,
                                            TYPE_NAME_PREFIX, FUNCTION_NAME_PREFIX, ERRORCODE_TYPE_NAME, true, true,
                                            VersionGuardConfig("VK_HEADER_VERSION >= {2}"),  true),
                      templateRoot, dstPath)
  {
  }

  CaptureConfig VulkanGenerator::GetCaptureConfig()
  {
    std::deque<std::string> filters;
    //filters.push_back(CREATE_FUNCTION);
    //filters.push_back(DESTROY_FUNCTION);
    //filters.push_back(ALLOCATE_FUNCTION);
    //filters.push_back(FREE_FUNCTION);
    return CaptureConfig(TYPE_NAME_PREFIX, filters, g_functionParameterNameOverride, g_functionParameterTypeOverride, false);
  }
}
<commit_msg>Added filtering for the new NVX and NV functions so they dont get added to the main classes.<commit_after>//***************************************************************************************************************************************************
//* BSD 3-Clause License
//*
//* Copyright (c) 2016, Rene Thrane
//* All rights reserved.
//*
//* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//*
//* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
//*    documentation and/or other materials provided with the distribution.
//* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this
//*    software without specific prior written permission.
//*
//* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
//* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//***************************************************************************************************************************************************

#include <RAIIGen/Generator/VulkanGenerator.hpp>
#include <RAIIGen/Generator/FunctionNamePair.hpp>
#include <RAIIGen/Generator/MatchedFunctionPair.hpp>
#include <RAIIGen/Generator/RAIIClassCustomization.hpp>
#include <RAIIGen/Generator/RAIIClassMethodOverrides.hpp>
#include <RAIIGen/CaseUtil.hpp>
#include <RAIIGen/Capture.hpp>
#include <FslBase/Exceptions.hpp>
#include <FslBase/IO/File.hpp>
#include <FslBase/String/StringUtil.hpp>
#include <algorithm>
#include <array>
#include <iostream>
#include <string>
#include <unordered_map>
#include <unordered_set>

using namespace Fsl;

namespace MB
{

  namespace
  {
    // OpenCL
    //const auto VULKAN_CREATE_FUNCTION = "clCreate";
    //const auto VULKAN_DESTROY_FUNCTION = "clDestroy";
    //const auto VULKAN_ALLOCATE_FUNCTION = "clAllocate";
    //const auto VULKAN_FREE_FUNCTION = "clFree";

    const auto CREATE_FUNCTION = "vkCreate";
    const auto DESTROY_FUNCTION = "vkDestroy";
    const auto ALLOCATE_FUNCTION = "vkAllocate";
    const auto FREE_FUNCTION = "vkFree";

    const auto TYPE_NAME_PREFIX = "Vk";
    const auto FUNCTION_NAME_PREFIX = "vk";

    const auto DEFAULT_VALUE = "VK_NULL_HANDLE";

    const auto ERRORCODE_TYPE_NAME = "VkResult";

    const std::vector<FunctionNamePair> g_functionPairs
    {
      FunctionNamePair(CREATE_FUNCTION, DESTROY_FUNCTION),
      FunctionNamePair(ALLOCATE_FUNCTION, FREE_FUNCTION)
    };

    // Manual matches for methods that don't follow 'standard' patterns
    const std::vector<FunctionNamePair> g_manualFunctionMatches
    {
      // Pipelines are destroyed with vkDestroyPipeline
      FunctionNamePair("vkCreateGraphicsPipelines", "vkDestroyPipeline"),
      FunctionNamePair("vkCreateComputePipelines", "vkDestroyPipeline"),
      FunctionNamePair("vkCreateDisplayPlaneSurfaceKHR", "vkDestroySurfaceKHR"),
    };

    const std::vector<RAIIClassCustomization> g_arrayRAIIClassCustomization
    {
      RAIIClassCustomization("vkAllocateCommandBuffers", "CommandBuffer", "CommandBuffers", "commandBuffers", "commandBufferCount", ""),
      RAIIClassCustomization("vkAllocateDescriptorSets", "DescriptorSet", "DescriptorSets", "descriptorSets", "descriptorSetCount", ""),
      RAIIClassCustomization("vkCreateComputePipelines", "ComputePipeline", "ComputePipelines", "computePipelines", "", "createInfoCount", SourceTemplateType::ArrayAllocationButSingleInstanceDestroy),
      RAIIClassCustomization("vkCreateGraphicsPipelines", "GraphicsPipeline", "GraphicsPipelines", "graphicsPipelines", "", "createInfoCount", SourceTemplateType::ArrayAllocationButSingleInstanceDestroy),
    };

    const std::vector<ClassFunctionAbsorb> g_classFunctionAbsorbtion
    {
    };

    const std::unordered_map<std::string, RAIIClassMethodOverrides> g_classMethodOverride =
    {
      { "SwapchainKHR", RAIIClassMethodOverrides("TemplateSnippet_ResetMemberHeader_CustomSwapchain.txt") },
    };

    const std::vector<std::string> g_forceNullParameter
    {
      "VkAllocationCallbacks"
    };

    const std::vector<FunctionGuard> g_functionGuards
    {
      // FunctionGuard("vkGetSwapchainStatusKHR", "VK_HEADER_VERSION >= 49")
    };

    const std::vector<BlackListEntry> g_functionNameBlacklist
    {
      BlackListEntry("GetFenceStatus", BlackListMatch::Exact),
      BlackListEntry("EXT", BlackListMatch::PostfixNotEntityName),
      BlackListEntry("GOOGLE", BlackListMatch::PostfixNotEntityName),
      BlackListEntry("KHR", BlackListMatch::PostfixNotEntityName),
      BlackListEntry("KHX", BlackListMatch::PostfixNotEntityName),
      BlackListEntry("AMD", BlackListMatch::PostfixNotEntityName),
      BlackListEntry("NVX", BlackListMatch::PostfixNotEntityName),
      BlackListEntry("NV", BlackListMatch::PostfixNotEntityName),
    };

    const std::vector<BlackListEntry> g_enumNameBlacklist
    {
      //BlackListEntry("AMD", BlackListMatch::Always),
      //BlackListEntry("EXT", BlackListMatch::Always),
      //BlackListEntry("GOOGLE", BlackListMatch::Always),
      //BlackListEntry("KHR", BlackListMatch::Always),
      //BlackListEntry("KHX", BlackListMatch::Always),
      //BlackListEntry("NV", BlackListMatch::Always),
      //BlackListEntry("NVX", BlackListMatch::Always),
    };

    const std::vector<BlackListEntry> g_enumMemberBlacklist
    {
      BlackListEntry("_BEGIN_RANGE", BlackListMatch::Postfix),
      BlackListEntry("_END_RANGE", BlackListMatch::Postfix),
      BlackListEntry("_RANGE_SIZE", BlackListMatch::Postfix),
      BlackListEntry("_MAX_ENUM", BlackListMatch::Postfix),

      BlackListEntry("_BEGIN_RANGE_", BlackListMatch::Contains),
      BlackListEntry("_END_RANGE_", BlackListMatch::Contains),
      BlackListEntry("_RANGE_SIZE_", BlackListMatch::Contains),
      BlackListEntry("_MAX_ENUM_", BlackListMatch::Contains),

      BlackListEntry("_AMD", "AMD", BlackListMatch::PostfixNotEntityNameEx),
      BlackListEntry("_EXT", "EXT", BlackListMatch::PostfixNotEntityNameEx),
      BlackListEntry("_GOOGLE", "GOOGLE", BlackListMatch::PostfixNotEntityNameEx),
      BlackListEntry("_KHR", "KHR", BlackListMatch::PostfixNotEntityNameEx),
      BlackListEntry("_KHX", "KHX", BlackListMatch::PostfixNotEntityNameEx),
      BlackListEntry("_NV", "NV", BlackListMatch::PostfixNotEntityNameEx),
      BlackListEntry("_NVX", "NVX", BlackListMatch::PostfixNotEntityNameEx),
    };

    //! Not necessary for the Vulkan header as it was properly constructed!
    const std::vector<FunctionParameterNameOverride> g_functionParameterNameOverride
    {
    };

    const std::vector<FunctionParameterTypeOverride> g_functionParameterTypeOverride
    {
    };

    const std::unordered_map<std::string, std::string> g_typeDefaultValues =
    {
      { "VkBuffer", DEFAULT_VALUE },
      { "VkBufferView", DEFAULT_VALUE },
      { "VkCommandBuffer", DEFAULT_VALUE },
      { "VkCommandPool", DEFAULT_VALUE },
      { "VkDebugReportCallbackEXT", DEFAULT_VALUE },
      { "VkDescriptorPool", DEFAULT_VALUE },
      { "VkDescriptorSet", DEFAULT_VALUE },
      { "VkDescriptorSetLayout", DEFAULT_VALUE },
      { "VkDevice", DEFAULT_VALUE },
      { "VkDeviceMemory", DEFAULT_VALUE },
      { "VkEvent", DEFAULT_VALUE },
      { "VkFence", DEFAULT_VALUE },
      { "VkFramebuffer", DEFAULT_VALUE },
      { "VkImage", DEFAULT_VALUE },
      { "VkImageView", DEFAULT_VALUE },
      { "VkInstance", DEFAULT_VALUE },
      { "VkPipeline", DEFAULT_VALUE },
      { "VkPipelineCache", DEFAULT_VALUE },
      { "VkPipelineLayout", DEFAULT_VALUE },
      { "VkQueryPool", DEFAULT_VALUE },
      { "VkRenderPass", DEFAULT_VALUE },
      { "VkSampler", DEFAULT_VALUE },
      { "VkSemaphore", DEFAULT_VALUE },
      { "VkShaderModule", DEFAULT_VALUE },
      { "VkSurfaceKHR", DEFAULT_VALUE },
      { "VkSwapchainKHR", DEFAULT_VALUE },
      { "VkSamplerYcbcrConversionKHR", DEFAULT_VALUE },
      { "VkDescriptorUpdateTemplateKHR", DEFAULT_VALUE },
      { "VkIndirectCommandsLayoutNVX", DEFAULT_VALUE },
      { "VkObjectTableNVX", DEFAULT_VALUE },
      { "VkValidationCacheEXT", DEFAULT_VALUE },
    };
  }

  VulkanGenerator::VulkanGenerator(const Capture& capture, const BasicConfig& basicConfig, const Fsl::IO::Path& templateRoot, const Fsl::IO::Path& dstPath)
    : SimpleGenerator(capture,
                      SimpleGeneratorConfig(basicConfig, g_functionPairs, g_manualFunctionMatches, g_arrayRAIIClassCustomization,
                                            g_classFunctionAbsorbtion, g_classMethodOverride, g_typeDefaultValues, g_forceNullParameter,
                                            g_functionGuards, g_functionNameBlacklist,
                                            g_enumNameBlacklist, g_enumMemberBlacklist,
                                            TYPE_NAME_PREFIX, FUNCTION_NAME_PREFIX, ERRORCODE_TYPE_NAME, true, true,
                                            VersionGuardConfig("VK_HEADER_VERSION >= {2}"),  true),
                      templateRoot, dstPath)
  {
  }

  CaptureConfig VulkanGenerator::GetCaptureConfig()
  {
    std::deque<std::string> filters;
    //filters.push_back(CREATE_FUNCTION);
    //filters.push_back(DESTROY_FUNCTION);
    //filters.push_back(ALLOCATE_FUNCTION);
    //filters.push_back(FREE_FUNCTION);
    return CaptureConfig(TYPE_NAME_PREFIX, filters, g_functionParameterNameOverride, g_functionParameterTypeOverride, false);
  }
}
<|endoftext|>


<commit_before>#include <Eigen/Core>       // Cholesky decomposition + solving
#include <Eigen/Cholesky>   // of system of linear equations.

#include "nao_igm.h"
#include "maple_functions.h"
#include "joint_bounds.h"

/**
 * @brief Check that all joint angles lie within bounds.
 *
 * @return -1 if all values are corrent, id of the first joint violating the
 * bounds.
 *
 * @attention No collision checks!
 */
int nao_igm::checkJointBounds()
{
    return(joint_bounds.check(state.q));
}

/**
 * @brief Set feet postures.
 *
 * @param[in] left_foot_position 3x1 vector of coordinates + yaw angle.
 * @param[in] right_foot_position 3x1 vector of coordinates + yaw angle.
 *
 * @note Roll and pitch angles are assumed to be 0.
 */
void nao_igm::setFeetPostures (
        const double *left_foot_position,
        const double *right_foot_position)
{
    if (state.support_foot == IGM_SUPPORT_LEFT)
    {
        setSupportPosture (left_foot_position, 0.0, 0.0, left_foot_position[3]);
        swing_foot_posture.init (right_foot_position, 0.0, 0.0, right_foot_position[3]);
    }
    else
    {
        setSupportPosture (right_foot_position, 0.0, 0.0, right_foot_position[3]);
        swing_foot_posture.init (left_foot_position, 0.0, 0.0, left_foot_position[3]);
    }
}

/**
 * @brief Set support foot posture.
 *
 * @param[in] support_foot_position 3x1 vector of coordinates
 * @param[in] roll angle
 * @param[in] pitch angle
 * @param[in] yaw angle
 */
void nao_igm::setSupportPosture (
        const double *support_foot_position,
        const double roll,
        const double pitch,
        const double yaw)
{
    state.q[SUPPORT_FOOT_POS_START]     = support_foot_position[0];
    state.q[SUPPORT_FOOT_POS_START + 1] = support_foot_position[1];
    state.q[SUPPORT_FOOT_POS_START + 2] = support_foot_position[2];
    rpy2R (roll, pitch, yaw, &state.q[SUPPORT_FOOT_ORIENTATION_START]);

    for (int i = SUPPORT_FOOT_POS_START; i < STATE_VAR_NUM; i++)
    {
        state_sensor.q[i] = state.q[i];
    }
}

/**
 * @brief Set coordinates of center of mass.
 *
 * @param[in] x coordinate
 * @param[in] y coordinate
 * @param[in] z coordinate
 */
void nao_igm::setCoM (const double x, const double y, const double z)
{
    CoM_position[0] = x;
    CoM_position[1] = y;
    CoM_position[2] = z;
}

/** @brief Initialize model.

    @param[in] support_foot_ current support foot.
    @param[in] x x-position
    @param[in] y y-position
    @param[in] z z-position
    @param[in] roll x-rotation
    @param[in] pitch y-rotation
    @param[in] yaw z-rotation
*/
void nao_igm::init(
        const igmSupportFoot support_foot_,
        const double x,
        const double y,
        const double z,
        const double roll,
        const double pitch,
        const double yaw)
{
    state.q[SUPPORT_FOOT_POS_START]     = x;
    state.q[SUPPORT_FOOT_POS_START + 1] = y;
    state.q[SUPPORT_FOOT_POS_START + 2] = z;
    rpy2R (roll, pitch, yaw, &state.q[SUPPORT_FOOT_ORIENTATION_START]);

    for (int i = 0; i < STATE_VAR_NUM; i++)
    {
        state_sensor.q[i] = state.q[i];
    }
    state.support_foot = state_sensor.support_foot = support_foot_;

    posture torso_posture;
    if (state.support_foot == IGM_SUPPORT_LEFT)
    {
        LLeg2RLeg(state.q, swing_foot_posture.data);
        LLeg2Torso(state.q, torso_posture.data);
        LLeg2CoM(state.q, CoM_position);
    }
    else
    {
        RLeg2LLeg(state.q, swing_foot_posture.data);
        RLeg2Torso(state.q, torso_posture.data);
        RLeg2CoM(state.q, CoM_position);
    }
    torso_posture.getOrientation(torso_orientation);
}

/**
 * @brief Switch support foot.
 *
 * @param[in] position_error 3x1 position error vector
 */
void nao_igm::switchSupportFoot(double *position_error)
{
    posture swing_foot_posture_sensor;
    state_sensor.getSwingFootPosture (swing_foot_posture_sensor.data);
    swing_foot_posture.getPositionDiff (swing_foot_posture_sensor, position_error);

    swing_foot_posture_sensor.getPosition (&state.q[SUPPORT_FOOT_POS_START]);
    swing_foot_posture_sensor.getOrientation (&state.q[SUPPORT_FOOT_ORIENTATION_START]);

    if (state.support_foot == IGM_SUPPORT_LEFT)
    {
        state.support_foot = state_sensor.support_foot = IGM_SUPPORT_RIGHT;
    }
    else
    {
        state.support_foot = state_sensor.support_foot = IGM_SUPPORT_LEFT;
    }
    for (int i = SUPPORT_FOOT_POS_START; i < STATE_VAR_NUM; i++)
    {
        state_sensor.q[i] = state.q[i];
    }
}

/** \brief Solves the Inverse Geometric Problem (IGM). Constraints for (x, y, z, X(alpha), Y(beta),
    Z(gamma)) of the foot not in support as well as (x, y, z) position of the CoM, and X(alpha),
    Y(beta) rotation of the torso can be imposed.

    \return int iter - the number of iterations performed until convergence, or -1 if the algorithm
    did not converge within max_iter number of iterations.

    \note It is assumed that the leading matrix of the constraints is nonsingular.

    @note On input, the entries of q are the joint angles from where to start the
    search for a solution (i.e., the initial guess). On output q contains a solution of the
    inverse kinematics problem (if iter != -1). Only q[0]...q[11] are altered.
*/
int nao_igm::igm()
{
    const int N = LOWER_JOINTS_NUM;

    double out[N*N+N];
    Eigen::VectorXd dq(N);
    Eigen::LLT<Eigen::MatrixXd> llt;

    double tol = 0.0005;
    int max_iter = 20;
    int iter = 0;
    double norm_dq = 1.0;

    while (norm_dq > tol && iter != -1)
    {
        // Form data
        if (state.support_foot == IGM_SUPPORT_LEFT)
            from_LLeg_3(state.q, swing_foot_posture.data, CoM_position, torso_orientation, out);
        else
            from_RLeg_3(state.q, swing_foot_posture.data, CoM_position, torso_orientation, out);

        Eigen::Map<Eigen::MatrixXd> A(out,N,N);
        Eigen::Map<Eigen::VectorXd> err(out+N*N,N);

        // Solve KKT system
        llt.compute(A*A.transpose());
        llt.solve(-err, &dq);
        dq = -A.transpose()*dq;

        // Update angles (of legs)
        for (int i=0; i<LOWER_JOINTS_NUM; i++)
            state.q[i] += dq[i];

        // Check termination condition
        norm_dq = 0;
        for (int i=0; i<11; i++)
            norm_dq += dq[i]*dq[i];
        norm_dq = sqrt(norm_dq);

        iter++;
        if (iter > max_iter)
        {
            iter = -1;
        }
    }

    return(iter);
}
<commit_msg>Revert "Do not set error along z to 0.0 in switchSupportFoot() (leave it for WMG)."<commit_after>#include <Eigen/Core>       // Cholesky decomposition + solving
#include <Eigen/Cholesky>   // of system of linear equations.

#include "nao_igm.h"
#include "maple_functions.h"
#include "joint_bounds.h"

/**
 * @brief Check that all joint angles lie within bounds.
 *
 * @return -1 if all values are corrent, id of the first joint violating the
 * bounds.
 *
 * @attention No collision checks!
 */
int nao_igm::checkJointBounds()
{
    return(joint_bounds.check(state.q));
}

/**
 * @brief Set feet postures.
 *
 * @param[in] left_foot_position 3x1 vector of coordinates + yaw angle.
 * @param[in] right_foot_position 3x1 vector of coordinates + yaw angle.
 *
 * @note Roll and pitch angles are assumed to be 0.
 */
void nao_igm::setFeetPostures (
        const double *left_foot_position,
        const double *right_foot_position)
{
    if (state.support_foot == IGM_SUPPORT_LEFT)
    {
        setSupportPosture (left_foot_position, 0.0, 0.0, left_foot_position[3]);
        swing_foot_posture.init (right_foot_position, 0.0, 0.0, right_foot_position[3]);
    }
    else
    {
        setSupportPosture (right_foot_position, 0.0, 0.0, right_foot_position[3]);
        swing_foot_posture.init (left_foot_position, 0.0, 0.0, left_foot_position[3]);
    }
}

/**
 * @brief Set support foot posture.
 *
 * @param[in] support_foot_position 3x1 vector of coordinates
 * @param[in] roll angle
 * @param[in] pitch angle
 * @param[in] yaw angle
 */
void nao_igm::setSupportPosture (
        const double *support_foot_position,
        const double roll,
        const double pitch,
        const double yaw)
{
    state.q[SUPPORT_FOOT_POS_START]     = support_foot_position[0];
    state.q[SUPPORT_FOOT_POS_START + 1] = support_foot_position[1];
    state.q[SUPPORT_FOOT_POS_START + 2] = support_foot_position[2];
    rpy2R (roll, pitch, yaw, &state.q[SUPPORT_FOOT_ORIENTATION_START]);

    for (int i = SUPPORT_FOOT_POS_START; i < STATE_VAR_NUM; i++)
    {
        state_sensor.q[i] = state.q[i];
    }
}

/**
 * @brief Set coordinates of center of mass.
 *
 * @param[in] x coordinate
 * @param[in] y coordinate
 * @param[in] z coordinate
 */
void nao_igm::setCoM (const double x, const double y, const double z)
{
    CoM_position[0] = x;
    CoM_position[1] = y;
    CoM_position[2] = z;
}

/** @brief Initialize model.

    @param[in] support_foot_ current support foot.
    @param[in] x x-position
    @param[in] y y-position
    @param[in] z z-position
    @param[in] roll x-rotation
    @param[in] pitch y-rotation
    @param[in] yaw z-rotation
*/
void nao_igm::init(
        const igmSupportFoot support_foot_,
        const double x,
        const double y,
        const double z,
        const double roll,
        const double pitch,
        const double yaw)
{
    state.q[SUPPORT_FOOT_POS_START]     = x;
    state.q[SUPPORT_FOOT_POS_START + 1] = y;
    state.q[SUPPORT_FOOT_POS_START + 2] = z;
    rpy2R (roll, pitch, yaw, &state.q[SUPPORT_FOOT_ORIENTATION_START]);

    for (int i = 0; i < STATE_VAR_NUM; i++)
    {
        state_sensor.q[i] = state.q[i];
    }
    state.support_foot = state_sensor.support_foot = support_foot_;

    posture torso_posture;
    if (state.support_foot == IGM_SUPPORT_LEFT)
    {
        LLeg2RLeg(state.q, swing_foot_posture.data);
        LLeg2Torso(state.q, torso_posture.data);
        LLeg2CoM(state.q, CoM_position);
    }
    else
    {
        RLeg2LLeg(state.q, swing_foot_posture.data);
        RLeg2Torso(state.q, torso_posture.data);
        RLeg2CoM(state.q, CoM_position);
    }
    torso_posture.getOrientation(torso_orientation);
}

/**
 * @brief Switch support foot.
 *
 * @param[in] position_error 3x1 position error vector
 *
 * @attention The error along z axis is ignored.
 */
void nao_igm::switchSupportFoot(double *position_error)
{
    posture swing_foot_posture_sensor;
    state_sensor.getSwingFootPosture (swing_foot_posture_sensor.data);
    swing_foot_posture.getPositionDiff (swing_foot_posture_sensor, position_error);

    swing_foot_posture_sensor.getPosition (&state.q[SUPPORT_FOOT_POS_START]);
    // reset z position
    state.q[SUPPORT_FOOT_POS_START + 2] = 0.0;
    swing_foot_posture_sensor.getOrientation (&state.q[SUPPORT_FOOT_ORIENTATION_START]);

    if (state.support_foot == IGM_SUPPORT_LEFT)
    {
        state.support_foot = state_sensor.support_foot = IGM_SUPPORT_RIGHT;
    }
    else
    {
        state.support_foot = state_sensor.support_foot = IGM_SUPPORT_LEFT;
    }
    for (int i = SUPPORT_FOOT_POS_START; i < STATE_VAR_NUM; i++)
    {
        state_sensor.q[i] = state.q[i];
    }
}

/** \brief Solves the Inverse Geometric Problem (IGM). Constraints for (x, y, z, X(alpha), Y(beta),
    Z(gamma)) of the foot not in support as well as (x, y, z) position of the CoM, and X(alpha),
    Y(beta) rotation of the torso can be imposed.

    \return int iter - the number of iterations performed until convergence, or -1 if the algorithm
    did not converge within max_iter number of iterations.

    \note It is assumed that the leading matrix of the constraints is nonsingular.

    @note On input, the entries of q are the joint angles from where to start the
    search for a solution (i.e., the initial guess). On output q contains a solution of the
    inverse kinematics problem (if iter != -1). Only q[0]...q[11] are altered.
*/
int nao_igm::igm()
{
    const int N = LOWER_JOINTS_NUM;

    double out[N*N+N];
    Eigen::VectorXd dq(N);
    Eigen::LLT<Eigen::MatrixXd> llt;

    double tol = 0.0005;
    int max_iter = 20;
    int iter = 0;
    double norm_dq = 1.0;

    while (norm_dq > tol && iter != -1)
    {
        // Form data
        if (state.support_foot == IGM_SUPPORT_LEFT)
            from_LLeg_3(state.q, swing_foot_posture.data, CoM_position, torso_orientation, out);
        else
            from_RLeg_3(state.q, swing_foot_posture.data, CoM_position, torso_orientation, out);

        Eigen::Map<Eigen::MatrixXd> A(out,N,N);
        Eigen::Map<Eigen::VectorXd> err(out+N*N,N);

        // Solve KKT system
        llt.compute(A*A.transpose());
        llt.solve(-err, &dq);
        dq = -A.transpose()*dq;

        // Update angles (of legs)
        for (int i=0; i<LOWER_JOINTS_NUM; i++)
            state.q[i] += dq[i];

        // Check termination condition
        norm_dq = 0;
        for (int i=0; i<11; i++)
            norm_dq += dq[i]*dq[i];
        norm_dq = sqrt(norm_dq);

        iter++;
        if (iter > max_iter)
        {
            iter = -1;
        }
    }

    return(iter);
}
<|endoftext|>


<commit_before>#include <UWP/DumperIPC.hpp>

#include <array>
#include <atomic>
#include <thread>
#include <cstdarg>

/// API
namespace IPC
{
/// IPC Message Queue
struct MessageEntry
{
	MessageEntry()
	{
	}

	explicit MessageEntry(const wchar_t* String)
	{
		wcscpy_s(this->String, MessageEntry::StringSize, String);
	}

	static constexpr std::size_t StringSize = 1024;
	wchar_t String[StringSize];
};

template< typename QueueType, std::size_t PoolSize >
class AtomicQueue
{
public:
	using Type = QueueType;
	static constexpr std::size_t MaxSize = PoolSize;

	AtomicQueue()
		:
		Head(0),
		Tail(0)
	{
	}

	~AtomicQueue()
	{
	}

	void Enqueue(const Type& Entry)
	{
		while( Mutex.test_and_set(std::memory_order_acquire) )
		{
			std::this_thread::yield();
		}
		Entries[Tail] = Entry;
		Tail = (Tail + 1) % MaxSize;
		Mutex.clear(std::memory_order_release);
	}

	Type Dequeue()
	{
		while( Mutex.test_and_set(std::memory_order_acquire) )
		{
			std::this_thread::yield();
		}
		Type Temp = Entries[Head];
		Head = (Head + 1) % MaxSize;
		Mutex.clear(std::memory_order_release);
		return Temp;
	}

	std::size_t Size()
	{
		while( Mutex.test_and_set(std::memory_order_acquire) )
		{
			std::this_thread::yield();
		}
		Mutex.clear(std::memory_order_release);
		std::size_t Result = Tail - Head;
		return Result;
	}

	bool Empty()
	{
		return Size() == 0;
	}

private:
	std::array<Type, MaxSize> Entries = {Type()};
	std::size_t Head = 0;
	std::size_t Tail = 0;
	std::atomic_flag Mutex = ATOMIC_FLAG_INIT;
};

////// Shared IPC Region //////////////////////////////////////////////////////
#pragma data_seg("SHARED")
AtomicQueue<MessageEntry, 1024> MessagePool = {};
std::atomic<std::size_t> CurMessageCount = 0;

// The process we are sending our data to
std::atomic<std::uint32_t> ClientProcess(0);

// The target UWP process we wish to dump
std::atomic<std::uint32_t> TargetProcess(0);

std::atomic<std::int32_t> TargetThread(InvalidThread);

#pragma data_seg()
#pragma comment(linker, "/section:SHARED,RWS")
///////////////////////////////////////////////////////////////////////////////

void SetClientProcess(std::uint32_t ProcessID)
{
	ClientProcess = ProcessID;
}

std::uint32_t GetClientProcess()
{
	return ClientProcess;
}

void SetTargetProcess(std::uint32_t ProcessID)
{
	TargetProcess = ProcessID;
}

std::uint32_t GetTargetProcess()
{
	return TargetProcess;
}

IPC_API void SetTargetThread(std::int32_t ThreadID)
{
	TargetThread = ThreadID;
}

IPC_API std::int32_t GetTargetThread()
{
	return TargetThread;
}

IPC_API void ClearTargetThread()
{
	TargetThread = InvalidThread;
}

void PushMessage(const wchar_t* Format, ...)
{
	std::va_list Args;
	MessageEntry Entry;

	va_start(Args, Format);
	vswprintf_s(
		Entry.String,
		Entry.StringSize,
		Format,
		Args
	);
	va_end(Args);

	MessagePool.Enqueue(Entry);
}

std::wstring PopMessage()
{
	MessageEntry Entry = MessagePool.Dequeue();
	return std::wstring(
		Entry.String,
		wcslen(Entry.String)
	);
}

std::size_t MessageCount()
{
	return MessagePool.Size();
}
}
<commit_msg>Rename "AtomicQueue" to "SafeQueue<commit_after>#include <UWP/DumperIPC.hpp>

#include <array>
#include <atomic>
#include <thread>
#include <cstdarg>

/// API
namespace IPC
{
/// IPC Message Queue
struct MessageEntry
{
	MessageEntry()
	{
	}

	explicit MessageEntry(const wchar_t* String)
	{
		wcscpy_s(this->String, MessageEntry::StringSize, String);
	}

	static constexpr std::size_t StringSize = 1024;
	wchar_t String[StringSize];
};

template< typename QueueType, std::size_t PoolSize >
class SafeQueue
{
public:
	using Type = QueueType;
	static constexpr std::size_t MaxSize = PoolSize;

	SafeQueue()
		:
		Head(0),
		Tail(0)
	{
	}

	~SafeQueue()
	{
	}

	void Enqueue(const Type& Entry)
	{
		while( Mutex.test_and_set(std::memory_order_acquire) )
		{
			std::this_thread::yield();
		}
		Entries[Tail] = Entry;
		Tail = (Tail + 1) % MaxSize;
		Mutex.clear(std::memory_order_release);
	}

	Type Dequeue()
	{
		while( Mutex.test_and_set(std::memory_order_acquire) )
		{
			std::this_thread::yield();
		}
		Type Temp = Entries[Head];
		Head = (Head + 1) % MaxSize;
		Mutex.clear(std::memory_order_release);
		return Temp;
	}

	std::size_t Size()
	{
		while( Mutex.test_and_set(std::memory_order_acquire) )
		{
			std::this_thread::yield();
		}
		Mutex.clear(std::memory_order_release);
		std::size_t Result = Tail - Head;
		return Result;
	}

	bool Empty()
	{
		return Size() == 0;
	}

private:
	std::array<Type, MaxSize> Entries = {Type()};
	std::size_t Head = 0;
	std::size_t Tail = 0;
	std::atomic_flag Mutex = ATOMIC_FLAG_INIT;
};

////// Shared IPC Region //////////////////////////////////////////////////////
#pragma data_seg("SHARED")
SafeQueue<MessageEntry, 1024> MessagePool = {};
std::atomic<std::size_t> CurMessageCount = 0;

// The process we are sending our data to
std::atomic<std::uint32_t> ClientProcess(0);

// The target UWP process we wish to dump
std::atomic<std::uint32_t> TargetProcess(0);

std::atomic<std::int32_t> TargetThread(InvalidThread);

#pragma data_seg()
#pragma comment(linker, "/section:SHARED,RWS")
///////////////////////////////////////////////////////////////////////////////

void SetClientProcess(std::uint32_t ProcessID)
{
	ClientProcess = ProcessID;
}

std::uint32_t GetClientProcess()
{
	return ClientProcess;
}

void SetTargetProcess(std::uint32_t ProcessID)
{
	TargetProcess = ProcessID;
}

std::uint32_t GetTargetProcess()
{
	return TargetProcess;
}

IPC_API void SetTargetThread(std::int32_t ThreadID)
{
	TargetThread = ThreadID;
}

IPC_API std::int32_t GetTargetThread()
{
	return TargetThread;
}

IPC_API void ClearTargetThread()
{
	TargetThread = InvalidThread;
}

void PushMessage(const wchar_t* Format, ...)
{
	std::va_list Args;
	MessageEntry Entry;

	va_start(Args, Format);
	vswprintf_s(
		Entry.String,
		Entry.StringSize,
		Format,
		Args
	);
	va_end(Args);

	MessagePool.Enqueue(Entry);
}

std::wstring PopMessage()
{
	MessageEntry Entry = MessagePool.Dequeue();
	return std::wstring(
		Entry.String,
		wcslen(Entry.String)
	);
}

std::size_t MessageCount()
{
	return MessagePool.Size();
}
}
<|endoftext|>