<commit_before>/*
    main.cpp

    This file is part of Kleopatra, the KDE keymanager
    Copyright (c) 2001,2002,2004 Klar�vdalens 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 <config-kleopatra.h>

#include "aboutdata.h"
#include "certmanager.h"

#include "libkleo/kleo/cryptobackendfactory.h"

#ifdef HAVE_USABLE_ASSUAN
# include <uiserver/uiserver.h>
# include <uiserver/assuancommand.h>
#endif

#include <kapplication.h>
#include <kcmdlineargs.h>
#include <kmessagebox.h>
#include <klocale.h>
#include <kglobal.h>
#include <kiconloader.h>

namespace {
    template <typename T>
    boost::shared_ptr<T> make_shared_ptr( T * t ) {
        return t ? boost::shared_ptr<T>( t ) : boost::shared_ptr<T>() ;
    }
}

int main( int argc, char** argv )
{
  AboutData aboutData;

  KCmdLineArgs::init(argc, argv, &aboutData);

  KCmdLineOptions options;
  options.add("external", ki18n("Search for external certificates initially"));
  options.add("query ", ki18n("Initial query string"));
  options.add("import-certificate ", ki18n("Name of certificate file to import"));
  KCmdLineArgs::addCmdLineOptions( options );

  KApplication app;

  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

  KGlobal::locale()->insertCatalog( "libkleopatra" );
  KIconLoader::global()->addAppDir( "libkleopatra" );

  if( !Kleo::CryptoBackendFactory::instance()->smime() ) {
    KMessageBox::error(0,
			i18n( "<qt>The crypto plugin could not be initialized.
"
			      "Certificate Manager will terminate now.</qt>") );
    return -2;
  }

  CertManager* manager = new CertManager( args->isSet("external"),
					  args->getOption("query"),
					  args->getOption("import-certificate") );

  args->clear();
  manager->show();

#ifdef HAVE_USABLE_ASSUAN
  Kleo::UiServer server;
  server.registerCommandFactory( make_shared_ptr( new Kleo::GenericAssuanCommandFactory<Kleo::VerifyEmailCommand> ) );
  server.registerCommandFactory( make_shared_ptr( new Kleo::GenericAssuanCommandFactory<Kleo::DecryptEmailCommand> ) );

  server.start();
#endif

  const int rc = app.exec();

#ifdef HAVE_USABLE_ASSUAN
  server.stop();
  server.waitForStopped();
#endif

  return rc;
}
<commit_msg>Handle Ui Server initalisation problems gracefully.<commit_after>/*
    main.cpp

    This file is part of Kleopatra, the KDE keymanager
    Copyright (c) 2001,2002,2004 Klar�vdalens 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 <config-kleopatra.h>

#include "aboutdata.h"
#include "certmanager.h"

#include "libkleo/kleo/cryptobackendfactory.h"

#ifdef HAVE_USABLE_ASSUAN
# include <uiserver/uiserver.h>
# include <uiserver/assuancommand.h>
#endif

#include <kapplication.h>
#include <kcmdlineargs.h>
#include <kmessagebox.h>
#include <klocale.h>
#include <kglobal.h>
#include <kiconloader.h>

#include <QTextDocument> // for Qt::escape

namespace {
    template <typename T>
    boost::shared_ptr<T> make_shared_ptr( T * t ) {
        return t ? boost::shared_ptr<T>( t ) : boost::shared_ptr<T>() ;
    }
}

int main( int argc, char** argv )
{
  AboutData aboutData;

  KCmdLineArgs::init(argc, argv, &aboutData);

  KCmdLineOptions options;
  options.add("external", ki18n("Search for external certificates initially"));
  options.add("query ", ki18n("Initial query string"));
  options.add("import-certificate ", ki18n("Name of certificate file to import"));
  KCmdLineArgs::addCmdLineOptions( options );

  KApplication app;

  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

  KGlobal::locale()->insertCatalog( "libkleopatra" );
  KIconLoader::global()->addAppDir( "libkleopatra" );

  if( !Kleo::CryptoBackendFactory::instance()->smime() ) {
    KMessageBox::error(0,
			i18n( "<qt>The crypto plugin could not be initialized.
"
			      "Certificate Manager will terminate now.</qt>") );
    return -2;
  }

  CertManager* manager = new CertManager( args->isSet("external"),
					  args->getOption("query"),
					  args->getOption("import-certificate") );

  args->clear();
  manager->show();

  int rc;
#ifdef HAVE_USABLE_ASSUAN
  try {
      Kleo::UiServer server;
      server.registerCommandFactory( make_shared_ptr( new Kleo::GenericAssuanCommandFactory<Kleo::VerifyEmailCommand> ) );
      server.registerCommandFactory( make_shared_ptr( new Kleo::GenericAssuanCommandFactory<Kleo::DecryptEmailCommand> ) );

      server.start();
#endif

      rc = app.exec();

#ifdef HAVE_USABLE_ASSUAN
      server.stop();
      server.waitForStopped();
  } catch ( const std::exception & e ) {
      QMessageBox::information( 0, i18n("GPG UI Server Error"),
                                i18n("<qt>The Kleopatra GPG UI Server Module couldn't be initialized.
"
                                     "The error given was: %1
"
                                     "You can use Kleopatra as a certificate manager, but cryptographic plugins that "
                                     "rely on a GPG UI Server being present might not work correctly, or at all.</qt>",
                                     Qt::escape( QString::fromUtf8( e.what() ) ) ));
      rc = app.exec();
  }
#endif

  return rc;
}
<|endoftext|>


<commit_before>#include <QtGui/QGuiApplication>
#include <QtQml>
#include <QtQuick/QQuickView>
#include <QJsonDocument>
#include <QJsonArray>
#include <QSqlQuery>
#include "kernel.h"
#include "errorobject.h"
#include "resource.h"
#include "ilwistype.h"
#include "catalog.h"
#include "mastercatalog.h"
#include "catalogview.h"
#include "ilwiscontext.h"
#include "models/catalogfiltermodel.h"
#include "models/mastercatalogmodel.h"
#include "models/operationmodel.h"
#include "models/operationcatalogmodel.h"
#include "models/usermessagehandler.h"
#include "applicationformexpressionparser.h"
#include "models/tranquilizerhandler.h"
#include "models/visualizationmanager.h"
#include "models/objectvisualizationmodel.h"
#include "models/ilwisobjectmodel.h"
#include "models/attributemodel.h"
#include "models/domainitemmodel.h"
#include "models/operationsbykeymodel.h"
#include "models/uicontextmodel.h"
#include "models/visualizationmanager.h"

#define TEST_WORKINGDIR QString("file:///d:/projects/ilwis/Ilwis4/testdata")

using namespace Ilwis;
//using namespace Desktopclient;

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

        QQmlApplicationEngine engine;
        QQmlContext *ctx = engine.rootContext();
        Ilwis::initIlwis();

        QFileInfo ilwisroot = context()->ilwisFolder();
        QString qmlpluginpath = ilwisroot.absoluteFilePath() + "/extensions/ui";

        engine.addImportPath(qmlpluginpath);
        engine.addPluginPath(qmlpluginpath);

        qmlRegisterType<MasterCatalogModel>("MasterCatalogModel",1,0,"MasterCatalogModel");
        qmlRegisterType<CatalogModel>("CatalogModel",1,0,"CatalogModel");
        qmlRegisterType<ResourceModel>("ResourceModel",1,0,"ResourceModel");
        qmlRegisterType<OperationCatalogModel>("OperationCatalogModel",1,0,"OperationCatalogModel");
        qmlRegisterType<OperationModel>("OperationModel",1,0,"OperationModel");
        qmlRegisterType<ApplicationFormExpressionParser>("ApplicationFormExpressionParser",1,0,"FormBuilder");
        qmlRegisterType<UserMessageHandler>("UserMessageHandler",1,0,"UserMessageHandler");
        qmlRegisterType<MessageModel>("MessageModel",1,0,"MessageModel");
        qmlRegisterType<TranquilizerHandler>("TranquilizerHandler",1,0, "TranquilizerHandler");
        qmlRegisterType<TranquilizerModel>("TranquilizerModel",1,0, "TranquilizerModel");
        qmlRegisterType<VisualizationManager>("VisualizationManager",1,0,"VisualizationManager");
        qmlRegisterType<ObjectVisualizationModel>("ObjectVisualizationModel",1,0,"ObjectVisualizationModel");
        qmlRegisterType<IlwisObjectModel>("IlwisObjectModel",1,0,"IlwisObjectModel");
        qmlRegisterType<AttributeModel>("AttributeModel",1,0,"AttributeModel");
        qmlRegisterType<DomainItemModel>("DomainItemModel",1,0,"DomainItemModel");
        qmlRegisterType<OperationsByKeyModel>("OperationsByKeyModel",1,0,"OperationsByKeyModel");
        qmlRegisterType<UIContextModel>("UIContextModel", 1,0, "UIContextModel");
        qmlRegisterType<PropertyEditorMetaData>("PropertyEditorMetaData", 1,0, "PropertyEditorMetaData");

        MasterCatalogModel mastercatalogmodel(ctx);

        ApplicationFormExpressionParser formbuilder;
        UserMessageHandler messageHandler;
        OperationCatalogModel operations;
        TranquilizerHandler tranquilizers;
        UIContextModel uiContext;
        uiContext.qmlContext(ctx);

        //uiContext.addPropertyEditor(itLINE,"Style",PropertyEditorMetaData("Style", QUrl("http://someurl/bla.qml")));
        uiContext.addPropertyEditor(itLINE,TR("Representation"),PropertyEditorMetaData(TR("Representation"), QUrl("RepresentationSetter.qml")));

        ctx->setContextProperty("mastercatalog", &mastercatalogmodel);
        ctx->setContextProperty("formbuilder", &formbuilder);
        ctx->setContextProperty("messagehandler", &messageHandler);
        ctx->setContextProperty("tranquilizerHandler", &tranquilizers);
        ctx->setContextProperty("operations", &operations);
        ctx->setContextProperty("uicontext", &uiContext);

        mastercatalogmodel.connect(&operations, &OperationCatalogModel::updateCatalog,&mastercatalogmodel, &MasterCatalogModel::updateCatalog );
        messageHandler.connect(kernel()->issues().data(), &IssueLogger::updateIssues,&messageHandler, &UserMessageHandler::addMessage );
        tranquilizers.connect(kernel(), &Kernel::updateTranquilizer, &tranquilizers, &TranquilizerHandler::updateTranquilizer,Qt::DirectConnection);
        tranquilizers.connect(kernel(), &Kernel::createTranquilizer, &tranquilizers, &TranquilizerHandler::createTranquilizer,Qt::DirectConnection);
        tranquilizers.connect(kernel(), &Kernel::removeTranquilizer, &tranquilizers, &TranquilizerHandler::removeTranquilizer);

        engine.load("qml/DesktopClient.qml");

        QObject *topLevel = engine.rootObjects().value(0);
        QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel);
        if ( !window ) {
            qWarning("Error: Your root item has to be a Window.");
            return -1;
        }
        mastercatalogmodel.root(window);
        window->show();
        return app.exec();
    }catch (const ErrorObject& err){
        qDebug() << err.message();
    }

    return 0;

}
<commit_msg>added new types<commit_after>#include <QtGui/QGuiApplication>
#include <QtQml>
#include <QtQuick/QQuickView>
#include <QJsonDocument>
#include <QJsonArray>
#include <QSqlQuery>
#include "kernel.h"
#include "errorobject.h"
#include "resource.h"
#include "ilwistype.h"
#include "catalog.h"
#include "mastercatalog.h"
#include "catalogview.h"
#include "ilwiscontext.h"
#include "models/catalogfiltermodel.h"
#include "models/mastercatalogmodel.h"
#include "models/operationmodel.h"
#include "models/operationcatalogmodel.h"
#include "models/usermessagehandler.h"
#include "applicationformexpressionparser.h"
#include "models/tranquilizerhandler.h"
#include "models/visualizationmanager.h"
#include "models/objectvisualizationmodel.h"
#include "models/ilwisobjectmodel.h"
#include "models/attributemodel.h"
#include "models/domainitemmodel.h"
#include "models/operationsbykeymodel.h"
#include "models/uicontextmodel.h"
#include "models/visualizationmanager.h"
//#include "ilwiscoreui/propertyeditors/representationsetter.h"
#include "ilwiscoreui/propertyeditors/representationsetter.h"

#define TEST_WORKINGDIR QString("file:///d:/projects/ilwis/Ilwis4/testdata")

using namespace Ilwis;
//using namespace Desktopclient;

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

        QQmlApplicationEngine engine;
        QQmlContext *ctx = engine.rootContext();
        Ilwis::initIlwis();

        QFileInfo ilwisroot = context()->ilwisFolder();
        QString qmlpluginpath = ilwisroot.absoluteFilePath() + "/extensions/ui";

        engine.addImportPath(qmlpluginpath);
        engine.addPluginPath(qmlpluginpath);

        qmlRegisterType<MasterCatalogModel>("MasterCatalogModel",1,0,"MasterCatalogModel");
        qmlRegisterType<CatalogModel>("CatalogModel",1,0,"CatalogModel");
        qmlRegisterType<ResourceModel>("ResourceModel",1,0,"ResourceModel");
        qmlRegisterType<OperationCatalogModel>("OperationCatalogModel",1,0,"OperationCatalogModel");
        qmlRegisterType<OperationModel>("OperationModel",1,0,"OperationModel");
        qmlRegisterType<ApplicationFormExpressionParser>("ApplicationFormExpressionParser",1,0,"FormBuilder");
        qmlRegisterType<UserMessageHandler>("UserMessageHandler",1,0,"UserMessageHandler");
        qmlRegisterType<MessageModel>("MessageModel",1,0,"MessageModel");
        qmlRegisterType<TranquilizerHandler>("TranquilizerHandler",1,0, "TranquilizerHandler");
        qmlRegisterType<TranquilizerModel>("TranquilizerModel",1,0, "TranquilizerModel");
        qmlRegisterType<VisualizationManager>("VisualizationManager",1,0,"VisualizationManager");
        qmlRegisterType<ObjectVisualizationModel>("ObjectVisualizationModel",1,0,"ObjectVisualizationModel");
        qmlRegisterType<IlwisObjectModel>("IlwisObjectModel",1,0,"IlwisObjectModel");
        qmlRegisterType<AttributeModel>("AttributeModel",1,0,"AttributeModel");
        qmlRegisterType<DomainItemModel>("DomainItemModel",1,0,"DomainItemModel");
        qmlRegisterType<OperationsByKeyModel>("OperationsByKeyModel",1,0,"OperationsByKeyModel");
        qmlRegisterType<UIContextModel>("UIContextModel", 1,0, "UIContextModel");
        qmlRegisterType<PropertyEditorMetaData>("PropertyEditorMetaData", 1,0, "PropertyEditorMetaData");

       // qmlRegisterType<PropertyEditor>("PropertyEditor", 1,0, "PropertyEditor");
        qmlRegisterType<RepresentationSetter>("RepresentationSetter", 1,0, "RepresentationSetter");

        MasterCatalogModel mastercatalogmodel(ctx);

        ApplicationFormExpressionParser formbuilder;
        UserMessageHandler messageHandler;
        OperationCatalogModel operations;
        TranquilizerHandler tranquilizers;
        UIContextModel uiContext;
        uiContext.qmlContext(ctx);

        //uiContext.addPropertyEditor(itLINE,"Style",PropertyEditorMetaData("Style", QUrl("http://someurl/bla.qml")));
        uiContext.addPropertyEditor(itLINE,TR("Representation"),PropertyEditorMetaData(TR("Representation"), QUrl("RepresentationProperties.qml")));

        ctx->setContextProperty("mastercatalog", &mastercatalogmodel);
        ctx->setContextProperty("formbuilder", &formbuilder);
        ctx->setContextProperty("messagehandler", &messageHandler);
        ctx->setContextProperty("tranquilizerHandler", &tranquilizers);
        ctx->setContextProperty("operations", &operations);
        ctx->setContextProperty("uicontext", &uiContext);

        mastercatalogmodel.connect(&operations, &OperationCatalogModel::updateCatalog,&mastercatalogmodel, &MasterCatalogModel::updateCatalog );
        messageHandler.connect(kernel()->issues().data(), &IssueLogger::updateIssues,&messageHandler, &UserMessageHandler::addMessage );
        tranquilizers.connect(kernel(), &Kernel::updateTranquilizer, &tranquilizers, &TranquilizerHandler::updateTranquilizer,Qt::DirectConnection);
        tranquilizers.connect(kernel(), &Kernel::createTranquilizer, &tranquilizers, &TranquilizerHandler::createTranquilizer,Qt::DirectConnection);
        tranquilizers.connect(kernel(), &Kernel::removeTranquilizer, &tranquilizers, &TranquilizerHandler::removeTranquilizer);

        engine.load("qml/DesktopClient.qml");

        QObject *topLevel = engine.rootObjects().value(0);
        QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel);
        if ( !window ) {
            qWarning("Error: Your root item has to be a Window.");
            return -1;
        }
        mastercatalogmodel.root(window);
        window->show();
        return app.exec();
    }catch (const ErrorObject& err){
        qDebug() << err.message();
    }

    return 0;

}
<|endoftext|>


<commit_before>#pragma once

#include <ostream>
#include <string>

#include <boost/algorithm/string.hpp>
#include <boost/variant.hpp>

#include "blackhole/detail/stream/stream.hpp"
#include "blackhole/formatter/map/value.hpp"
#include "blackhole/formatter/string/parser.hpp"
#include "blackhole/record.hpp"

namespace blackhole {

namespace formatter {

namespace string {

class variadic_visitor_t : public boost::static_visitor<> {
    std::ostringstream& stream;

public:
    variadic_visitor_t(std::ostringstream& stream) :
        stream(stream)
    {}

    template<typename T>
    void operator()(const T& value) const {
        stream << value;
    }

    void operator()(const std::string& value) const {
        stream << "'" << value << "'";
    }
};

class visitor_t : public boost::static_visitor<> {
    stickystream_t& stream;
    const mapping::value_t& mapper;
    const attribute::set_view_t& view;

public:
    visitor_t(stickystream_t& stream,
              const mapping::value_t& mapper,
              const attribute::set_view_t& view) :
        stream(stream),
        mapper(mapper),
        view(view)
    {}

    void operator()(const literal_t& literal) {
        stream.rdbuf()->storage()->append(literal.value);
    }

    void operator()(const placeholder::required_t& ph) {
        if (auto attribute = view.find(ph.name)) {
            mapper(stream, ph.name, attribute->value);
            return;
        }

        throw error_t("required attribute '%s' was not provided", ph.name);
    }

    void operator()(const placeholder::optional_t& ph) {
        if (auto attribute = view.find(ph.name)) {
            stream.rdbuf()->storage()->append(ph.prefix);
            mapper(stream, ph.name, attribute->value);
            stream.rdbuf()->storage()->append(ph.suffix);
        }
    }

    //!@todo: Test separator/pattern.
    void operator()(const placeholder::variadic_t& ph) {
        std::vector<std::string> passed;
        passed.reserve(view.upper_size());

        //!@todo: Call begin() & end() with parameter.
        for (auto it = view.begin(); it != view.end(); ++it) {
            const std::string& name = it->first;
            const attribute_t& attribute = it->second;

            //!@todo: This code needs some optimization love.
            std::ostringstream stream;
            stream << "'" << name << "': ";
            variadic_visitor_t visitor(stream);
            boost::apply_visitor(visitor, attribute.value);
            passed.push_back(stream.str());
        }

        if (!passed.empty()) {
            stream.rdbuf()->storage()->append(ph.prefix);
            stream.rdbuf()->storage()->append(
                boost::algorithm::join(passed, ph.separator)
            );
            stream.rdbuf()->storage()->append(ph.suffix);
        }
    }
};

} // namespace string

} // namespace formatter

} // namespace blackhole
<commit_msg>[Tasks] Priority.<commit_after>#pragma once

#include <ostream>
#include <string>

#include <boost/algorithm/string.hpp>
#include <boost/variant.hpp>

#include "blackhole/detail/stream/stream.hpp"
#include "blackhole/formatter/map/value.hpp"
#include "blackhole/formatter/string/parser.hpp"
#include "blackhole/record.hpp"

namespace blackhole {

namespace formatter {

namespace string {

class variadic_visitor_t : public boost::static_visitor<> {
    std::ostringstream& stream;

public:
    variadic_visitor_t(std::ostringstream& stream) :
        stream(stream)
    {}

    template<typename T>
    void operator()(const T& value) const {
        stream << value;
    }

    void operator()(const std::string& value) const {
        stream << "'" << value << "'";
    }
};

class visitor_t : public boost::static_visitor<> {
    stickystream_t& stream;
    const mapping::value_t& mapper;
    const attribute::set_view_t& view;

public:
    visitor_t(stickystream_t& stream,
              const mapping::value_t& mapper,
              const attribute::set_view_t& view) :
        stream(stream),
        mapper(mapper),
        view(view)
    {}

    void operator()(const literal_t& literal) {
        stream.rdbuf()->storage()->append(literal.value);
    }

    void operator()(const placeholder::required_t& ph) {
        if (auto attribute = view.find(ph.name)) {
            mapper(stream, ph.name, attribute->value);
            return;
        }

        throw error_t("required attribute '%s' was not provided", ph.name);
    }

    void operator()(const placeholder::optional_t& ph) {
        if (auto attribute = view.find(ph.name)) {
            stream.rdbuf()->storage()->append(ph.prefix);
            mapper(stream, ph.name, attribute->value);
            stream.rdbuf()->storage()->append(ph.suffix);
        }
    }

    //!@todo: 1. Test pattern.
    void operator()(const placeholder::variadic_t& ph) {
        std::vector<std::string> passed;
        passed.reserve(view.upper_size());

        //!@todo: 3. Call begin() & end() with parameter.
        for (auto it = view.begin(); it != view.end(); ++it) {
            const std::string& name = it->first;
            const attribute_t& attribute = it->second;

            //!@todo: 2. This code needs some optimization love.
            std::ostringstream stream;
            stream << "'" << name << "': ";
            variadic_visitor_t visitor(stream);
            boost::apply_visitor(visitor, attribute.value);
            passed.push_back(stream.str());
        }

        if (!passed.empty()) {
            stream.rdbuf()->storage()->append(ph.prefix);
            stream.rdbuf()->storage()->append(
                boost::algorithm::join(passed, ph.separator)
            );
            stream.rdbuf()->storage()->append(ph.suffix);
        }
    }
};

} // namespace string

} // namespace formatter

} // namespace blackhole
<|endoftext|>


<commit_before>/*
 * Generalized Window Function Wrapper for Jamoma DSP
 * Copyright © 2010 by Timothy Place
 *
 * License: This code is licensed under the terms of the "New BSD License"
 * http://creativecommons.org/licenses/BSD/
 */

#include "WindowFunction.h"

#define thisTTClass			WindowFunction
#define thisTTClassName		"WindowFunction"
#define thisTTClassTags		"audio, processor"

TT_AUDIO_CONSTRUCTOR,
	mFunctionObject(NULL),
	mNumPoints(8192),
	mPadding(0)
{
	addAttributeWithSetter(Function,	kTypeSymbol);
	addAttributeWithSetter(NumPoints,	kTypeUInt32);
	addAttributeWithSetter(Mode,		kTypeSymbol);
	addAttributeWithSetter(Padding,		kTypeUInt32);

	addMessageWithArgument(getFunctions);
	addMessageWithArgument(setParameter);

	setAttributeValue(TT("function"), TT("rectangular"));
	setAttributeValue(TT("mode"), TT("lookup"));
}

WindowFunction::~WindowFunction()
{
	delete mFunctionObject;
}

TTErr WindowFunction::setFunction(const TTValue& function)
{
	TTErr err;

	mFunction = function;
	err = TTObjectInstantiate(mFunction, &mFunctionObject, maxNumChannels);
	if (!err)
		err = fill();
	return err;
}

TTErr WindowFunction::setParameter(TTValue& aParameterValueForTheFunction)
{
	TTErr err;

	if (aParameterValueForTheFunction.getSize() < 2)
		err = kTTErrWrongNumValues;
	else {
		TTSymbolPtr parameterName = aParameterValueForTheFunction;
		TTValue		v;

		v.copyFrom(aParameterValueForTheFunction, 1);
		err = mFunctionObject->setAttributeValue(parameterName, v);
	}
	aParameterValueForTheFunction.clear();
	return err;
}

TTErr WindowFunction::fill()
{
	mLookupTable.assign(mNumPoints, 0.0);
	if (mFunctionObject) {
		TTInt32 numPoints = mNumPoints-(mPadding*2);

		TTLimitMin<TTInt32>(numPoints, 0);
		for (TTInt32 i=0; i<numPoints; i++)
			mFunctionObject->calculate(i/TTFloat64(numPoints-1), mLookupTable[i+mPadding]);
	}
	else
		mLookupTable.assign(mNumPoints, 0.0);

	return kTTErrNone;
}

TTErr WindowFunction::setNumPoints(const TTValue& numPoints)
{
	return doSetNumPoints(numPoints);
}

TTErr WindowFunction::doSetNumPoints(const TTUInt32 numPoints)
{
	mNumPoints = numPoints;
	mLookupTable.resize(mNumPoints);
	return fill();
}

TTErr WindowFunction::setPadding(const TTValue& padding)
{
	mPadding = padding;
	return fill();
}

TTErr WindowFunction::setMode(const TTValue& mode)
{
	mMode = mode;
	if (mMode == TT("apply")) {
		setProcessMethod(processApply);
		setCalculateMethod(lookupValue);
	}
	else if (mMode == TT("generate")) {
		setProcessMethod(processGenerate);
		setCalculateMethod(calculateValue);
	}
	else {
		setProcessMethod(processLookup);
		setCalculateMethod(lookupValue);
	}
	return kTTErrNone;
}

TTErr WindowFunction::getFunctions(TTValue& listOfWindowTypesToReturn)
{
	return TTGetRegisteredClassNamesForTags(listOfWindowTypesToReturn, TT("window"));
}

#if 0
#pragma mark -
#pragma mark Process Routines
#endif

inline TTErr WindowFunction::calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data)
{
	return mFunctionObject->calculate(x, y);
}

inline TTErr WindowFunction::lookupValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data)
{
	y = mLookupTable[TTClip(x, 0.0, 1.0) * mNumPoints];
	return kTTErrNone;
}

TTErr WindowFunction::processGenerate(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
	return mFunctionObject->process(inputs, outputs);
}

TTErr WindowFunction::processLookup(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
	TT_WRAP_CALCULATE_METHOD(lookupValue)
}

TTErr WindowFunction::processApply(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
	TTAudioSignal&		in = inputs->getSignal(0);
	TTAudioSignal&		out = outputs->getSignal(0);
	TTUInt16			vs = in.getVectorSizeAsInt();
	TTSampleValuePtr	inSample;
	TTSampleValuePtr	outSample;
	TTUInt16			numChannels = TTAudioSignal::getMinChannelCount(in, out);
	TTUInt16			channel;

	// In 'apply' mode we automatically update the lookup table size to the vector size
	// This is slow, but hopefully only happens once (if ever)
	if (vs != mNumPoints)
		doSetNumPoints(vs);

	for (channel=0; channel<numChannels; channel++) {
		inSample = in.mSampleVectors[channel];
		outSample = out.mSampleVectors[channel];

		for (TTUInt32 i=0; i<vs; i++)
			*outSample++ = (*inSample++) * mLookupTable[i];
	}
	return kTTErrNone;
}

<commit_msg>WindowFunction: fix for parameter changes not updating the lookup table.<commit_after>/*
 * Generalized Window Function Wrapper for Jamoma DSP
 * Copyright © 2010 by Timothy Place
 *
 * License: This code is licensed under the terms of the "New BSD License"
 * http://creativecommons.org/licenses/BSD/
 */

#include "WindowFunction.h"

#define thisTTClass			WindowFunction
#define thisTTClassName		"WindowFunction"
#define thisTTClassTags		"audio, processor"

TT_AUDIO_CONSTRUCTOR,
	mFunctionObject(NULL),
	mNumPoints(8192),
	mPadding(0)
{
	addAttributeWithSetter(Function,	kTypeSymbol);
	addAttributeWithSetter(NumPoints,	kTypeUInt32);
	addAttributeWithSetter(Mode,		kTypeSymbol);
	addAttributeWithSetter(Padding,		kTypeUInt32);

	addMessageWithArgument(getFunctions);
	addMessageWithArgument(setParameter);

	setAttributeValue(TT("function"), TT("rectangular"));
	setAttributeValue(TT("mode"), TT("lookup"));
}

WindowFunction::~WindowFunction()
{
	delete mFunctionObject;
}

TTErr WindowFunction::setFunction(const TTValue& function)
{
	TTErr err;

	mFunction = function;
	err = TTObjectInstantiate(mFunction, &mFunctionObject, maxNumChannels);
	if (!err)
		err = fill();
	return err;
}

TTErr WindowFunction::setParameter(TTValue& aParameterValueForTheFunction)
{
	TTErr err;

	if (aParameterValueForTheFunction.getSize() < 2)
		err = kTTErrWrongNumValues;
	else {
		TTSymbolPtr parameterName = aParameterValueForTheFunction;
		TTValue		v;

		v.copyFrom(aParameterValueForTheFunction, 1);
		err = mFunctionObject->setAttributeValue(parameterName, v);
		if (!err)
			fill();
	}
	aParameterValueForTheFunction.clear();
	return err;
}

TTErr WindowFunction::fill()
{
	mLookupTable.assign(mNumPoints, 0.0);
	if (mFunctionObject) {
		TTInt32 numPoints = mNumPoints-(mPadding*2);

		TTLimitMin<TTInt32>(numPoints, 0);
		for (TTInt32 i=0; i<numPoints; i++)
			mFunctionObject->calculate(i/TTFloat64(numPoints-1), mLookupTable[i+mPadding]);
	}
	else
		mLookupTable.assign(mNumPoints, 0.0);

	return kTTErrNone;
}

TTErr WindowFunction::setNumPoints(const TTValue& numPoints)
{
	return doSetNumPoints(numPoints);
}

TTErr WindowFunction::doSetNumPoints(const TTUInt32 numPoints)
{
	mNumPoints = numPoints;
	mLookupTable.resize(mNumPoints);
	return fill();
}

TTErr WindowFunction::setPadding(const TTValue& padding)
{
	mPadding = padding;
	return fill();
}

TTErr WindowFunction::setMode(const TTValue& mode)
{
	mMode = mode;
	if (mMode == TT("apply")) {
		setProcessMethod(processApply);
		setCalculateMethod(lookupValue);
	}
	else if (mMode == TT("generate")) {
		setProcessMethod(processGenerate);
		setCalculateMethod(calculateValue);
	}
	else {
		setProcessMethod(processLookup);
		setCalculateMethod(lookupValue);
	}
	return kTTErrNone;
}

TTErr WindowFunction::getFunctions(TTValue& listOfWindowTypesToReturn)
{
	return TTGetRegisteredClassNamesForTags(listOfWindowTypesToReturn, TT("window"));
}

#if 0
#pragma mark -
#pragma mark Process Routines
#endif

inline TTErr WindowFunction::calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data)
{
	return mFunctionObject->calculate(x, y);
}

inline TTErr WindowFunction::lookupValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data)
{
	y = mLookupTable[TTClip(x, 0.0, 1.0) * mNumPoints];
	return kTTErrNone;
}

TTErr WindowFunction::processGenerate(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
	return mFunctionObject->process(inputs, outputs);
}

TTErr WindowFunction::processLookup(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
	TT_WRAP_CALCULATE_METHOD(lookupValue)
}

TTErr WindowFunction::processApply(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
	TTAudioSignal&		in = inputs->getSignal(0);
	TTAudioSignal&		out = outputs->getSignal(0);
	TTUInt16			vs = in.getVectorSizeAsInt();
	TTSampleValuePtr	inSample;
	TTSampleValuePtr	outSample;
	TTUInt16			numChannels = TTAudioSignal::getMinChannelCount(in, out);
	TTUInt16			channel;

	// In 'apply' mode we automatically update the lookup table size to the vector size
	// This is slow, but hopefully only happens once (if ever)
	if (vs != mNumPoints)
		doSetNumPoints(vs);

	for (channel=0; channel<numChannels; channel++) {
		inSample = in.mSampleVectors[channel];
		outSample = out.mSampleVectors[channel];

		for (TTUInt32 i=0; i<vs; i++)
			*outSample++ = (*inSample++) * mLookupTable[i];
	}
	return kTTErrNone;
}

<|endoftext|>


<commit_before>#include "core/gameboy.h"
#include "core/display.h"

#include <stdio.h>
#include <stdlib.h>

#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>

static void key_callback(GLFWwindow *window, int key, int scancode, int action, int mode);

void render_loop(Gameboy &gb)
{
  //
  // Set up window
  //
  const unsigned int width = Display::width * 5;
  const unsigned int height = Display::height * 5;
  if (!glfwInit()) {
    fprintf(stderr, "Failed to initialise GLFW\n");
    abort();
  }

  glfwWindowHint(GLFW_SAMPLES, 4);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

  GLFWwindow *window = glfwCreateWindow(width, height, "Gameboy Emulator", NULL, NULL);
  if (window == NULL) {
    fprintf(stderr, "Failed to open window.\n");
    glfwTerminate();
    abort();
  }
  glfwMakeContextCurrent(window);
  glfwSetWindowUserPointer(window, &gb);
  glfwSetKeyCallback(window, key_callback);

  glewExperimental = true;
  if (glewInit() != GLEW_OK) {
    fprintf(stderr, "Failed to initialise GLEW.\n");
    abort();
  }

  //
  // OpenGL settings
  //
  glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  gluOrtho2D(0, width, height, 0);

  //
  // Shaders
  //
  const GLchar *vertex_shader_source =
    "#version 330 core\n"
    "layout (location = 0) in vec2 position;"
    "layout (location = 1) in vec2 texCoord;"
    "out vec2 TexCoord;"
    "void main()"
    "{"
    "  gl_Position = vec4(position, 0.0, 1.0);"
    "  TexCoord = texCoord;"
    "}";

  const GLchar *fragment_shader_source =
    "#version 330 core\n"
    "in vec2 TexCoord;"
    "out vec4 colour;"
    "uniform sampler2D display;"
    "void main()"
    "{"
    "  colour = texture(display, TexCoord);"
    "}";

  GLuint vertex_shader = glCreateShader(GL_VERTEX_SHADER);
  glShaderSource(vertex_shader, 1, &vertex_shader_source, NULL);
  glCompileShader(vertex_shader);
  GLint status;
  glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &status);
  if (!status)
  {
    char error_buffer[512];
    glGetShaderInfoLog(vertex_shader, 512, NULL, error_buffer);
    fprintf(stderr, "Vertex shader error:\n%s\n", error_buffer);
    abort();
  }

  GLuint fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
  glShaderSource(fragment_shader, 1, &fragment_shader_source, NULL);
  glCompileShader(fragment_shader);
  glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &status);
  if (!status)
  {
    char error_buffer[512];
    glGetShaderInfoLog(fragment_shader, 512, NULL, error_buffer);
    fprintf(stderr, "Fragment shader error:\n%s\n", error_buffer);
    abort();
  }

  GLuint shader_program = glCreateProgram();
  glAttachShader(shader_program, vertex_shader);
  glAttachShader(shader_program, fragment_shader);
  glLinkProgram(shader_program);
  glGetProgramiv(shader_program, GL_LINK_STATUS, &status);
  if (!status)
  {
    char error_buffer[512];
    glGetProgramInfoLog(shader_program, 512, NULL, error_buffer);
    fprintf(stderr, "Shader link error:\n%s\n", error_buffer);
    abort();
  }
  glUseProgram(shader_program);

  //
  // Buffers
  //
  GLfloat display_vertices[] = {
    // Pos          Tex
   -1.0f,-1.0f,  0.0f, 1.0f,
   -1.0f, 1.0f,  0.0f, 0.0f,
    1.0f,-1.0f,  1.0f, 1.0f,
    1.0f, 1.0f,  1.0f, 0.0f,
    1.0f,-1.0f,  1.0f, 1.0f,
   -1.0f, 1.0f,  0.0f, 0.0f,
  };

  GLuint vao, vbo;
  glGenVertexArrays(1, &vao);
  glGenBuffers(1, &vbo);

  glBindVertexArray(vao);

  glBindBuffer(GL_ARRAY_BUFFER, vbo);
  glBufferData(GL_ARRAY_BUFFER, sizeof(display_vertices), display_vertices, GL_STATIC_DRAW);

  // Position attribute
  glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4*sizeof(GLfloat), 0);
  glEnableVertexAttribArray(0);

  // TexCoord attribute
  glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4*sizeof(GLfloat), (GLvoid*)(2*sizeof(GLfloat)));
  glEnableVertexAttribArray(1);

  //
  // Texture
  //
  GLuint texture;
  glGenTextures(1, &texture);
  glBindTexture(GL_TEXTURE_2D, texture);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  // Uncomment to change display FPS
  //  glfwSwapInterval(0);
  while (!glfwWindowShouldClose(window))
  {
    for (int i=0; i<10000; i++)
    {
      gb.step();
    }

    glClear(GL_COLOR_BUFFER_BIT);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, Display::width, Display::height, 0, GL_RGB, GL_UNSIGNED_BYTE, gb.get_framebuffer());
    glUniform1i(glGetUniformLocation(shader_program, "display"), 0);
    glDrawArrays(GL_TRIANGLES, 0, 6);
    glfwSwapBuffers(window);
    glfwPollEvents();
  }
}

void key_callback(GLFWwindow *window, int key, int scancode, int action, int mode)
{
  Gameboy *gb = (Gameboy *)glfwGetWindowUserPointer(window);
  bool pressed = (action != GLFW_RELEASE);
  switch (key)
  {
    case GLFW_KEY_UP:
      pressed ? gb->button_pressed(Joypad::Button::UP) :
                gb->button_released(Joypad::Button::UP);
      break;
    case GLFW_KEY_DOWN:
      pressed ? gb->button_pressed(Joypad::Button::DOWN) :
                gb->button_released(Joypad::Button::DOWN);
      break;
    case GLFW_KEY_LEFT:
      pressed ? gb->button_pressed(Joypad::Button::LEFT) :
                gb->button_released(Joypad::Button::LEFT);
      break;
    case GLFW_KEY_RIGHT:
      pressed ? gb->button_pressed(Joypad::Button::RIGHT) :
                gb->button_released(Joypad::Button::RIGHT);
      break;
    case GLFW_KEY_Z:
      pressed ? gb->button_pressed(Joypad::Button::A) :
                gb->button_released(Joypad::Button::A);
      break;
    case GLFW_KEY_X:
      pressed ? gb->button_pressed(Joypad::Button::B) :
                gb->button_released(Joypad::Button::B);
      break;
    case GLFW_KEY_ENTER:
      pressed ? gb->button_pressed(Joypad::Button::START) :
                gb->button_released(Joypad::Button::START);
      break;
    case GLFW_KEY_BACKSPACE:
      pressed ? gb->button_pressed(Joypad::Button::SELECT) :
                gb->button_released(Joypad::Button::SELECT);
      break;
  }
}
<commit_msg>GLFW: Make renderer OpenGL ES compatible<commit_after>#include "core/gameboy.h"
#include "core/display.h"

#include <stdio.h>
#include <stdlib.h>

#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>

static void key_callback(GLFWwindow *window, int key, int scancode, int action, int mode);

GLuint compile_shader(GLenum type, const char* data) {
  GLuint shader = glCreateShader(type);
  glShaderSource(shader, 1, &data, NULL);
  glCompileShader(shader);

  GLint compile_status;
  glGetShaderiv(shader, GL_COMPILE_STATUS, &compile_status);
  if (compile_status != GL_TRUE) {
    char buffer[1024];
    GLsizei length;
    glGetShaderInfoLog(shader, sizeof(buffer), &length, &buffer[0]);
    fprintf(stderr, "Shader failed to compile: %s\n", buffer);
    return 0;
  }

  return shader;
}

GLuint link_program(GLuint frag_shader, GLuint vert_shader) {
  GLuint program = glCreateProgram();
  glAttachShader(program, frag_shader);
  glAttachShader(program, vert_shader);
  glLinkProgram(program);

  GLint link_status;
  glGetProgramiv(program, GL_LINK_STATUS, &link_status);
  if (link_status != GL_TRUE) {
    char buffer[1024];
    GLsizei length;
    glGetProgramInfoLog(program, sizeof(buffer), &length, &buffer[0]);
    fprintf(stderr, "Program failed to link: %s\n", buffer);
    return 0;
  }

  return program;
}

const GLchar *kVertexShaderSource =
    "#version 100\n"
    "attribute vec2 a_position;"
    "attribute vec2 a_texcoord;"
    "varying vec2 v_texcoord;"
    "void main() {"
    "  gl_Position = vec4(a_position, 0.0, 1.0);"
    "  v_texcoord = a_texcoord;"
    "}";

const GLchar *kFragmentShaderSource =
    "#version 100\n"
    "precision mediump float;"
    "varying vec2 v_texcoord;"
    "uniform sampler2D u_texture;"
    "void main() {"
    "  gl_FragColor = texture2D(u_texture, v_texcoord);"
    "}";

struct Vertex {
  GLfloat pos[2];
  GLfloat tex[2];
};

const Vertex kDisplayVertices[] = {
 {{-1.0f,-1.0f},  {0.0f, 1.0f}},
 {{-1.0f, 1.0f},  {0.0f, 0.0f}},
 {{ 1.0f,-1.0f},  {1.0f, 1.0f}},
 {{ 1.0f, 1.0f},  {1.0f, 0.0f}},
 {{ 1.0f,-1.0f},  {1.0f, 1.0f}},
 {{-1.0f, 1.0f},  {0.0f, 0.0f}},
};

GLFWwindow *initgl(int32_t width, int32_t height) {
  if (!glfwInit()) {
    fprintf(stderr, "Failed to initialise GLFW\n");
    abort();
  }

  GLFWwindow *window = glfwCreateWindow(width, height, "Gameboy Emulator", NULL, NULL);
  if (window == NULL) {
    fprintf(stderr, "Failed to open window.\n");
    abort();
  }
  glfwMakeContextCurrent(window);
  glfwSetKeyCallback(window, key_callback);

  glewExperimental = true;
  if (glewInit() != GLEW_OK) {
    fprintf(stderr, "Failed to initialise GLEW.\n");
    abort();
  }

  glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
  return window;
}

GLuint init_shaders() {
  printf("opengl version: (%s)\n", glGetString(GL_VERSION));
  GLuint vertex_shader = compile_shader(GL_VERTEX_SHADER, kVertexShaderSource);
  if (!vertex_shader)
    abort();

  GLuint frag_shader = compile_shader(GL_FRAGMENT_SHADER, kFragmentShaderSource);
  if (!frag_shader)
    abort();

  GLuint program = link_program(frag_shader, vertex_shader);
  if (!program)
    abort();

  glUseProgram(program);

  return program;
}

void render_loop(Gameboy &gb)
{
  const unsigned int width = Display::width * 5;
  const unsigned int height = Display::height * 5;

  GLFWwindow *window = initgl(width, height);
  glfwSetWindowUserPointer(window, &gb);

  //
  // OpenGL settings
  //
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  gluOrtho2D(0, width, height, 0);

  GLuint program = init_shaders();

  GLuint texture_loc = glGetUniformLocation(program, "u_texture");
  GLuint position_loc = glGetAttribLocation(program, "a_position");
  GLuint texcoord_loc = glGetAttribLocation(program, "a_texcoord");

  //
  // Buffers
  //
  GLuint vbo;
  glGenBuffers(1, &vbo);
  glBindBuffer(GL_ARRAY_BUFFER, vbo);
  glBufferData(GL_ARRAY_BUFFER, sizeof(kDisplayVertices), kDisplayVertices, GL_STATIC_DRAW);

  GLuint vao;
  glGenVertexArrays(1, &vao);
  glBindVertexArray(vao);

  // position attribute
  glVertexAttribPointer(position_loc, 2,
      GL_FLOAT, GL_FALSE, sizeof(Vertex),
      reinterpret_cast<GLvoid*>(offsetof(Vertex, pos)));
  glEnableVertexAttribArray(position_loc);

  // texcoord attribute
  glVertexAttribPointer(texcoord_loc, 2,
      GL_FLOAT, GL_FALSE, sizeof(Vertex),
      reinterpret_cast<GLvoid*>(offsetof(Vertex, tex)));
  glEnableVertexAttribArray(texcoord_loc);

  //
  // Texture
  //
  GLuint texture;
  glGenTextures(1, &texture);
  glBindTexture(GL_TEXTURE_2D, texture);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

  glActiveTexture(GL_TEXTURE0);

  // Uncomment to change display FPS
  //  glfwSwapInterval(0);
  while (!glfwWindowShouldClose(window))
  {
    for (int i=0; i<16666; i++)
    {
      gb.step();
    }

    glClear(GL_COLOR_BUFFER_BIT);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, Display::width, Display::height,
        0, GL_RGB, GL_UNSIGNED_BYTE, gb.get_framebuffer());
    glUniform1i(texture_loc, 0);
    glDrawArrays(GL_TRIANGLES, 0, 6);

    glfwSwapBuffers(window);
    glfwPollEvents();
  }
}

void key_callback(GLFWwindow *window, int key, int scancode, int action, int mode)
{
  Gameboy *gb = (Gameboy *)glfwGetWindowUserPointer(window);
  bool pressed = (action != GLFW_RELEASE);
  switch (key)
  {
    case GLFW_KEY_UP:
      pressed ? gb->button_pressed(Joypad::Button::UP) :
                gb->button_released(Joypad::Button::UP);
      break;
    case GLFW_KEY_DOWN:
      pressed ? gb->button_pressed(Joypad::Button::DOWN) :
                gb->button_released(Joypad::Button::DOWN);
      break;
    case GLFW_KEY_LEFT:
      pressed ? gb->button_pressed(Joypad::Button::LEFT) :
                gb->button_released(Joypad::Button::LEFT);
      break;
    case GLFW_KEY_RIGHT:
      pressed ? gb->button_pressed(Joypad::Button::RIGHT) :
                gb->button_released(Joypad::Button::RIGHT);
      break;
    case GLFW_KEY_Z:
      pressed ? gb->button_pressed(Joypad::Button::A) :
                gb->button_released(Joypad::Button::A);
      break;
    case GLFW_KEY_X:
      pressed ? gb->button_pressed(Joypad::Button::B) :
                gb->button_released(Joypad::Button::B);
      break;
    case GLFW_KEY_ENTER:
      pressed ? gb->button_pressed(Joypad::Button::START) :
                gb->button_released(Joypad::Button::START);
      break;
    case GLFW_KEY_BACKSPACE:
      pressed ? gb->button_pressed(Joypad::Button::SELECT) :
                gb->button_released(Joypad::Button::SELECT);
      break;
  }
}
<|endoftext|>


<commit_before>// (C) 2014 Arek Olek

#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/adjacency_matrix.hpp>

#include <omp.h>

#include "bfs.hpp"
#include "dfs.hpp"
#include "fifodfs.hpp"
#include "fivethree.hpp"
#include "lost.hpp"
#include "rdfs.hpp"
#include "random.hpp"
#include "ilst.hpp"
#include "greedy.hpp"

#include "test_suite.hpp"

#include "debug.hpp"
#include "graph.hpp"
#include "options.hpp"
#include "range.hpp"
#include "timing.hpp"

boost::adjacency_matrix<boost::undirectedS> typedef amatrix;
boost::adjacency_list<boost::hash_setS, boost::vecS, boost::undirectedS> typedef ahash;
boost::adjacency_list<boost::listS, boost::vecS, boost::undirectedS> typedef alist;
boost::adjacency_list<boost::slistS, boost::vecS, boost::undirectedS> typedef aslist;
boost::adjacency_list<boost::setS, boost::vecS, boost::undirectedS> typedef aset;
boost::adjacency_list<boost::multisetS, boost::vecS, boost::undirectedS> typedef amultiset;
boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS> typedef avec;

template<class Graph, class Tree>
std::function<Tree(Graph&)> make_construction(std::string name,
                                              unsigned index,
                                              unsigned size,
                                              unsigned seed,
                                              std::string sseed) {
  if (name == "bfs")
    return bfs_tree<Graph, Tree> ;
  if (name == "dfs")
    return dfs_tree<Graph, Tree> ;
  if (name == "rdfs")
    return rdfs_tree<Graph, Tree> ;
  if (name == "rdfs50")
    return rdfs_best_tree<Graph, Tree> ;
  if (name == "fifo")
    return fifo_dfs_tree<Graph, Tree> ;
  if (name == "random")
    return std::bind(random_tree<Graph, Tree>, std::placeholders::_1, seed);
  if (name == "wilson")
    return std::bind(wilson_tree<Graph, Tree>, std::placeholders::_1, seed);
  if (name == "greedy")
    return std::bind(greedy_tree<Graph, Tree>, std::placeholders::_1, seed);
  if (name == "ilst")
    return ilst<Graph, Tree> ;
  if (name == "5/3") {
    return [=](const Graph& G) {
      std::default_random_engine generator(seed);
      Tree g(num_vertices(G));
      copy_edges_shuffled(five_three_tree<Graph, Tree>(G), g, generator);
      return g;
    };
  }
  if (found(".xml", name)) {
    return [=](const Graph& G) {
      real_suite<Tree> suite(name, size, sseed);
      return std::get<0>(suite.get(index));
    };
  }
  throw std::invalid_argument("Unknown construction method: " + name);
}

template<class Graph>
std::function<unsigned(Graph&)> make_upper(std::string name) {
  if (name == "53") {
    return [](const Graph& G) {
      return 5*(num_vertices(G)-3)/6;
    };
  }
  return upper_bound<Graph> ;
}

std::string type(amatrix const & G) { return "matrix"; }
std::string type(ahash const & G) { return "unordered_set"; }
std::string type(aset const & G) { return "set"; }
std::string type(amultiset const & G) { return "multiset"; }
std::string type(alist const & G) { return "list"; }
std::string type(aslist const & G) { return "slist"; }
std::string type(avec const & G) { return "vector"; }

template <class Graph, class Tree, class Suite, class Strings>
void run(Suite& suite,
         Strings const & constructions,
         Strings const & improvements,
         bool scratch,
         std::string seed) {
  timing total(CLOCK_REALTIME);
  total.start();
  auto graph_type = type(Graph(0));
  auto tree_type = type(Tree(0));
  #pragma omp parallel
  {
    auto id = omp_get_thread_num();
    double elapsed_c, elapsed_i;
    std::stringstream buffer;
    timing timer;
    #pragma omp for schedule(dynamic) nowait
    for(uint i = 0; i < suite.size(); ++i) {
      auto trial = suite.get(i);
      auto G = std::get<0>(trial);

      for (auto cname : constructions) {
        auto construct = make_construction<Graph, Tree>(cname, i, suite.size(), suite.get_seed(i), seed);
        auto upper = make_upper<Graph>(suite.type());
        timer.start();
        auto T = construct(G);
        elapsed_c = timer.stop();

        assert(num_edges(T) == num_vertices(T) - 1);
        assert(is_connected(T));
        assert(is_subgraph(T, G));

        const auto tree(T);

        for (auto iname : improvements) {
          if (scratch) T = tree;
          auto num_internal_before = num_internal(T);
          auto improve = make_improvement<Graph, Tree>(iname);

          timer.start();
          auto rules = improve(G, T);
          elapsed_i = timer.stop();

          buffer
#ifdef GRAPH_REPR
            << graph_type << '\t'
#endif
#ifdef TREE_REPR
            << tree_type << '\t'
#endif
            << std::get<1>(trial) << '\t'
            << id << '\t'
            << suite.type() << '\t'
            << std::get<2>(trial) << '\t'
            << std::get<3>(trial) << '\t'
            << num_vertices(G) << '\t'
            << num_edges(G) << '\t'
            << upper(G) << '\t'
            << cname << '\t'
            << iname << '\t'
            << num_internal_before << '\t'
            << num_internal(T) << '\t'
            << elapsed_c << '\t'
            << elapsed_i << '\t'
            << sum(rules) << '\t'
            << join(rules, "-")
            << std::endl;
            ;
#ifndef NDEBUG
          if (suite.size() < 10)
            show("graph" + std::to_string(i) + graph_type + ".dot", G, T);
          //if(rules[rules.size()-2] > 10) show("graph" + std::to_string(i) + ".dot", G, T);
#endif
          if (!scratch) elapsed_c += elapsed_i;
        }
      }

      if (id == 0 || i + 1 == suite.size()) {
        std::cerr << '\t' << 100 * (i + 1) / suite.size() << "% of "
        << suite.size();
        std::cerr << '\t' << readable(total.stop()) << " elapsed    \r";
      }
    }
    #pragma omp critical
    std::cout << buffer.str() << std::flush;
  }
  std::cerr << std::endl;
}

template <class Graph, class Tree, class Sizes, class Params, class Strings>
void run(std::string t,
         unsigned z,
         Sizes sizes,
         Params params,
         Strings const & constructions,
         Strings const & improvements,
         bool scratch,
         std::string seed) {
  if (found(".xml", t)) {
    real_suite<Graph> suite(t, z, seed);
    run<Graph, Tree>(suite, constructions, improvements, scratch, seed);
  } else if (found(".", t)) {
    file_suite<Graph> suite(t, z, seed);
    run<Graph, Tree>(suite, constructions, improvements, scratch, seed);
  } else {
    test_suite<Graph> suite(t, z, sizes, params, seed);
    run<Graph, Tree>(suite, constructions, improvements, scratch, seed);
  }
}

template <class Graph, class Sizes, class Degrees, class Strings>
void run(std::string tree,
         std::string model,
         unsigned sample,
         Sizes sizes,
         Degrees degrees,
         Strings const & constructions,
         Strings const & improvements,
         bool scratch,
         std::string seed) {
#ifdef TREE_REPR
  if (tree == "matrix")
    run<Graph, amatrix>  (model, sample, sizes, degrees, constructions, improvements, scratch, seed);
  if (tree == "unordered_set")
    run<Graph, ahash>    (model, sample, sizes, degrees, constructions, improvements, scratch, seed);
  if (tree == "multiset")
    run<Graph, amultiset>(model, sample, sizes, degrees, constructions, improvements, scratch, seed);
  if (tree == "list")
    run<Graph, alist>    (model, sample, sizes, degrees, constructions, improvements, scratch, seed);
  if (tree == "set")
    run<Graph, aset>     (model, sample, sizes, degrees, constructions, improvements, scratch, seed);
  if (tree == "vector")
    run<Graph, avec>     (model, sample, sizes, degrees, constructions, improvements, scratch, seed);
#endif
  if (tree == "slist")
    run<Graph, aslist>   (model, sample, sizes, degrees, constructions, improvements, scratch, seed);
}

template <class Sizes, class Degrees, class Strings>
void run(std::string graph,
         std::string tree,
         std::string model,
         unsigned sample,
         Sizes sizes,
         Degrees degrees,
         Strings const & constructions,
         Strings const & improvements,
         bool scratch,
         std::string seed) {
#ifdef GRAPH_REPR
  if (graph == "matrix")
    run<amatrix>  (tree, model, sample, sizes, degrees, constructions, improvements, scratch, seed);
  if (graph == "unordered_set")
    run<ahash>    (tree, model, sample, sizes, degrees, constructions, improvements, scratch, seed);
  if (graph == "multiset")
    run<amultiset>(tree, model, sample, sizes, degrees, constructions, improvements, scratch, seed);
  if (graph == "slist")
    run<aslist>   (tree, model, sample, sizes, degrees, constructions, improvements, scratch, seed);
  if (graph == "vector")
    run<avec>     (tree, model, sample, sizes, degrees, constructions, improvements, scratch, seed);
  if (graph == "list")
    run<alist>    (tree, model, sample, sizes, degrees, constructions, improvements, scratch, seed);
#endif
  if (graph == "set")
    run<aset>     (tree, model, sample, sizes, degrees, constructions, improvements, scratch, seed);
}

std::string time_seed() {
  return std::to_string(std::chrono::system_clock::now().time_since_epoch().count());
}

int main(int argc, char** argv){
  using std::string;
  using std::vector;

  std::ios_base::sync_with_stdio(0);

  options opt(argc, argv);
  auto z = opt.get<int>("-z", 100);
  auto graphs = opt.getList<string>("-g", {"set"});
  auto trees = opt.getList<string>("-t", {"slist"});
  auto sizes = opt.getList<unsigned>("-n", {1000});
  auto tests = opt.getList<string>("-m", {"gnp+mst"});
  auto degrees = opt.getList<double>("-d", { 3. });
  auto constructions = opt.getList<string>("-c", {"wilson"});
  auto improvements = opt.getList<string>("-i", {"none"});
  auto scratch = opt.has("--scratch");
  auto seed = opt.get<string>("-s", time_seed());

  std::cout << "# Seed: " << seed << std::endl;

  std::cout
#ifdef GRAPH_REPR
    << "graph\t"
#endif
#ifdef TREE_REPR
    << "tree\t"
#endif
    << "run\t"
    << "thread\t"
    << "model\t"
    << "degree\t"
    << "param\t"
    << "vertices\t"
    << "edges\t"
    << "upper\t"
    << "construction\t"
    << "improvement\t"
    << "before\t"
    << "internal\t"
    << "ctime\t"
    << "itime\t"
    << "steps\t"
    << "rules"
    << std::endl;

  for(auto t : tests)
    for(auto graph : graphs)
      for(auto tree : trees)
        run(graph, tree, t, z, sizes, degrees, constructions, improvements,
            scratch, seed);

  return 0;
}
<commit_msg>add CXXFLAG to disable progress reporting<commit_after>// (C) 2014 Arek Olek

#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/adjacency_matrix.hpp>

#include <omp.h>

#include "bfs.hpp"
#include "dfs.hpp"
#include "fifodfs.hpp"
#include "fivethree.hpp"
#include "lost.hpp"
#include "rdfs.hpp"
#include "random.hpp"
#include "ilst.hpp"
#include "greedy.hpp"

#include "test_suite.hpp"

#include "debug.hpp"
#include "graph.hpp"
#include "options.hpp"
#include "range.hpp"
#include "timing.hpp"

boost::adjacency_matrix<boost::undirectedS> typedef amatrix;
boost::adjacency_list<boost::hash_setS, boost::vecS, boost::undirectedS> typedef ahash;
boost::adjacency_list<boost::listS, boost::vecS, boost::undirectedS> typedef alist;
boost::adjacency_list<boost::slistS, boost::vecS, boost::undirectedS> typedef aslist;
boost::adjacency_list<boost::setS, boost::vecS, boost::undirectedS> typedef aset;
boost::adjacency_list<boost::multisetS, boost::vecS, boost::undirectedS> typedef amultiset;
boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS> typedef avec;

template<class Graph, class Tree>
std::function<Tree(Graph&)> make_construction(std::string name,
                                              unsigned index,
                                              unsigned size,
                                              unsigned seed,
                                              std::string sseed) {
  if (name == "bfs")
    return bfs_tree<Graph, Tree> ;
  if (name == "dfs")
    return dfs_tree<Graph, Tree> ;
  if (name == "rdfs")
    return rdfs_tree<Graph, Tree> ;
  if (name == "rdfs50")
    return rdfs_best_tree<Graph, Tree> ;
  if (name == "fifo")
    return fifo_dfs_tree<Graph, Tree> ;
  if (name == "random")
    return std::bind(random_tree<Graph, Tree>, std::placeholders::_1, seed);
  if (name == "wilson")
    return std::bind(wilson_tree<Graph, Tree>, std::placeholders::_1, seed);
  if (name == "greedy")
    return std::bind(greedy_tree<Graph, Tree>, std::placeholders::_1, seed);
  if (name == "ilst")
    return ilst<Graph, Tree> ;
  if (name == "5/3") {
    return [=](const Graph& G) {
      std::default_random_engine generator(seed);
      Tree g(num_vertices(G));
      copy_edges_shuffled(five_three_tree<Graph, Tree>(G), g, generator);
      return g;
    };
  }
  if (found(".xml", name)) {
    return [=](const Graph& G) {
      real_suite<Tree> suite(name, size, sseed);
      return std::get<0>(suite.get(index));
    };
  }
  throw std::invalid_argument("Unknown construction method: " + name);
}

template<class Graph>
std::function<unsigned(Graph&)> make_upper(std::string name) {
  if (name == "53") {
    return [](const Graph& G) {
      return 5*(num_vertices(G)-3)/6;
    };
  }
  return upper_bound<Graph> ;
}

std::string type(amatrix const & G) { return "matrix"; }
std::string type(ahash const & G) { return "unordered_set"; }
std::string type(aset const & G) { return "set"; }
std::string type(amultiset const & G) { return "multiset"; }
std::string type(alist const & G) { return "list"; }
std::string type(aslist const & G) { return "slist"; }
std::string type(avec const & G) { return "vector"; }

template <class Graph, class Tree, class Suite, class Strings>
void run(Suite& suite,
         Strings const & constructions,
         Strings const & improvements,
         bool scratch,
         std::string seed) {
#ifndef NPROGRESS
  timing total(CLOCK_REALTIME);
  total.start();
#endif
  auto graph_type = type(Graph(0));
  auto tree_type = type(Tree(0));
  #pragma omp parallel
  {
    auto id = omp_get_thread_num();
    double elapsed_c, elapsed_i;
    std::stringstream buffer;
    timing timer;
    #pragma omp for schedule(dynamic) nowait
    for(uint i = 0; i < suite.size(); ++i) {
      auto trial = suite.get(i);
      auto G = std::get<0>(trial);

      for (auto cname : constructions) {
        auto construct = make_construction<Graph, Tree>(cname, i, suite.size(), suite.get_seed(i), seed);
        auto upper = make_upper<Graph>(suite.type());
        timer.start();
        auto T = construct(G);
        elapsed_c = timer.stop();

        assert(num_edges(T) == num_vertices(T) - 1);
        assert(is_connected(T));
        assert(is_subgraph(T, G));

        const auto tree(T);

        for (auto iname : improvements) {
          if (scratch) T = tree;
          auto num_internal_before = num_internal(T);
          auto improve = make_improvement<Graph, Tree>(iname);

          timer.start();
          auto rules = improve(G, T);
          elapsed_i = timer.stop();

          buffer
#ifdef GRAPH_REPR
            << graph_type << '\t'
#endif
#ifdef TREE_REPR
            << tree_type << '\t'
#endif
            << std::get<1>(trial) << '\t'
            << id << '\t'
            << suite.type() << '\t'
            << std::get<2>(trial) << '\t'
            << std::get<3>(trial) << '\t'
            << num_vertices(G) << '\t'
            << num_edges(G) << '\t'
            << upper(G) << '\t'
            << cname << '\t'
            << iname << '\t'
            << num_internal_before << '\t'
            << num_internal(T) << '\t'
            << elapsed_c << '\t'
            << elapsed_i << '\t'
            << sum(rules) << '\t'
            << join(rules, "-")
            << std::endl;
            ;
#ifndef NDEBUG
          if (suite.size() < 10)
            show("graph" + std::to_string(i) + graph_type + ".dot", G, T);
          //if(rules[rules.size()-2] > 10) show("graph" + std::to_string(i) + ".dot", G, T);
#endif
          if (!scratch) elapsed_c += elapsed_i;
        }
      }

#ifndef NPROGRESS
      if (id == 0 || i + 1 == suite.size()) {
        std::cerr << '\t' << 100 * (i + 1) / suite.size() << "% of "
        << suite.size();
        std::cerr << '\t' << readable(total.stop()) << " elapsed    \r";
      }
#endif
    }
    #pragma omp critical
    std::cout << buffer.str() << std::flush;
  }
#ifndef NPROGRESS
  std::cerr << std::endl;
#endif
}

template <class Graph, class Tree, class Sizes, class Params, class Strings>
void run(std::string t,
         unsigned z,
         Sizes sizes,
         Params params,
         Strings const & constructions,
         Strings const & improvements,
         bool scratch,
         std::string seed) {
  if (found(".xml", t)) {
    real_suite<Graph> suite(t, z, seed);
    run<Graph, Tree>(suite, constructions, improvements, scratch, seed);
  } else if (found(".", t)) {
    file_suite<Graph> suite(t, z, seed);
    run<Graph, Tree>(suite, constructions, improvements, scratch, seed);
  } else {
    test_suite<Graph> suite(t, z, sizes, params, seed);
    run<Graph, Tree>(suite, constructions, improvements, scratch, seed);
  }
}

template <class Graph, class Sizes, class Degrees, class Strings>
void run(std::string tree,
         std::string model,
         unsigned sample,
         Sizes sizes,
         Degrees degrees,
         Strings const & constructions,
         Strings const & improvements,
         bool scratch,
         std::string seed) {
#ifdef TREE_REPR
  if (tree == "matrix")
    run<Graph, amatrix>  (model, sample, sizes, degrees, constructions, improvements, scratch, seed);
  if (tree == "unordered_set")
    run<Graph, ahash>    (model, sample, sizes, degrees, constructions, improvements, scratch, seed);
  if (tree == "multiset")
    run<Graph, amultiset>(model, sample, sizes, degrees, constructions, improvements, scratch, seed);
  if (tree == "list")
    run<Graph, alist>    (model, sample, sizes, degrees, constructions, improvements, scratch, seed);
  if (tree == "set")
    run<Graph, aset>     (model, sample, sizes, degrees, constructions, improvements, scratch, seed);
  if (tree == "vector")
    run<Graph, avec>     (model, sample, sizes, degrees, constructions, improvements, scratch, seed);
#endif
  if (tree == "slist")
    run<Graph, aslist>   (model, sample, sizes, degrees, constructions, improvements, scratch, seed);
}

template <class Sizes, class Degrees, class Strings>
void run(std::string graph,
         std::string tree,
         std::string model,
         unsigned sample,
         Sizes sizes,
         Degrees degrees,
         Strings const & constructions,
         Strings const & improvements,
         bool scratch,
         std::string seed) {
#ifdef GRAPH_REPR
  if (graph == "matrix")
    run<amatrix>  (tree, model, sample, sizes, degrees, constructions, improvements, scratch, seed);
  if (graph == "unordered_set")
    run<ahash>    (tree, model, sample, sizes, degrees, constructions, improvements, scratch, seed);
  if (graph == "multiset")
    run<amultiset>(tree, model, sample, sizes, degrees, constructions, improvements, scratch, seed);
  if (graph == "slist")
    run<aslist>   (tree, model, sample, sizes, degrees, constructions, improvements, scratch, seed);
  if (graph == "vector")
    run<avec>     (tree, model, sample, sizes, degrees, constructions, improvements, scratch, seed);
  if (graph == "list")
    run<alist>    (tree, model, sample, sizes, degrees, constructions, improvements, scratch, seed);
#endif
  if (graph == "set")
    run<aset>     (tree, model, sample, sizes, degrees, constructions, improvements, scratch, seed);
}

std::string time_seed() {
  return std::to_string(std::chrono::system_clock::now().time_since_epoch().count());
}

int main(int argc, char** argv){
  using std::string;
  using std::vector;

  std::ios_base::sync_with_stdio(0);

  options opt(argc, argv);
  auto z = opt.get<int>("-z", 100);
  auto graphs = opt.getList<string>("-g", {"set"});
  auto trees = opt.getList<string>("-t", {"slist"});
  auto sizes = opt.getList<unsigned>("-n", {1000});
  auto tests = opt.getList<string>("-m", {"gnp+mst"});
  auto degrees = opt.getList<double>("-d", { 3. });
  auto constructions = opt.getList<string>("-c", {"wilson"});
  auto improvements = opt.getList<string>("-i", {"none"});
  auto scratch = opt.has("--scratch");
  auto seed = opt.get<string>("-s", time_seed());

  std::cout << "# Seed: " << seed << std::endl;

  std::cout
#ifdef GRAPH_REPR
    << "graph\t"
#endif
#ifdef TREE_REPR
    << "tree\t"
#endif
    << "run\t"
    << "thread\t"
    << "model\t"
    << "degree\t"
    << "param\t"
    << "vertices\t"
    << "edges\t"
    << "upper\t"
    << "construction\t"
    << "improvement\t"
    << "before\t"
    << "internal\t"
    << "ctime\t"
    << "itime\t"
    << "steps\t"
    << "rules"
    << std::endl;

  for(auto t : tests)
    for(auto graph : graphs)
      for(auto tree : trees)
        run(graph, tree, t, z, sizes, degrees, constructions, improvements,
            scratch, seed);

  return 0;
}
<|endoftext|>


<commit_before>#include "GeometricRand.h"

GeometricRand::GeometricRand(double probability)
{
    setProbability(probability);
}

std::string GeometricRand::name()
{
    return "Geometric(" + toStringWithPrecision(getProbability()) + ")";
}

void GeometricRand::setProbability(double probability)
{
    p = std::min(std::max(probability, MIN_POSITIVE), 1.0);
    q = 1.0 - p;

    /// we use two different generators for two different cases
    /// if p < 0.2 then the tail is too heavy
    /// (probability to be in main body is less then 0.977482)
    /// thus we always use low bound of variate exponential distribution
    /// otherwise we choose table method
    if (p < 0.2)
    {
        W.setRate(-std::log(q));
    }
    else
    {
        table[0] = p;
        double prod = p;
        for (int i = 1; i < tableSize; ++i)
        {
            prod *= q;
            table[i] = table[i - 1] + prod;
        }
    }
}

double GeometricRand::P(int k) const
{
    return (k < 0) ? 0 : p * std::pow(q, k);
}

double GeometricRand::F(double x) const
{
    return (x < 0) ? 0 : 1 - std::pow(q, std::floor(x) + 1);
}

double GeometricRand::variate() const
{
    if (p < 0.2)
        return variateByExponential();
    return variateByTable();
}

double GeometricRand::variate(double probability)
{
    if (probability < 0.2)
        return std::floor(ExponentialRand::variate(-std::log(1 - probability)));

    double U = UniformRand::standardVariate();
    int x = 0;
    double prod = probability, sum = prod, q = 1 - probability;
    while (U > sum) {
        prod *= q;
        sum += prod;
        ++x;
    }
    return x;
}

void GeometricRand::sample(QVector<double> &outputData)
{
    if (p < 0.2) {
        for (double &var : outputData)
            var = variateByExponential();
    }
    else {
        for (double &var : outputData)
            var = variateByTable();
    }
}

double GeometricRand::variateByExponential() const
{
    return std::floor(W.variate());
}

double GeometricRand::variateByTable() const
{
    double U = UniformRand::standardVariate();
    /// handle tail by recursion
    if (U > table[tableSize - 1])
        return tableSize + variateByTable();
    /// handle the main body
    int x = 0;
    while (U > table[x])
        ++x;
    return x;
}

double GeometricRand::Quantile(double F) const
{
    if (F < 0 || F > 1)
        return NAN;
    if (F == 0)
        return -INFINITY;
    if (F == 1)
        return INFINITY;
    return std::log1p(F) / std::log(1 - p);
}

double GeometricRand::Median() const
{
    return std::floor(-M_LN2 / std::log(q));
}

double GeometricRand::Mode() const
{
    return 0.0;
}

double GeometricRand::Skewness() const
{
    return (2 - p) / std::sqrt(q);
}

double GeometricRand::ExcessKurtosis() const
{
    return p * p / q + 6;
}

double GeometricRand::Entropy() const
{
    double a = -q * std::log(q);
    double b = -p * std::log(p);
    return (a + b) / (M_LN2 * p);
}

<commit_msg>Update GeometricRand.cpp<commit_after>#include "GeometricRand.h"

GeometricRand::GeometricRand(double probability)
{
    setProbability(probability);
}

std::string GeometricRand::name()
{
    return "Geometric(" + toStringWithPrecision(getProbability()) + ")";
}

void GeometricRand::setProbability(double probability)
{
    p = std::min(probability, 1.0);
    if (p <= 0)
        p = MIN_POSITIVE;
    q = 1.0 - p;

    /// we use two different generators for two different cases
    /// if p < 0.2 then the tail is too heavy
    /// (probability to be in main body is less then 0.977482)
    /// thus we always use low bound of variate exponential distribution
    /// otherwise we choose table method
    if (p < 0.2)
    {
        W.setRate(-std::log(q));
    }
    else
    {
        table[0] = p;
        double prod = p;
        for (int i = 1; i < tableSize; ++i)
        {
            prod *= q;
            table[i] = table[i - 1] + prod;
        }
    }
}

double GeometricRand::P(int k) const
{
    return (k < 0) ? 0 : p * std::pow(q, k);
}

double GeometricRand::F(double x) const
{
    return (x < 0) ? 0 : 1 - std::pow(q, std::floor(x) + 1);
}

double GeometricRand::variate() const
{
    if (p < 0.2)
        return variateByExponential();
    return variateByTable();
}

double GeometricRand::variate(double probability)
{
    if (probability < 0.2)
        return std::floor(ExponentialRand::variate(-std::log(1 - probability)));

    double U = UniformRand::standardVariate();
    int x = 0;
    double prod = probability, sum = prod, q = 1 - probability;
    while (U > sum) {
        prod *= q;
        sum += prod;
        ++x;
    }
    return x;
}

void GeometricRand::sample(QVector<double> &outputData)
{
    if (p < 0.2) {
        for (double &var : outputData)
            var = variateByExponential();
    }
    else {
        for (double &var : outputData)
            var = variateByTable();
    }
}

double GeometricRand::variateByExponential() const
{
    return std::floor(W.variate());
}

double GeometricRand::variateByTable() const
{
    double U = UniformRand::standardVariate();
    /// handle tail by recursion
    if (U > table[tableSize - 1])
        return tableSize + variateByTable();
    /// handle the main body
    int x = 0;
    while (U > table[x])
        ++x;
    return x;
}

double GeometricRand::Quantile(double F) const
{
    if (F < 0 || F > 1)
        return NAN;
    if (F == 0)
        return -INFINITY;
    if (F == 1)
        return INFINITY;
    return std::log1p(F) / std::log(1 - p);
}

double GeometricRand::Median() const
{
    return std::floor(-M_LN2 / std::log(q));
}

double GeometricRand::Mode() const
{
    return 0.0;
}

double GeometricRand::Skewness() const
{
    return (2 - p) / std::sqrt(q);
}

double GeometricRand::ExcessKurtosis() const
{
    return p * p / q + 6;
}

double GeometricRand::Entropy() const
{
    double a = -q * std::log(q);
    double b = -p * std::log(p);
    return (a + b) / (M_LN2 * p);
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: pe_struc.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 18:50:01 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <precomp.h>
#include <s2_luidl/pe_struc.hxx>

// NOT FULLY DECLARED SERVICES
#include <ary/idl/i_gate.hxx>
#include <ary/idl/i_struct.hxx>
#include <ary/idl/ip_ce.hxx>
#include <ary_i/codeinf2.hxx>
#include <s2_luidl/tk_ident.hxx>
#include <s2_luidl/tk_punct.hxx>
#include <s2_luidl/tk_keyw.hxx>
#include <s2_luidl/pe_type2.hxx>
#include <s2_luidl/pe_selem.hxx>

namespace csi
{
namespace uidl
{

PE_Struct::PE_Struct()
    // :    aWork,
    //      pStati
{
    pStati = new S_Stati(*this);
}

void
PE_Struct::EstablishContacts( UnoIDL_PE *               io_pParentPE,
                              ary::n22::Repository &            io_rRepository,
                              TokenProcessing_Result &  o_rResult )
{
    UnoIDL_PE::EstablishContacts(io_pParentPE,io_rRepository,o_rResult);
    Work().pPE_Element->EstablishContacts(this,io_rRepository,o_rResult);
    Work().pPE_Type->EstablishContacts(this,io_rRepository,o_rResult);
}

PE_Struct::~PE_Struct()
{
}

void
PE_Struct::ProcessToken( const Token & i_rToken )
{
    i_rToken.Trigger(*Stati().pCurStatus);
}

void
PE_Struct::InitData()
{
    Work().InitData();
    Stati().pCurStatus = &Stati().aWaitForName;
}

void
PE_Struct::TransferData()
{
    if (NOT Work().bIsPreDeclaration)
    {
        csv_assert(Work().sData_Name.size() > 0);
        csv_assert(Work().nCurStruct.IsValid());
    }
    Stati().pCurStatus = &Stati().aNone;
}

void
PE_Struct::ReceiveData()
{
    Stati().pCurStatus->On_SubPE_Left();
}

PE_Struct::S_Work::S_Work()
    :   sData_Name(),
        sData_TemplateParam(),
        bIsPreDeclaration(false),
        nCurStruct(0),
        pPE_Element(0),
        nCurParsed_ElementRef(0),
        pPE_Type(0),
        nCurParsed_Base(0)

{
    pPE_Element = new PE_StructElement(nCurParsed_ElementRef,nCurStruct,sData_TemplateParam);
    pPE_Type = new PE_Type(nCurParsed_Base);
}

void
PE_Struct::S_Work::InitData()
{
    sData_Name.clear();
    sData_TemplateParam.clear();
    bIsPreDeclaration = false;
    nCurStruct = 0;
    nCurParsed_ElementRef = 0;
    nCurParsed_Base = 0;
}

void
PE_Struct::S_Work::Prepare_PE_QualifiedName()
{
    nCurParsed_ElementRef = 0;
}

void
PE_Struct::S_Work::Prepare_PE_Element()
{
    nCurParsed_Base = 0;
}

void
PE_Struct::S_Work::Data_Set_Name( const char * i_sName )
{
    sData_Name = i_sName;
}

void
PE_Struct::S_Work::Data_Set_TemplateParam( const char * i_sTemplateParam )
{
    sData_TemplateParam = i_sTemplateParam;
}

PE_Struct::S_Stati::S_Stati(PE_Struct & io_rStruct)
    :   aNone(io_rStruct),
        aWaitForName(io_rStruct),
        aGotName(io_rStruct),
        aWaitForTemplateParam(io_rStruct),
        aWaitForTemplateEnd(io_rStruct),
        aWaitForBase(io_rStruct),
        aGotBase(io_rStruct),
        aWaitForElement(io_rStruct),
        aWaitForFinish(io_rStruct),
        pCurStatus(0)
{
    pCurStatus = &aNone;
}

//***********************       Stati       ***************************//

UnoIDL_PE &
PE_Struct::PE_StructState::MyPE()
{
    return rStruct;
}

void
PE_Struct::State_WaitForName::Process_Identifier( const TokIdentifier & i_rToken )
{
    Work().Data_Set_Name(i_rToken.Text());
    MoveState( Stati().aGotName );
    SetResult(done,stay);
}

void
PE_Struct::State_GotName::Process_Punctuation( const TokPunctuation & i_rToken )
{
    if ( i_rToken.Id() != TokPunctuation::Semicolon )
    {
        switch (i_rToken.Id())
        {
            case TokPunctuation::Colon:
                MoveState( Stati().aWaitForBase );
                SetResult(done,push_sure,Work().pPE_Type.Ptr());
                Work().Prepare_PE_QualifiedName();
                break;
            case TokPunctuation::CurledBracketOpen:
                PE().store_Struct();
                MoveState( Stati().aWaitForElement );
                SetResult(done,stay);
                break;
            case TokPunctuation::Lesser:
                MoveState( Stati().aWaitForTemplateParam );
                SetResult(done,stay);
                break;
            default:
                SetResult(not_done,pop_failure);
        }   // end switch
    }
    else
    {
        Work().sData_Name.clear();
        SetResult(done,pop_success);
    }
}

void
PE_Struct::State_WaitForTemplateParam::Process_Identifier( const TokIdentifier & i_rToken )
{
    Work().Data_Set_TemplateParam(i_rToken.Text());
    MoveState( Stati().aWaitForTemplateEnd );
    SetResult(done,stay);
}

void
PE_Struct::State_WaitForTemplateEnd::Process_Punctuation( const TokPunctuation & i_rToken )
{
    // Assume:  TokPunctuation::Greater
    MoveState( Stati().aGotName );
    SetResult(done,stay);
}

void
PE_Struct::State_WaitForBase::On_SubPE_Left()
{
    MoveState(Stati().aGotBase);
}

void
PE_Struct::State_GotBase::Process_Punctuation( const TokPunctuation & i_rToken )
{
    if ( i_rToken.Id() == TokPunctuation::CurledBracketOpen )
    {
        PE().store_Struct();
        MoveState( Stati().aWaitForElement );
        SetResult(done,stay);
    }
    else
    {
        SetResult(not_done,pop_failure);
    }
}

void
PE_Struct::State_WaitForElement::Process_Identifier( const TokIdentifier & )
{
    SetResult( not_done, push_sure, Work().pPE_Element.Ptr() );
    Work().Prepare_PE_Element();
}

void
PE_Struct::State_WaitForElement::Process_NameSeparator()
{
    SetResult( not_done, push_sure, Work().pPE_Element.Ptr());
    Work().Prepare_PE_Element();
}

void
PE_Struct::State_WaitForElement::Process_BuiltInType( const TokBuiltInType & )
{
    SetResult( not_done, push_sure, Work().pPE_Element.Ptr());
    Work().Prepare_PE_Element();
}

void
PE_Struct::State_WaitForElement::Process_TypeModifier(const TokTypeModifier & )
{
    SetResult( not_done, push_sure, Work().pPE_Element.Ptr());
    Work().Prepare_PE_Element();
}

void
PE_Struct::State_WaitForElement::Process_Punctuation( const TokPunctuation & i_rToken )
{
    if ( i_rToken.Id() == TokPunctuation::CurledBracketClose )
    {
        MoveState( Stati().aWaitForFinish );
        SetResult( done, stay );
    }
    else
    {
        SetResult( not_done, pop_failure );
    }
}

void
PE_Struct::State_WaitForFinish::Process_Punctuation( const TokPunctuation & i_rToken )
{
    if (i_rToken.Id() == TokPunctuation::Semicolon)
    {
        MoveState( Stati().aNone );
        SetResult( done, pop_success );
    }
    else
    {
        SetResult( not_done, pop_failure );
    }
}

void
PE_Struct::store_Struct()
{
    ary::idl::Struct &
        rCe = Gate().Ces().Store_Struct(
                        CurNamespace().CeId(),
                        Work().sData_Name,
                        Work().nCurParsed_Base,
                        Work().sData_TemplateParam );
    PassDocuAt(rCe);
    Work().nCurStruct = rCe.CeId();
}

}   // namespace uidl
}   // namespace csi
<commit_msg>INTEGRATION: CWS warnings01 (1.4.4); FILE MERGED 2005/10/18 08:36:20 np 1.4.4.1: #i53898#<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: pe_struc.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 12:07:42 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <precomp.h>
#include <s2_luidl/pe_struc.hxx>

// NOT FULLY DECLARED SERVICES
#include <ary/idl/i_gate.hxx>
#include <ary/idl/i_struct.hxx>
#include <ary/idl/ip_ce.hxx>
#include <ary_i/codeinf2.hxx>
#include <s2_luidl/tk_ident.hxx>
#include <s2_luidl/tk_punct.hxx>
#include <s2_luidl/tk_keyw.hxx>
#include <s2_luidl/pe_type2.hxx>
#include <s2_luidl/pe_selem.hxx>

namespace csi
{
namespace uidl
{

PE_Struct::PE_Struct()
    // :    aWork,
    //      pStati
{
    pStati = new S_Stati(*this);
}

void
PE_Struct::EstablishContacts( UnoIDL_PE *               io_pParentPE,
                              ary::n22::Repository &            io_rRepository,
                              TokenProcessing_Result &  o_rResult )
{
    UnoIDL_PE::EstablishContacts(io_pParentPE,io_rRepository,o_rResult);
    Work().pPE_Element->EstablishContacts(this,io_rRepository,o_rResult);
    Work().pPE_Type->EstablishContacts(this,io_rRepository,o_rResult);
}

PE_Struct::~PE_Struct()
{
}

void
PE_Struct::ProcessToken( const Token & i_rToken )
{
    i_rToken.Trigger(*Stati().pCurStatus);
}

void
PE_Struct::InitData()
{
    Work().InitData();
    Stati().pCurStatus = &Stati().aWaitForName;
}

void
PE_Struct::TransferData()
{
    if (NOT Work().bIsPreDeclaration)
    {
        csv_assert(Work().sData_Name.size() > 0);
        csv_assert(Work().nCurStruct.IsValid());
    }
    Stati().pCurStatus = &Stati().aNone;
}

void
PE_Struct::ReceiveData()
{
    Stati().pCurStatus->On_SubPE_Left();
}

PE_Struct::S_Work::S_Work()
    :   sData_Name(),
        sData_TemplateParam(),
        bIsPreDeclaration(false),
        nCurStruct(0),
        pPE_Element(0),
        nCurParsed_ElementRef(0),
        pPE_Type(0),
        nCurParsed_Base(0)

{
    pPE_Element = new PE_StructElement(nCurParsed_ElementRef,nCurStruct,sData_TemplateParam);
    pPE_Type = new PE_Type(nCurParsed_Base);
}

void
PE_Struct::S_Work::InitData()
{
    sData_Name.clear();
    sData_TemplateParam.clear();
    bIsPreDeclaration = false;
    nCurStruct = 0;
    nCurParsed_ElementRef = 0;
    nCurParsed_Base = 0;
}

void
PE_Struct::S_Work::Prepare_PE_QualifiedName()
{
    nCurParsed_ElementRef = 0;
}

void
PE_Struct::S_Work::Prepare_PE_Element()
{
    nCurParsed_Base = 0;
}

void
PE_Struct::S_Work::Data_Set_Name( const char * i_sName )
{
    sData_Name = i_sName;
}

void
PE_Struct::S_Work::Data_Set_TemplateParam( const char * i_sTemplateParam )
{
    sData_TemplateParam = i_sTemplateParam;
}

PE_Struct::S_Stati::S_Stati(PE_Struct & io_rStruct)
    :   aNone(io_rStruct),
        aWaitForName(io_rStruct),
        aGotName(io_rStruct),
        aWaitForTemplateParam(io_rStruct),
        aWaitForTemplateEnd(io_rStruct),
        aWaitForBase(io_rStruct),
        aGotBase(io_rStruct),
        aWaitForElement(io_rStruct),
        aWaitForFinish(io_rStruct),
        pCurStatus(0)
{
    pCurStatus = &aNone;
}

//***********************       Stati       ***************************//

UnoIDL_PE &
PE_Struct::PE_StructState::MyPE()
{
    return rStruct;
}

void
PE_Struct::State_WaitForName::Process_Identifier( const TokIdentifier & i_rToken )
{
    Work().Data_Set_Name(i_rToken.Text());
    MoveState( Stati().aGotName );
    SetResult(done,stay);
}

void
PE_Struct::State_GotName::Process_Punctuation( const TokPunctuation & i_rToken )
{
    if ( i_rToken.Id() != TokPunctuation::Semicolon )
    {
        switch (i_rToken.Id())
        {
            case TokPunctuation::Colon:
                MoveState( Stati().aWaitForBase );
                SetResult(done,push_sure,Work().pPE_Type.Ptr());
                Work().Prepare_PE_QualifiedName();
                break;
            case TokPunctuation::CurledBracketOpen:
                PE().store_Struct();
                MoveState( Stati().aWaitForElement );
                SetResult(done,stay);
                break;
            case TokPunctuation::Lesser:
                MoveState( Stati().aWaitForTemplateParam );
                SetResult(done,stay);
                break;
            default:
                SetResult(not_done,pop_failure);
        }   // end switch
    }
    else
    {
        Work().sData_Name.clear();
        SetResult(done,pop_success);
    }
}

void
PE_Struct::State_WaitForTemplateParam::Process_Identifier( const TokIdentifier & i_rToken )
{
    Work().Data_Set_TemplateParam(i_rToken.Text());
    MoveState( Stati().aWaitForTemplateEnd );
    SetResult(done,stay);
}

void
PE_Struct::State_WaitForTemplateEnd::Process_Punctuation( const TokPunctuation & )
{
    // Assume:  TokPunctuation::Greater
    MoveState( Stati().aGotName );
    SetResult(done,stay);
}

void
PE_Struct::State_WaitForBase::On_SubPE_Left()
{
    MoveState(Stati().aGotBase);
}

void
PE_Struct::State_GotBase::Process_Punctuation( const TokPunctuation & i_rToken )
{
    if ( i_rToken.Id() == TokPunctuation::CurledBracketOpen )
    {
        PE().store_Struct();
        MoveState( Stati().aWaitForElement );
        SetResult(done,stay);
    }
    else
    {
        SetResult(not_done,pop_failure);
    }
}

void
PE_Struct::State_WaitForElement::Process_Identifier( const TokIdentifier & )
{
    SetResult( not_done, push_sure, Work().pPE_Element.Ptr() );
    Work().Prepare_PE_Element();
}

void
PE_Struct::State_WaitForElement::Process_NameSeparator()
{
    SetResult( not_done, push_sure, Work().pPE_Element.Ptr());
    Work().Prepare_PE_Element();
}

void
PE_Struct::State_WaitForElement::Process_BuiltInType( const TokBuiltInType & )
{
    SetResult( not_done, push_sure, Work().pPE_Element.Ptr());
    Work().Prepare_PE_Element();
}

void
PE_Struct::State_WaitForElement::Process_TypeModifier(const TokTypeModifier & )
{
    SetResult( not_done, push_sure, Work().pPE_Element.Ptr());
    Work().Prepare_PE_Element();
}

void
PE_Struct::State_WaitForElement::Process_Punctuation( const TokPunctuation & i_rToken )
{
    if ( i_rToken.Id() == TokPunctuation::CurledBracketClose )
    {
        MoveState( Stati().aWaitForFinish );
        SetResult( done, stay );
    }
    else
    {
        SetResult( not_done, pop_failure );
    }
}

void
PE_Struct::State_WaitForFinish::Process_Punctuation( const TokPunctuation & i_rToken )
{
    if (i_rToken.Id() == TokPunctuation::Semicolon)
    {
        MoveState( Stati().aNone );
        SetResult( done, pop_success );
    }
    else
    {
        SetResult( not_done, pop_failure );
    }
}

void
PE_Struct::store_Struct()
{
    ary::idl::Struct &
        rCe = Gate().Ces().Store_Struct(
                        CurNamespace().CeId(),
                        Work().sData_Name,
                        Work().nCurParsed_Base,
                        Work().sData_TemplateParam );
    PassDocuAt(rCe);
    Work().nCurStruct = rCe.CeId();
}

}   // namespace uidl
}   // namespace csi
<|endoftext|>


<commit_before>#include <cstdint>
#include <immintrin.h>

void jpeg_zigzag_avx512bw_permute16(const uint8_t* in, uint8_t* out) {

    const __m512i v = _mm512_loadu_si512((const __m512i*)in);

    // crosslane 16-bit shuffle #1:
    //   [ 0, 1][ 2, 3][ 4, 5][ 8, 9][10,11][16,17][18,19][24,25] -- lane 0: missing: 32
    //   [ 6, 7][12,13][14,15][20,21][26,27][28,29][32,33][34,35] -- lane 1: missing: 19, 34, 40, 41, 48
    //   [22,23][30,31][36,37][42,43][44,45][48,49][50,51][56,57] -- lane 2: missing: 15, 29, 35
    //   [38,39][46,47][52,53][54,55][58,59][60,61][62,63][62,62] -- lane 3: missing: 31, 45
    const int16_t crosslane_shuffle1[32] __attribute__((aligned(64))) = {
         0,  1,  2,  4,  5,  8,  9, 12,
         3,  6,  7, 10, 13, 14, 16, 17,
        11, 15, 18, 21, 22, 24, 25, 28,
        19, 23, 26, 27, 29, 30, 31, 31
    };

    const __m512i shuf1 = _mm512_permutexvar_epi16(_mm512_load_si512((__m512i*)crosslane_shuffle1), v);

    // in-lane 8-bit shuffle #1
    const int8_t inlane_shuffle1[64] __attribute__((aligned(64))) = {
        /* lane 0 */  0,  1,  6, 10,  7,  2,  3,  8, 11, 14, -1, 15, 12,  9,  4,  5,
        /* lane 1 */  2, -1,  8, 13, -1, -1, -1, 14,  9,  6,  3,  0,  1,  4,  7, 10,
        /* lane 2 */ -1,  6, 11, 14, 15, 12,  7,  4, -1,  0, -1,  1,  2,  5,  8, 13,
        /* lane 3 */  8,  9,  4, -1,  0, -1,  1,  2,  5, 10, 11,  6,  3,  7, 12, 13
    };

    const __m512i t0 = _mm512_shuffle_epi8(shuf1, _mm512_load_si512(inlane_shuffle1));

    // crosslane 16-bit shuffle #2 -- we need to get values not available in step #1
    //   [32,33][32,33][32,33][32,33][32,33][32,33][32,33][32,33] -- lane 0: missing: 32
    //   [18,19][34,35][40,41][48,49][48,49][48,49][48,49][48,49] -- lane 1: missing: 19, 34, 40, 41, 48
    //   [14,15][28,29][34,35][34,35][34,35][34,35][34,35][34,35] -- lane 2: missing: 15, 29, 35
    //   [30,31][44,45][44,45][44,45][44,45][44,45][44,45][44,45] -- lane 2: missing: 31, 45
    const int16_t crosslane_shuffle2[32] __attribute__((aligned(64))) = {
        /* lane 0*/ 16, 16, 16, 16, 16, 16, 16, 16,
        /* lane 1*/  9, 17, 20, 24, 24, 24, 24, 24,
        /* lane 2*/  7, 14, 17, 17, 17, 17, 17, 17,
        /* lane 3*/ 15, 22, 22, 22, 22, 22, 22, 22
    };
    const __m512i shuf2 = _mm512_permutexvar_epi16(_mm512_load_si512((__m512i*)crosslane_shuffle2), v);

    // in-lane 8-bit shuffle #2
    const int8_t inlane_shuffle2[64] __attribute__((aligned(64))) = {
        /* lane 0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,  0, -1, -1, -1, -1, -1,
        /* lane 1 */ -1,  1, -1, -1,  4,  6,  5,  2, -1, -1, -1, -1, -1, -1, -1, -1,
        /* lane 2 */  5, -1, -1, -1, -1, -1, -1, -1,  3, -1,  1, -1, -1, -1, -1, -1,
        /* lane 3 */ -1, -1, -1,  3, -1,  1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
    };

    const __m512i t1 = _mm512_shuffle_epi8(shuf2, _mm512_load_si512(inlane_shuffle2));

    const __m512i res = _mm512_or_si512(t0, t1);
    _mm512_storeu_si512((__m512i*)out, res);
}
<commit_msg>Make constants static -- code become much smaller<commit_after>#include <cstdint>
#include <immintrin.h>

void jpeg_zigzag_avx512bw_permute16(const uint8_t* in, uint8_t* out) {

    const __m512i v = _mm512_loadu_si512((const __m512i*)in);

    // crosslane 16-bit shuffle #1:
    //   [ 0, 1][ 2, 3][ 4, 5][ 8, 9][10,11][16,17][18,19][24,25] -- lane 0: missing: 32
    //   [ 6, 7][12,13][14,15][20,21][26,27][28,29][32,33][34,35] -- lane 1: missing: 19, 34, 40, 41, 48
    //   [22,23][30,31][36,37][42,43][44,45][48,49][50,51][56,57] -- lane 2: missing: 15, 29, 35
    //   [38,39][46,47][52,53][54,55][58,59][60,61][62,63][62,62] -- lane 3: missing: 31, 45
    static const int16_t crosslane_shuffle1[32] __attribute__((aligned(64))) = {
         0,  1,  2,  4,  5,  8,  9, 12,
         3,  6,  7, 10, 13, 14, 16, 17,
        11, 15, 18, 21, 22, 24, 25, 28,
        19, 23, 26, 27, 29, 30, 31, 31
    };

    const __m512i shuf1 = _mm512_permutexvar_epi16(_mm512_load_si512((__m512i*)crosslane_shuffle1), v);

    // in-lane 8-bit shuffle #1
    static const int8_t inlane_shuffle1[64] __attribute__((aligned(64))) = {
        /* lane 0 */  0,  1,  6, 10,  7,  2,  3,  8, 11, 14, -1, 15, 12,  9,  4,  5,
        /* lane 1 */  2, -1,  8, 13, -1, -1, -1, 14,  9,  6,  3,  0,  1,  4,  7, 10,
        /* lane 2 */ -1,  6, 11, 14, 15, 12,  7,  4, -1,  0, -1,  1,  2,  5,  8, 13,
        /* lane 3 */  8,  9,  4, -1,  0, -1,  1,  2,  5, 10, 11,  6,  3,  7, 12, 13
    };

    const __m512i t0 = _mm512_shuffle_epi8(shuf1, _mm512_load_si512(inlane_shuffle1));

    // crosslane 16-bit shuffle #2 -- we need to get values not available in step #1
    //   [32,33][32,33][32,33][32,33][32,33][32,33][32,33][32,33] -- lane 0: missing: 32
    //   [18,19][34,35][40,41][48,49][48,49][48,49][48,49][48,49] -- lane 1: missing: 19, 34, 40, 41, 48
    //   [14,15][28,29][34,35][34,35][34,35][34,35][34,35][34,35] -- lane 2: missing: 15, 29, 35
    //   [30,31][44,45][44,45][44,45][44,45][44,45][44,45][44,45] -- lane 2: missing: 31, 45
    static const int16_t crosslane_shuffle2[32] __attribute__((aligned(64))) = {
        /* lane 0*/ 16, 16, 16, 16, 16, 16, 16, 16,
        /* lane 1*/  9, 17, 20, 24, 24, 24, 24, 24,
        /* lane 2*/  7, 14, 17, 17, 17, 17, 17, 17,
        /* lane 3*/ 15, 22, 22, 22, 22, 22, 22, 22
    };
    const __m512i shuf2 = _mm512_permutexvar_epi16(_mm512_load_si512((__m512i*)crosslane_shuffle2), v);

    // in-lane 8-bit shuffle #2
    static const int8_t inlane_shuffle2[64] __attribute__((aligned(64))) = {
        /* lane 0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,  0, -1, -1, -1, -1, -1,
        /* lane 1 */ -1,  1, -1, -1,  4,  6,  5,  2, -1, -1, -1, -1, -1, -1, -1, -1,
        /* lane 2 */  5, -1, -1, -1, -1, -1, -1, -1,  3, -1,  1, -1, -1, -1, -1, -1,
        /* lane 3 */ -1, -1, -1,  3, -1,  1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
    };

    const __m512i t1 = _mm512_shuffle_epi8(shuf2, _mm512_load_si512(inlane_shuffle2));

    const __m512i res = _mm512_or_si512(t0, t1);
    _mm512_storeu_si512((__m512i*)out, res);
}

<|endoftext|>