<commit_before>/************************************************************************
    filename:   CEGuiSample.cpp
    created:    24/9/2004
    author:     Paul D Turner
*************************************************************************/
/*************************************************************************
    Crazy Eddie's GUI System (http://www.cegui.org.uk)
    Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk)

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

    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 "CEGuiSample.h"

#ifdef HAVE_CONFIG_H
#   include "config.h"
#endif
#include "CEGUIConfig.h"

// includes for renderer selector classes
#if defined( __WIN32__ ) || defined( _WIN32 )
#   include "Win32CEGuiRendererSelector.h"
#elif defined(linux)
#   ifdef CEGUI_SAMPLES_USE_GTK2
#       include "GTK2CEGuiRendererSelector.h"
#   else
#       include "CLICEGuiRendererSelector.h"
#   endif
#endif

// includes for application types
#ifdef CEGUI_SAMPLES_USE_OGRE
#   include "CEGuiOgreBaseApplication.h"
#endif
#ifdef CEGUI_SAMPLES_USE_OPENGL
#   include "CEGuiOpenGLBaseApplication.h"
#endif
#ifdef CEGUI_SAMPLES_USE_IRRLICHT
#   include "CEGuiIrrlichtBaseApplication.h"
#endif
#if defined( __WIN32__ ) || defined( _WIN32 )
#   include "CEGuiD3D81BaseApplication.h"
#   include "CEGuiD3D9BaseApplication.h"
#endif
// now we include the base CEGuiBaseApplication just in case someone has managed to
// get this far without any of the renderers.  This ensures the framework will build,
// although there will be no renderers available for selection in the samples.
#include "CEGuiBaseApplication.h"

/*************************************************************************
    Constructor
*************************************************************************/
CEGuiSample::CEGuiSample() :
        d_rendererSelector(0),
        d_sampleApp(0)
{}

/*************************************************************************
    Destructor
*************************************************************************/
CEGuiSample::~CEGuiSample()
{
    if (d_sampleApp)
    {
        d_sampleApp->cleanup();
        delete d_sampleApp;
    }

    if (d_rendererSelector)
    {
        delete d_rendererSelector;
    }

}

/*************************************************************************
    Application entry point
*************************************************************************/
int CEGuiSample::run()
{
    if (initialise())
    {
        cleanup();
    }

    return 0;
}

/*************************************************************************
    Initialise the sample application
*************************************************************************/
bool CEGuiSample::initialise()
{
    // Setup renderer selection dialog for Win32
#if defined( __WIN32__ ) || defined( _WIN32 )
    d_rendererSelector = new Win32CEGuiRendererSelector;

    // enable renderer types supported for Win32
    d_rendererSelector->setRendererAvailability(Direct3D81GuiRendererType);
    d_rendererSelector->setRendererAvailability(Direct3D9GuiRendererType);

#elif defined(linux)
    // decide which method to use for renderer selection
#   ifdef CEGUI_SAMPLES_USE_GTK2
        d_rendererSelector = new GTK2CEGuiRendererSelector();
#   else
        d_rendererSelector = new CLICEGuiRendererSelector();
#   endif
#endif

    // enable available renderer types
#ifdef CEGUI_SAMPLES_USE_OGRE
    d_rendererSelector->setRendererAvailability(OgreGuiRendererType);
#endif
#ifdef CEGUI_SAMPLES_USE_OPENGL
    d_rendererSelector->setRendererAvailability(OpenGLGuiRendererType);
#endif
#ifdef CEGUI_SAMPLES_USE_IRRLICHT
    d_rendererSelector->setRendererAvailability(IrrlichtGuiRendererType);
#endif

    // get selection from user
    if (d_rendererSelector->inkokeDialog())
    {
        // create appropriate application type based upon users selection
        switch(d_rendererSelector->getSelectedRendererType())
        {
#ifdef CEGUI_SAMPLES_USE_OGRE
        case OgreGuiRendererType:
            d_sampleApp = new CEGuiOgreBaseApplication();
            break;
#endif
#if defined( __WIN32__ ) || defined( _WIN32 )
        case Direct3D81GuiRendererType:
            d_sampleApp = new CEGuiD3D81BaseApplication();
            break;

        case Direct3D9GuiRendererType:
            d_sampleApp = new CEGuiD3D9BaseApplication();
            break;
#endif
#ifdef CEGUI_SAMPLES_USE_OPENGL
        case OpenGLGuiRendererType:
            d_sampleApp = new CEGuiOpenGLBaseApplication();
            break;
#endif
#ifdef CEGUI_SAMPLES_USE_IRRLICHT
        case IrrlichtGuiRendererType:
            d_sampleApp = new CEGuiIrrlichtBaseApplication();
            break;
#endif

        default:
            // TODO: Throw exception or something!
            break;
        }

        // execute the base application (which sets up the demo via 'this' and runs it.
        if (d_sampleApp->execute(this))
        {
            // signal that app initialised and ran
            return true;
        }

        // sample app did not initialise, delete the object.
        delete d_sampleApp;
        d_sampleApp = 0;
    }

    // delete renderer selector object
    delete d_rendererSelector;
    d_rendererSelector = 0;

    // signal app did not initialise and run.
    return false;
}

/*************************************************************************
    Cleanup the sample application.
*************************************************************************/
void CEGuiSample::cleanup()
{
    if (d_sampleApp)
    {
        d_sampleApp->cleanup();
        delete d_sampleApp;
        d_sampleApp = 0;
    }

    if (d_rendererSelector)
    {
        delete d_rendererSelector;
        d_rendererSelector = 0;
    }

}
<commit_msg>Unified tests for linux platform to test for the same preprocessor define (that being __linux__).<commit_after>/************************************************************************
    filename:   CEGuiSample.cpp
    created:    24/9/2004
    author:     Paul D Turner
*************************************************************************/
/*************************************************************************
    Crazy Eddie's GUI System (http://www.cegui.org.uk)
    Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk)

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

    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 "CEGuiSample.h"

#ifdef HAVE_CONFIG_H
#   include "config.h"
#endif
#include "CEGUIConfig.h"

// includes for renderer selector classes
#if defined( __WIN32__ ) || defined( _WIN32 )
#   include "Win32CEGuiRendererSelector.h"
#elif defined(__linux__)
#   ifdef CEGUI_SAMPLES_USE_GTK2
#       include "GTK2CEGuiRendererSelector.h"
#   else
#       include "CLICEGuiRendererSelector.h"
#   endif
#endif

// includes for application types
#ifdef CEGUI_SAMPLES_USE_OGRE
#   include "CEGuiOgreBaseApplication.h"
#endif
#ifdef CEGUI_SAMPLES_USE_OPENGL
#   include "CEGuiOpenGLBaseApplication.h"
#endif
#ifdef CEGUI_SAMPLES_USE_IRRLICHT
#   include "CEGuiIrrlichtBaseApplication.h"
#endif
#if defined( __WIN32__ ) || defined( _WIN32 )
#   include "CEGuiD3D81BaseApplication.h"
#   include "CEGuiD3D9BaseApplication.h"
#endif
// now we include the base CEGuiBaseApplication just in case someone has managed to
// get this far without any of the renderers.  This ensures the framework will build,
// although there will be no renderers available for selection in the samples.
#include "CEGuiBaseApplication.h"

/*************************************************************************
    Constructor
*************************************************************************/
CEGuiSample::CEGuiSample() :
        d_rendererSelector(0),
        d_sampleApp(0)
{}

/*************************************************************************
    Destructor
*************************************************************************/
CEGuiSample::~CEGuiSample()
{
    if (d_sampleApp)
    {
        d_sampleApp->cleanup();
        delete d_sampleApp;
    }

    if (d_rendererSelector)
    {
        delete d_rendererSelector;
    }

}

/*************************************************************************
    Application entry point
*************************************************************************/
int CEGuiSample::run()
{
    if (initialise())
    {
        cleanup();
    }

    return 0;
}

/*************************************************************************
    Initialise the sample application
*************************************************************************/
bool CEGuiSample::initialise()
{
    // Setup renderer selection dialog for Win32
#if defined( __WIN32__ ) || defined( _WIN32 )
    d_rendererSelector = new Win32CEGuiRendererSelector;

    // enable renderer types supported for Win32
    d_rendererSelector->setRendererAvailability(Direct3D81GuiRendererType);
    d_rendererSelector->setRendererAvailability(Direct3D9GuiRendererType);

#elif defined(__linux__)
    // decide which method to use for renderer selection
#   ifdef CEGUI_SAMPLES_USE_GTK2
        d_rendererSelector = new GTK2CEGuiRendererSelector();
#   else
        d_rendererSelector = new CLICEGuiRendererSelector();
#   endif
#endif

    // enable available renderer types
#ifdef CEGUI_SAMPLES_USE_OGRE
    d_rendererSelector->setRendererAvailability(OgreGuiRendererType);
#endif
#ifdef CEGUI_SAMPLES_USE_OPENGL
    d_rendererSelector->setRendererAvailability(OpenGLGuiRendererType);
#endif
#ifdef CEGUI_SAMPLES_USE_IRRLICHT
    d_rendererSelector->setRendererAvailability(IrrlichtGuiRendererType);
#endif

    // get selection from user
    if (d_rendererSelector->inkokeDialog())
    {
        // create appropriate application type based upon users selection
        switch(d_rendererSelector->getSelectedRendererType())
        {
#ifdef CEGUI_SAMPLES_USE_OGRE
        case OgreGuiRendererType:
            d_sampleApp = new CEGuiOgreBaseApplication();
            break;
#endif
#if defined( __WIN32__ ) || defined( _WIN32 )
        case Direct3D81GuiRendererType:
            d_sampleApp = new CEGuiD3D81BaseApplication();
            break;

        case Direct3D9GuiRendererType:
            d_sampleApp = new CEGuiD3D9BaseApplication();
            break;
#endif
#ifdef CEGUI_SAMPLES_USE_OPENGL
        case OpenGLGuiRendererType:
            d_sampleApp = new CEGuiOpenGLBaseApplication();
            break;
#endif
#ifdef CEGUI_SAMPLES_USE_IRRLICHT
        case IrrlichtGuiRendererType:
            d_sampleApp = new CEGuiIrrlichtBaseApplication();
            break;
#endif

        default:
            // TODO: Throw exception or something!
            break;
        }

        // execute the base application (which sets up the demo via 'this' and runs it.
        if (d_sampleApp->execute(this))
        {
            // signal that app initialised and ran
            return true;
        }

        // sample app did not initialise, delete the object.
        delete d_sampleApp;
        d_sampleApp = 0;
    }

    // delete renderer selector object
    delete d_rendererSelector;
    d_rendererSelector = 0;

    // signal app did not initialise and run.
    return false;
}

/*************************************************************************
    Cleanup the sample application.
*************************************************************************/
void CEGuiSample::cleanup()
{
    if (d_sampleApp)
    {
        d_sampleApp->cleanup();
        delete d_sampleApp;
        d_sampleApp = 0;
    }

    if (d_rendererSelector)
    {
        delete d_rendererSelector;
        d_rendererSelector = 0;
    }

}
<|endoftext|>


<commit_before>#define SOL_CHECK_ARGUMENTS 1

#include <sol.hpp>
#include <string>
#include <memory>
#include <iostream>

int main(int, char**) {
	std::cout << "=== optional and iteration example ===" << std::endl;

	struct thing {
		int a = 20;

		thing() = default;
		thing(int a) : a(a) {}
	};

	struct super_thing : thing {
		int b = 40;
	};

	struct unrelated {

	};

	sol::state lua;

	// Comment out the new_usertype call
	// to prevent derived class "super_thing"
	// from being picked up and cast to its base
	// class
	lua.new_usertype<super_thing>("super_thing",
		sol::base_classes, sol::bases<thing>()
	);

	// Make a few things
	lua["t1"] = thing{};
	lua["t2"] = super_thing{};
	lua["t3"] = unrelated{};
	// And a table
	lua["container"] = lua.create_table_with(
		0, thing{50},
		1, unrelated{},
		4, super_thing{}
	);

	std::vector<std::reference_wrapper<thing>> things;
	// Our recursive function
	// We use some lambda techniques and pass the function itself itself so we can recurse,
	// but a regular function would work too!
	auto fx = [&lua, &things](auto& f, auto& tbl) -> void {
		// You can iterate through a table: it has
		// begin() and end()
		// like standard containers
		for (auto key_value_pair : tbl) {
			// Note that iterators are extremely frail
			// and should not be used outside of
			// well-constructed for loops
			// that use pre-increment ++,
			// or C++ ranged-for loops
			const sol::object& key = key_value_pair.first;
			const sol::object& value = key_value_pair.second;
			sol::type t = value.get_type();
			switch (t) {
			case sol::type::table:
				f(f, value.as<sol::table>());
				break;
			case sol::type::userdata: {
				// This allows us to check if a userdata is
				// a specific class type
				sol::optional<thing&> maybe_thing = value.as<sol::optional<thing&>>();
				if (maybe_thing) {
					thing& the_thing = maybe_thing.value();
					if (key.is<std::string>()) {
						std::cout << "key " << key.as<std::string>() << " is a thing -- ";
					}
					else if (key.is<int>()) {
						std::cout << "key " << key.as<int>() << " is a thing -- ";
					}
					std::cout << "thing.a ==" << the_thing.a << std::endl;
					things.push_back(the_thing);
				}
			}
			break;
			default:
				break;
			}
		}
	};
	fx(fx, lua);

	std::cout << std::endl;

	return 0;
}
<commit_msg>This references thing is really going to hurt me from VC++ one day in production<commit_after>#define SOL_CHECK_ARGUMENTS 1

#include <sol.hpp>
#include <string>
#include <memory>
#include <iostream>

int main(int, char**) {
	std::cout << "=== optional and iteration example ===" << std::endl;

	struct thing {
		int a = 20;

		thing() = default;
		thing(int a) : a(a) {}
	};

	struct super_thing : thing {
		int b = 40;
	};

	struct unrelated {

	};

	sol::state lua;

	// Comment out the new_usertype call
	// to prevent derived class "super_thing"
	// from being picked up and cast to its base
	// class
	lua.new_usertype<super_thing>("super_thing",
		sol::base_classes, sol::bases<thing>()
	);

	// Make a few things
	lua["t1"] = thing{};
	lua["t2"] = super_thing{};
	lua["t3"] = unrelated{};
	// And a table
	lua["container"] = lua.create_table_with(
		0, thing{50},
		1, unrelated{},
		4, super_thing{}
	);

	std::vector<std::reference_wrapper<thing>> things;
	// Our recursive function
	// We use some lambda techniques and pass the function itself itself so we can recurse,
	// but a regular function would work too!
	auto fx = [&lua, &things](auto& f, auto tbl) -> void {
		// You can iterate through a table: it has
		// begin() and end()
		// like standard containers
		for (auto key_value_pair : tbl) {
			// Note that iterators are extremely frail
			// and should not be used outside of
			// well-constructed for loops
			// that use pre-increment ++,
			// or C++ ranged-for loops
			const sol::object& key = key_value_pair.first;
			const sol::object& value = key_value_pair.second;
			sol::type t = value.get_type();
			switch (t) {
			case sol::type::table:
				f(f, value.as<sol::table>());
				break;
			case sol::type::userdata: {
				// This allows us to check if a userdata is
				// a specific class type
				sol::optional<thing&> maybe_thing = value.as<sol::optional<thing&>>();
				if (maybe_thing) {
					thing& the_thing = maybe_thing.value();
					if (key.is<std::string>()) {
						std::cout << "key " << key.as<std::string>() << " is a thing -- ";
					}
					else if (key.is<int>()) {
						std::cout << "key " << key.as<int>() << " is a thing -- ";
					}
					std::cout << "thing.a ==" << the_thing.a << std::endl;
					things.push_back(the_thing);
				}
			}
			break;
			default:
				break;
			}
		}
	};
	fx(fx, lua);

	std::cout << std::endl;

	return 0;
}
<|endoftext|>


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

#include <osg/Notify>
#include <osgDB/ReadFile>
#include <osgGA/TrackballManipulator>
#include <osgViewer/Viewer>

int main( int argc, char **argv )
{
    osg::ArgumentParser arguments(&argc,argv);

    // initialize the viewer.
    osgViewer::Viewer viewer(arguments);

    osg::ref_ptr<osg::Node> model = osgDB::readNodeFiles(arguments);

    if (!model)
    {
        OSG_NOTICE<<"No models loaded, please specify a model file on the command line"<<std::endl;
        return 1;
    }

    viewer.setSceneData(model.get());

    viewer.setCameraManipulator(new osgGA::TrackballManipulator());

    return viewer.run();
}
<commit_msg>Experiments with modifying the projection matrix to provide keystoning.<commit_after>/* OpenSceneGraph example, osganimate.
*
*  Permission is hereby granted, free of charge, to any person obtaining a copy
*  of this software and associated documentation files (the "Software"), to deal
*  in the Software without restriction, including without limitation the rights
*  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
*  copies of the Software, and to permit persons to whom the Software is
*  furnished to do so, subject to the following conditions:
*
*  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
*  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
*  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
*  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
*  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
*  THE SOFTWARE.
*/

#include <osg/Notify>
#include <osg/io_utils>

#include <osgDB/ReadFile>
#include <osgGA/TrackballManipulator>
#include <osgViewer/Viewer>

int main( int argc, char **argv )
{
    osg::ArgumentParser arguments(&argc,argv);

    // initialize the viewer.
    osgViewer::Viewer viewer(arguments);

    osg::Vec2d translate(0.0,0.0);
    osg::Vec2d scale(1.0,1.0);
    osg::Vec2d taper(1.0,1.0);
    double angle = 0; // osg::inDegrees(45.0);

    if (arguments.read("-a",angle)) { OSG_NOTICE<<"angle = "<<angle<<std::endl; angle = osg::inDegrees(angle); }
    if (arguments.read("-t",translate.x(), translate.y())) { OSG_NOTICE<<"translate = "<<translate<<std::endl;}
    if (arguments.read("-s",scale.x(), scale.y())) { OSG_NOTICE<<"scale = "<<scale<<std::endl;}
    if (arguments.read("-k",taper.x(), taper.y())) { OSG_NOTICE<<"taper = "<<taper<<std::endl;}

    osg::ref_ptr<osg::Node> model = osgDB::readNodeFiles(arguments);

    if (!model)
    {
        OSG_NOTICE<<"No models loaded, please specify a model file on the command line"<<std::endl;
        return 1;
    }

    viewer.setSceneData(model.get());

    viewer.setCameraManipulator(new osgGA::TrackballManipulator());

    viewer.realize();

    viewer.getCamera()->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);

    osg::Matrixd& pm = viewer.getCamera()->getProjectionMatrix();

    pm.postMultRotate(osg::Quat(angle, osg::Vec3d(0.0,0.0,1.0)));
    pm.postMultScale(osg::Vec3d(scale.x(),scale.y(),1.0));
    pm.postMultTranslate(osg::Vec3d(translate.x(),translate.y(),0.0));

    if (taper.x()!=1.0)
    {
        double x0 = (1.0+taper.x())/(1-taper.x());
        OSG_NOTICE<<"x0 = "<<x0<<std::endl;

        pm.postMult(osg::Matrixd(1.0-x0, 0.0,    0.0,    1.0,
                                 0.0,    1.0-x0, 0.0,    0.0,
                                 0.0,    0.0,    (1.0-x0)*0.5, 0.0,
                                 0.0,    0.0,    0.0,    -x0));
    }

    return viewer.run();
}
<|endoftext|>


<commit_before>/*
 * @file opencog/embodiment/Control/OperationalAvatarController/PatternMiningAgent.cc
 *
 * @author Shujing Ke <rainkekekeke@gmail.com>
 * @date   2014-04-11
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */
#include <boost/tokenizer.hpp>
#include <boost/lexical_cast.hpp>

#include <opencog/atomspace/SimpleTruthValue.h>
#include <opencog/spacetime/TimeServer.h>
#include <opencog/util/Config.h>
#include <opencog/guile/load-file.h>
#include "OAC.h"
#include "PatternMiningAgent.h"

using namespace opencog::oac;

PatternMiningAgent::~PatternMiningAgent()
{
}

PatternMiningAgent::PatternMiningAgent(CogServer& cs) : Agent(cs)
{
    this->cycleCount = 0;

    // Force the Agent initialize itself during its first cycle.
    this->forceInitNextCycle();
}

void PatternMiningAgent::init()
{
    logger().debug( "PatternMiningAgent::%s - Initialize the Agent [cycle = %d]",
                    __FUNCTION__, this->cycleCount);

    // Get OAC
    OAC* oac = dynamic_cast<OAC*>(&_cogserver);
    OC_ASSERT(oac, "Did not get an OAC server");

    // Get AtomSpace
    corpusAtomSpace = new AtomSpace();

    // load test corpus
    if ( load_scm_file( *(this->corpusAtomSpace), "pm_test_corpus.scm" ) == 0  )
        logger().info( "PatternMiningAgent::%s - Loaded pattern miner test corpus file: '%s'",
                        __FUNCTION__,
                       "pm_test_corpus.scm"
                     );
    else
        logger().error( "PatternMiningAgent::%s - Failed to load pattern miner test corpus file: '%s'",
                         __FUNCTION__,
                        "pm_test_corpus.scm"
                      );

    cout << "PatternMiningAgent: init: loaded test corpus into corpusAtomSpace \n ";

    // create a pattern miner
    this->patternMiner = new PatternMiner(corpusAtomSpace,config().get_int("PATTERN_MAX_GRAM"));

    // Avoid initialize during next cycle
    this->bInitialized = true;

    cout << "PatternMiningAgent: init finished!\n ";
}

void PatternMiningAgent::run()
{
    this->cycleCount = _cogserver.getCycleCount();

    logger().debug( "PatternMiningAgent::%s - Executing run %d times",
                     __FUNCTION__, this->cycleCount);

    // Get OAC
    OAC* oac = dynamic_cast<OAC*>(&_cogserver);
    OC_ASSERT(oac, "Did not get an OAC server!");

    // Initialize the Agent (demandList etc)
    if ( !this->bInitialized )
        this->init();

    // test, only run once
    static bool hasRun = false;
    if (hasRun)
        return;
    this->patternMiner->runPatternMiner();
    hasRun = true;

}
<commit_msg>Added the necessary pre-load scm files into corpus Atomspace.<commit_after>/*
 * @file opencog/embodiment/Control/OperationalAvatarController/PatternMiningAgent.cc
 *
 * @author Shujing Ke <rainkekekeke@gmail.com>
 * @date   2014-04-11
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */
#include <boost/tokenizer.hpp>
#include <boost/lexical_cast.hpp>

#include <opencog/atomspace/SimpleTruthValue.h>
#include <opencog/spacetime/TimeServer.h>
#include <opencog/util/Config.h>
#include <opencog/guile/load-file.h>
#include <opencog/guile/SchemeEval.h>
#include <opencog/embodiment/AtomSpaceExtensions/atom_types.h>
#include <opencog/embodiment/AtomSpaceExtensions/AtomSpaceUtil.h>
#include "OAC.h"
#include "PatternMiningAgent.h"

using namespace opencog::oac;

PatternMiningAgent::~PatternMiningAgent()
{
}

PatternMiningAgent::PatternMiningAgent(CogServer& cs) : Agent(cs)
{
    this->cycleCount = 0;

    // Force the Agent initialize itself during its first cycle.
    this->forceInitNextCycle();
}

void PatternMiningAgent::init()
{
    sleep(15);
    logger().debug( "PatternMiningAgent::%s - Initialize the Agent [cycle = %d]",
                    __FUNCTION__, this->cycleCount);

    // Get OAC
    OAC* oac = dynamic_cast<OAC*>(&_cogserver);
    OC_ASSERT(oac, "Did not get an OAC server");

    // create corpus AtomSpace
    corpusAtomSpace = new AtomSpace();

    // pre-load scm files:
//    SCM_PRELOAD           = scm/core_types.scm,
//                            scm/spacetime_types.scm,
//                            scm/nlp_types.scm,
//                            scm/attention_types.scm,
//                            scm/embodiment_types.scm,
//                            scm/persistence.scm,
//                            scm/utilities.scm,
//                            scm/file-utils.scm,
//                            scm/debug.scm,

    load_scm_file( *(this->corpusAtomSpace), "./scm/core_types.scm" );
    load_scm_file( *(this->corpusAtomSpace), "./scm/spacetime_types.scm" );
    load_scm_file( *(this->corpusAtomSpace), "./scm/nlp_types.scm" );
    load_scm_file( *(this->corpusAtomSpace), "./scm/attention_types.scm" );
    load_scm_file( *(this->corpusAtomSpace), "./scm/embodiment_types.scm" );
    load_scm_file( *(this->corpusAtomSpace), "./scm/persistence.scm" );
    load_scm_file( *(this->corpusAtomSpace), "./scm/utilities.scm" );
    load_scm_file( *(this->corpusAtomSpace), "./scm/file-utils.scm" );
    load_scm_file( *(this->corpusAtomSpace), "./scm/debug.scm" );

    // load test corpus
    if ( load_scm_file( *(this->corpusAtomSpace), "./pm_test_corpus.scm" ) == 0  )
        logger().info( "PatternMiningAgent::%s - Loaded pattern miner test corpus file: '%s'",
                        __FUNCTION__,
                       "pm_test_corpus.scm"
                     );
    else
        logger().error( "PatternMiningAgent::%s - Failed to load pattern miner test corpus file: '%s'",
                         __FUNCTION__,
                        "pm_test_corpus.scm"
                      );

    cout << "PatternMiningAgent: init: loaded test corpus into corpusAtomSpace \n ";

    // create a pattern miner
    this->patternMiner = new PatternMiner(corpusAtomSpace,config().get_int("PATTERN_MAX_GRAM"));

    // Avoid initialize during next cycle
    this->bInitialized = true;

    cout << "PatternMiningAgent: init finished!\n ";
}

void PatternMiningAgent::run()
{
    this->cycleCount = _cogserver.getCycleCount();

    logger().debug( "PatternMiningAgent::%s - Executing run %d times",
                     __FUNCTION__, this->cycleCount);

    // Get OAC
    OAC* oac = dynamic_cast<OAC*>(&_cogserver);
    OC_ASSERT(oac, "Did not get an OAC server!");

    // Initialize the Agent (demandList etc)
    if ( !this->bInitialized )
        this->init();

    // test, only run once
    static bool hasRun = false;
    if (hasRun)
        return;
    this->patternMiner->runPatternMiner();
    hasRun = true;

}
<|endoftext|>


<commit_before><commit_msg>CUDA/CPU test for NegativeLogLikelihoodLoss(12) function based loss operator. (#3793)<commit_after><|endoftext|>


<commit_before>/*
 * Copyright 2017-present Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <folly/logging/CustomLogFormatter.h>

#include <folly/Format.h>
#include <folly/logging/LogLevel.h>
#include <folly/logging/LogMessage.h>
#include <folly/portability/Time.h>
#include <algorithm>

namespace {
using folly::LogLevel;
using folly::StringPiece;

StringPiece getGlogLevelName(LogLevel level) {
  if (level < LogLevel::INFO) {
    return "VERBOSE";
  } else if (level < LogLevel::WARN) {
    return "INFO";
  } else if (level < LogLevel::ERR) {
    return "WARNING";
  } else if (level < LogLevel::CRITICAL) {
    return "ERROR";
  } else if (level < LogLevel::DFATAL) {
    return "CRITICAL";
  }
  return "FATAL";
}

StringPiece getResetSequence(LogLevel level) {
  if (level >= LogLevel::INFO && level < LogLevel::WARN) {
    return "\e[0m";
  } else {
    return "";
  }
}

StringPiece getColorSequence(LogLevel level) {
  if (level < LogLevel::INFO) {
    return "\e[1;30m"; // BOLD/BRIGHT BLACK ~ GREY
  } else if (level < LogLevel::WARN) {
    return ""; // NO COLOR
  } else if (level < LogLevel::ERR) {
    return "\e[33m"; // YELLOW
  } else if (level < LogLevel::CRITICAL) {
    return "\e[31m"; // RED
  }
  return "\e[1;41m"; // BOLD ON RED BACKGROUND
}

struct FormatKeys {
  const StringPiece key;
  const std::size_t argIndex;
  const std::size_t width;

  constexpr FormatKeys(
      StringPiece key_,
      std::size_t argIndex_,
      std::size_t width_ = 0)
      : key(key_), argIndex(argIndex_), width(width_) {}
};

/**
 * The first part of pairs in this array are the key names and the second part
 * of the pairs are the argument index for folly::format().
 *
 * NOTE: This array must be sorted by key name, since we use std::lower_bound
 * to search in it.
 *
 * TODO: Support including thread names and thread context info.
 */
constexpr std::array<FormatKeys, 11> formatKeys{{
    FormatKeys(/* key */ "D", /*      argIndex  */ 2, /* width */ 2),
    FormatKeys(/* key */ "FILE", /*   argIndex  */ 8),
    FormatKeys(/* key */ "FUN", /*    argIndex  */ 9),
    FormatKeys(/* key */ "H", /*      argIndex  */ 3, /* width */ 2),
    FormatKeys(/* key */ "L", /*      argIndex  */ 0, /* width */ 1),
    FormatKeys(/* key */ "LINE", /*   argIndex */ 10, /* width */ 4),
    FormatKeys(/* key */ "M", /*      argIndex  */ 4, /* width */ 2),
    FormatKeys(/* key */ "S", /*      argIndex  */ 5, /* width */ 2),
    FormatKeys(/* key */ "THREAD", /* argIndex  */ 7, /* width */ 5),
    FormatKeys(/* key */ "USECS", /*  argIndex  */ 6, /* width */ 6),
    FormatKeys(/* key */ "m", /*      argIndex  */ 1, /* width */ 2),
}};
constexpr int messageIndex = formatKeys.size();

} // namespace

namespace folly {

CustomLogFormatter::CustomLogFormatter(StringPiece format, bool colored)
    : colored_(colored) {
  parseFormatString(format);
}

void CustomLogFormatter::parseFormatString(StringPiece input) {
  std::size_t estimatedWidth = 0;
  functionNameCount_ = 0;
  fileNameCount_ = 0;
  // Replace all format keys to numbers to improve performance and to use
  // varying value types (which is not possible using folly::vformat()).
  std::string output;
  output.reserve(input.size());
  const char* varNameStart = nullptr;

  enum StateEnum {
    LITERAL,
    FMT_NAME,
    FMT_MODIFIERS,
  } state = LITERAL;

  for (const char* p = input.begin(); p < input.end(); ++p) {
    switch (state) {
      case LITERAL:
        output.append(p, 1);
        // In case of `{{` or `}}`, copy it as it is and only increment the
        // estimatedWidth once as it will result to a single character in
        // output.
        if ((p + 1) != input.end() /* ensure not last character */ &&
            (0 == memcmp(p, "}}", 2) || 0 == memcmp(p, "{{", 2))) {
          output.append(p + 1, 1);
          estimatedWidth++;
          p++;
        }
        // If we see a single open curly brace, it denotes a start of a format
        // name and so we change the state to FMT_NAME and do not increment
        // estimatedWidth as it won't be in the output.
        else if (*p == '{') {
          varNameStart = p + 1;
          state = FMT_NAME;
        }
        // In case it is just a regular literal, just increment estimatedWidth
        // by one and move on to the next character.
        else {
          estimatedWidth++;
        }
        break;
      // In case we have started processing a format name/key
      case FMT_NAME:
        // Unless it is the end of the format name/key, do nothing and scan over
        // the name/key. When it is the end of the format name/key, look up
        // the argIndex for it and replace the name/key with that index.
        if (*p == ':' || *p == '}') {
          StringPiece varName(varNameStart, p);
          auto item = std::lower_bound(
              formatKeys.begin(),
              formatKeys.end(),
              varName,
              [](const auto& a, const auto& b) { return a.key < b; });

          if (UNLIKELY(item == formatKeys.end() || item->key != varName)) {
            throw std::runtime_error(folly::to<std::string>(
                "unknown format argument \"", varName, "\""));
          }
          output.append(folly::to<std::string>(item->argIndex));
          output.append(p, 1);

          // Based on the format key, increment estimatedWidth with the
          // estimate of how many characters long the value of the format key
          // will be. If it is a FILE or a FUN, the width will be variable
          // depending on the values of those fields.
          estimatedWidth += item->width;
          if (item->key == "FILE") {
            fileNameCount_++;
          } else if (item->key == "FUN") {
            functionNameCount_++;
          }

          // Figure out if there are modifiers that follow the key or if we
          // continue processing literals.
          if (*p == ':') {
            state = FMT_MODIFIERS;
          } else {
            state = LITERAL;
          }
        }
        break;
      // In case we have started processing a format modifier (after :)
      case FMT_MODIFIERS:
        // Modifiers are just copied as is and are not considered to determine
        // the estimatedWidth.
        output.append(p, 1);
        if (*p == '}') {
          state = LITERAL;
        }
        break;
    }
  }
  if (state != LITERAL) {
    throw std::runtime_error("unterminated format string");
  }
  // Append a single space after the header format if header is not empty.
  if (!output.empty()) {
    output.append(" ");
    estimatedWidth++;
  }
  logFormat_ = output;
  staticEstimatedWidth_ = estimatedWidth;

  // populate singleLineLogFormat_ with the padded line format.
  if (colored_) {
    singleLineLogFormat_ = folly::to<std::string>(
        "{",
        messageIndex + 1,
        "}",
        logFormat_,
        "{",
        messageIndex,
        "}{",
        messageIndex + 2,
        "}\n");
  } else {
    singleLineLogFormat_ =
        folly::to<std::string>(logFormat_, "{", messageIndex, "}\n");
  }
}

std::string CustomLogFormatter::formatMessage(
    const LogMessage& message,
    const LogCategory* /* handlerCategory */) {
  // Get the local time info
  struct tm ltime;
  auto timeSinceEpoch = message.getTimestamp().time_since_epoch();
  auto epochSeconds =
      std::chrono::duration_cast<std::chrono::seconds>(timeSinceEpoch);
  std::chrono::microseconds usecs =
      std::chrono::duration_cast<std::chrono::microseconds>(timeSinceEpoch) -
      epochSeconds;
  time_t unixTimestamp = epochSeconds.count();
  if (!localtime_r(&unixTimestamp, &ltime)) {
    memset(&ltime, 0, sizeof(ltime));
  }

  auto basename = message.getFileBaseName();

  // Most common logs will be single line logs and so we can format the entire
  // log string including the message at once.
  if (!message.containsNewlines()) {
    return folly::sformat(
        singleLineLogFormat_,
        getGlogLevelName(message.getLevel())[0],
        ltime.tm_mon + 1,
        ltime.tm_mday,
        ltime.tm_hour,
        ltime.tm_min,
        ltime.tm_sec,
        usecs.count(),
        message.getThreadID(),
        basename,
        message.getFunctionName(),
        message.getLineNumber(),
        // NOTE: THE FOLLOWING ARGUMENTS ALWAYS NEED TO BE THE LAST 3:
        message.getMessage(),
        // If colored logs are enabled, the singleLineLogFormat_ will contain
        // placeholders for the color and the reset sequences. If not, then
        // the following params will just be ignored by the folly::sformat().
        getColorSequence(message.getLevel()),
        getResetSequence(message.getLevel()));
  }
  // If the message contains multiple lines, ensure that the log header is
  // prepended before each message line.
  else {
    const auto headerFormatter = folly::format(
        logFormat_,
        getGlogLevelName(message.getLevel())[0],
        ltime.tm_mon + 1,
        ltime.tm_mday,
        ltime.tm_hour,
        ltime.tm_min,
        ltime.tm_sec,
        usecs.count(),
        message.getThreadID(),
        basename,
        message.getFunctionName(),
        message.getLineNumber());

    // Estimate header length. If this still isn't long enough the string will
    // grow as necessary, so the code will still be correct, but just slightly
    // less efficient than if we had allocated a large enough buffer the first
    // time around.
    size_t headerLengthGuess = staticEstimatedWidth_ +
        (fileNameCount_ * basename.size()) +
        (functionNameCount_ * message.getFunctionName().size());

    // Format the data into a buffer.
    std::string buffer;
    // If colored logging is supported, then process the color based on
    // the level of the message.
    if (colored_) {
      buffer.append(getColorSequence(message.getLevel()).toString());
    }
    StringPiece msgData{message.getMessage()};

    // Make a guess at how many lines will be in the message, just to make an
    // initial buffer allocation.  If the guess is too small then the string
    // will reallocate and grow as necessary, it will just be slightly less
    // efficient than if we had guessed enough space.
    size_t numLinesGuess = 4;
    buffer.reserve((headerLengthGuess * numLinesGuess) + msgData.size());

    size_t idx = 0;
    while (true) {
      auto end = msgData.find('\n', idx);
      if (end == StringPiece::npos) {
        end = msgData.size();
      }

      auto line = msgData.subpiece(idx, end - idx);
      headerFormatter.appendTo(buffer);
      buffer.append(line.data(), line.size());
      buffer.push_back('\n');

      if (end == msgData.size()) {
        break;
      }
      idx = end + 1;
    }
    // If colored logging is supported and the current message is a color other
    // than the default, then RESET colors after printing message.
    if (colored_) {
      buffer.append(getResetSequence(message.getLevel()).toString());
    }
    return buffer;
  }
}
} // namespace folly
<commit_msg>Escape the escape sequences in CustomLogFormatter<commit_after>/*
 * Copyright 2017-present Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <folly/logging/CustomLogFormatter.h>

#include <folly/Format.h>
#include <folly/logging/LogLevel.h>
#include <folly/logging/LogMessage.h>
#include <folly/portability/Time.h>
#include <algorithm>

namespace {
using folly::LogLevel;
using folly::StringPiece;

StringPiece getGlogLevelName(LogLevel level) {
  if (level < LogLevel::INFO) {
    return "VERBOSE";
  } else if (level < LogLevel::WARN) {
    return "INFO";
  } else if (level < LogLevel::ERR) {
    return "WARNING";
  } else if (level < LogLevel::CRITICAL) {
    return "ERROR";
  } else if (level < LogLevel::DFATAL) {
    return "CRITICAL";
  }
  return "FATAL";
}

StringPiece getResetSequence(LogLevel level) {
  if (level >= LogLevel::INFO && level < LogLevel::WARN) {
    return "\033[0m";
  } else {
    return "";
  }
}

StringPiece getColorSequence(LogLevel level) {
  if (level < LogLevel::INFO) {
    return "\033[1;30m"; // BOLD/BRIGHT BLACK ~ GREY
  } else if (level < LogLevel::WARN) {
    return ""; // NO COLOR
  } else if (level < LogLevel::ERR) {
    return "\033[33m"; // YELLOW
  } else if (level < LogLevel::CRITICAL) {
    return "\033[31m"; // RED
  }
  return "\033[1;41m"; // BOLD ON RED BACKGROUND
}

struct FormatKeys {
  const StringPiece key;
  const std::size_t argIndex;
  const std::size_t width;

  constexpr FormatKeys(
      StringPiece key_,
      std::size_t argIndex_,
      std::size_t width_ = 0)
      : key(key_), argIndex(argIndex_), width(width_) {}
};

/**
 * The first part of pairs in this array are the key names and the second part
 * of the pairs are the argument index for folly::format().
 *
 * NOTE: This array must be sorted by key name, since we use std::lower_bound
 * to search in it.
 *
 * TODO: Support including thread names and thread context info.
 */
constexpr std::array<FormatKeys, 11> formatKeys{{
    FormatKeys(/* key */ "D", /*      argIndex  */ 2, /* width */ 2),
    FormatKeys(/* key */ "FILE", /*   argIndex  */ 8),
    FormatKeys(/* key */ "FUN", /*    argIndex  */ 9),
    FormatKeys(/* key */ "H", /*      argIndex  */ 3, /* width */ 2),
    FormatKeys(/* key */ "L", /*      argIndex  */ 0, /* width */ 1),
    FormatKeys(/* key */ "LINE", /*   argIndex */ 10, /* width */ 4),
    FormatKeys(/* key */ "M", /*      argIndex  */ 4, /* width */ 2),
    FormatKeys(/* key */ "S", /*      argIndex  */ 5, /* width */ 2),
    FormatKeys(/* key */ "THREAD", /* argIndex  */ 7, /* width */ 5),
    FormatKeys(/* key */ "USECS", /*  argIndex  */ 6, /* width */ 6),
    FormatKeys(/* key */ "m", /*      argIndex  */ 1, /* width */ 2),
}};
constexpr int messageIndex = formatKeys.size();

} // namespace

namespace folly {

CustomLogFormatter::CustomLogFormatter(StringPiece format, bool colored)
    : colored_(colored) {
  parseFormatString(format);
}

void CustomLogFormatter::parseFormatString(StringPiece input) {
  std::size_t estimatedWidth = 0;
  functionNameCount_ = 0;
  fileNameCount_ = 0;
  // Replace all format keys to numbers to improve performance and to use
  // varying value types (which is not possible using folly::vformat()).
  std::string output;
  output.reserve(input.size());
  const char* varNameStart = nullptr;

  enum StateEnum {
    LITERAL,
    FMT_NAME,
    FMT_MODIFIERS,
  } state = LITERAL;

  for (const char* p = input.begin(); p < input.end(); ++p) {
    switch (state) {
      case LITERAL:
        output.append(p, 1);
        // In case of `{{` or `}}`, copy it as it is and only increment the
        // estimatedWidth once as it will result to a single character in
        // output.
        if ((p + 1) != input.end() /* ensure not last character */ &&
            (0 == memcmp(p, "}}", 2) || 0 == memcmp(p, "{{", 2))) {
          output.append(p + 1, 1);
          estimatedWidth++;
          p++;
        }
        // If we see a single open curly brace, it denotes a start of a format
        // name and so we change the state to FMT_NAME and do not increment
        // estimatedWidth as it won't be in the output.
        else if (*p == '{') {
          varNameStart = p + 1;
          state = FMT_NAME;
        }
        // In case it is just a regular literal, just increment estimatedWidth
        // by one and move on to the next character.
        else {
          estimatedWidth++;
        }
        break;
      // In case we have started processing a format name/key
      case FMT_NAME:
        // Unless it is the end of the format name/key, do nothing and scan over
        // the name/key. When it is the end of the format name/key, look up
        // the argIndex for it and replace the name/key with that index.
        if (*p == ':' || *p == '}') {
          StringPiece varName(varNameStart, p);
          auto item = std::lower_bound(
              formatKeys.begin(),
              formatKeys.end(),
              varName,
              [](const auto& a, const auto& b) { return a.key < b; });

          if (UNLIKELY(item == formatKeys.end() || item->key != varName)) {
            throw std::runtime_error(folly::to<std::string>(
                "unknown format argument \"", varName, "\""));
          }
          output.append(folly::to<std::string>(item->argIndex));
          output.append(p, 1);

          // Based on the format key, increment estimatedWidth with the
          // estimate of how many characters long the value of the format key
          // will be. If it is a FILE or a FUN, the width will be variable
          // depending on the values of those fields.
          estimatedWidth += item->width;
          if (item->key == "FILE") {
            fileNameCount_++;
          } else if (item->key == "FUN") {
            functionNameCount_++;
          }

          // Figure out if there are modifiers that follow the key or if we
          // continue processing literals.
          if (*p == ':') {
            state = FMT_MODIFIERS;
          } else {
            state = LITERAL;
          }
        }
        break;
      // In case we have started processing a format modifier (after :)
      case FMT_MODIFIERS:
        // Modifiers are just copied as is and are not considered to determine
        // the estimatedWidth.
        output.append(p, 1);
        if (*p == '}') {
          state = LITERAL;
        }
        break;
    }
  }
  if (state != LITERAL) {
    throw std::runtime_error("unterminated format string");
  }
  // Append a single space after the header format if header is not empty.
  if (!output.empty()) {
    output.append(" ");
    estimatedWidth++;
  }
  logFormat_ = output;
  staticEstimatedWidth_ = estimatedWidth;

  // populate singleLineLogFormat_ with the padded line format.
  if (colored_) {
    singleLineLogFormat_ = folly::to<std::string>(
        "{",
        messageIndex + 1,
        "}",
        logFormat_,
        "{",
        messageIndex,
        "}{",
        messageIndex + 2,
        "}\n");
  } else {
    singleLineLogFormat_ =
        folly::to<std::string>(logFormat_, "{", messageIndex, "}\n");
  }
}

std::string CustomLogFormatter::formatMessage(
    const LogMessage& message,
    const LogCategory* /* handlerCategory */) {
  // Get the local time info
  struct tm ltime;
  auto timeSinceEpoch = message.getTimestamp().time_since_epoch();
  auto epochSeconds =
      std::chrono::duration_cast<std::chrono::seconds>(timeSinceEpoch);
  std::chrono::microseconds usecs =
      std::chrono::duration_cast<std::chrono::microseconds>(timeSinceEpoch) -
      epochSeconds;
  time_t unixTimestamp = epochSeconds.count();
  if (!localtime_r(&unixTimestamp, &ltime)) {
    memset(&ltime, 0, sizeof(ltime));
  }

  auto basename = message.getFileBaseName();

  // Most common logs will be single line logs and so we can format the entire
  // log string including the message at once.
  if (!message.containsNewlines()) {
    return folly::sformat(
        singleLineLogFormat_,
        getGlogLevelName(message.getLevel())[0],
        ltime.tm_mon + 1,
        ltime.tm_mday,
        ltime.tm_hour,
        ltime.tm_min,
        ltime.tm_sec,
        usecs.count(),
        message.getThreadID(),
        basename,
        message.getFunctionName(),
        message.getLineNumber(),
        // NOTE: THE FOLLOWING ARGUMENTS ALWAYS NEED TO BE THE LAST 3:
        message.getMessage(),
        // If colored logs are enabled, the singleLineLogFormat_ will contain
        // placeholders for the color and the reset sequences. If not, then
        // the following params will just be ignored by the folly::sformat().
        getColorSequence(message.getLevel()),
        getResetSequence(message.getLevel()));
  }
  // If the message contains multiple lines, ensure that the log header is
  // prepended before each message line.
  else {
    const auto headerFormatter = folly::format(
        logFormat_,
        getGlogLevelName(message.getLevel())[0],
        ltime.tm_mon + 1,
        ltime.tm_mday,
        ltime.tm_hour,
        ltime.tm_min,
        ltime.tm_sec,
        usecs.count(),
        message.getThreadID(),
        basename,
        message.getFunctionName(),
        message.getLineNumber());

    // Estimate header length. If this still isn't long enough the string will
    // grow as necessary, so the code will still be correct, but just slightly
    // less efficient than if we had allocated a large enough buffer the first
    // time around.
    size_t headerLengthGuess = staticEstimatedWidth_ +
        (fileNameCount_ * basename.size()) +
        (functionNameCount_ * message.getFunctionName().size());

    // Format the data into a buffer.
    std::string buffer;
    // If colored logging is supported, then process the color based on
    // the level of the message.
    if (colored_) {
      buffer.append(getColorSequence(message.getLevel()).toString());
    }
    StringPiece msgData{message.getMessage()};

    // Make a guess at how many lines will be in the message, just to make an
    // initial buffer allocation.  If the guess is too small then the string
    // will reallocate and grow as necessary, it will just be slightly less
    // efficient than if we had guessed enough space.
    size_t numLinesGuess = 4;
    buffer.reserve((headerLengthGuess * numLinesGuess) + msgData.size());

    size_t idx = 0;
    while (true) {
      auto end = msgData.find('\n', idx);
      if (end == StringPiece::npos) {
        end = msgData.size();
      }

      auto line = msgData.subpiece(idx, end - idx);
      headerFormatter.appendTo(buffer);
      buffer.append(line.data(), line.size());
      buffer.push_back('\n');

      if (end == msgData.size()) {
        break;
      }
      idx = end + 1;
    }
    // If colored logging is supported and the current message is a color other
    // than the default, then RESET colors after printing message.
    if (colored_) {
      buffer.append(getResetSequence(message.getLevel()).toString());
    }
    return buffer;
  }
}
} // namespace folly
<|endoftext|>


<commit_before>/* Copyright (c) 2011 Cody Miller, Daniel Norris, Brett Hitchcock.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *****************************************************************************/

#include "Application.h"

#include <CEGUI.h>
#include "Application/NullLogger.h"

#include <RendererModules/Ogre/CEGUIOgreRenderer.h>

#include <boost/asio.hpp>
#include <boost/thread.hpp>

Application::Application()
  : resource_path_ (getResourcePath()),
    config_path_ (getConfigPath())
{
  // Initialize the root system
  root_.reset(initializeRoot(resource_path_, config_path_, resource_path_));

  // Initialize the window
  window_ = initializeWindow();

  // Set up references to all the resources
  initializeResources();

  // Set up the scene manager
  scene_manager_ = initializeSceneManager();

  // Create a new camera
  Graphics::instance()->constructCamera();

  // Constructs the viewports
  initializeViewport();

  // Initialize the input subsystem
  input_system_.reset(initializeInput(root_.get(), window_));

  // Set default mipmap level
  TextureManager::getSingleton().setDefaultNumMipmaps(5);

  // Create any resource listeners (for loading screens)
  //createResourceListener();

  // Load resources
  ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

  // Create the scene
  Graphics::instance()->setup();

  // Add event listeners
  root_->addFrameListener(Engine::instance());

  // Give the Engine what it needs to function
  Engine::instance()->setWindow( window_ );
  Engine::instance()->bindCamera( false ); //Active camera.

  // Initialize the user interface
  //initializeInterface();

  // Connect to the remote server if we're able to
  initializeNetwork();

  // Add event handling functions
  handler_mappings["LocalMovePlayer"] = &Engine::handleLocalMovePlayer;
  handler_mappings["LocalRotatePlayer"] = &Engine::handleLocalRotatePlayer;
  handler_mappings["LocalUDCamera"] = &Engine::handleLocalUDCamera;
  handler_mappings["LocalLRCamera"] = &Engine::handleLocalLRCamera;
  handler_mappings["LocalZoomCamera"] = &Engine::handleLocalZoomCamera;
  handler_mappings["LocalFireCannon"] = &Engine::handleLocalFireCannon;
  handler_mappings["NetworkCreateEntity"] = &Engine::handleNetworkCreateEntity;
  handler_mappings["NetworkDestroyEntity"]= &Engine::handleNetworkDestroyEntity;
  handler_mappings["NetworkMoveEntity"] = &Engine::handleNetworkMoveEntity;
  handler_mappings["NetworkRotateEntity"] = &Engine::handleNetworkRotateEntity;
  handler_mappings["NetworkSetAmbient"] = &Engine::handleNetworkSetAmbient;

}

Application::~Application()
{
  // The boost::shared_ptrs free what needs to be freed here.
}

bool Application::handleQuit(const CEGUI::EventArgs& args)
{
  exit(1);
//  Graphics::instance()->rotateCamera(0.01, 0.0);
}

void Application::go()
{
  root_->startRendering();

  // clean up
  //destroyScene();
}

Ogre::Root* Application::initializeRoot(const Ogre::String& plugin,
                                        const Ogre::String& config,
                                        const Ogre::String& log)
{
  Ogre::Root *r = OGRE_NEW Root( plugin + "plugins.cfg", config + "ogre.cfg", log + "Ogre.log");

  if (r == 0)
    throw "Could not initialize Ogre::Root!";

  return r;
}

void Application::initializeNetwork()
{
  Ogre::ConfigFile *network_config = new Ogre::ConfigFile;

  network_config->load(getConfigPath() + "network.cfg");
  const Ogre::String address = network_config->getSetting("Address");
  const Ogre::String port = network_config->getSetting("Port");

  Network::instance()->connect(address.c_str(), port.c_str());

  // This is necessary to have the networking branch off on its own thread.
  thread_ = boost::thread(boost::bind(&asio::io_service::run, &Network::service()));
}

Ogre::RenderWindow* Application::initializeWindow()
{
  Ogre::RenderWindow* win = NULL;

  if (root_->showConfigDialog())
    win = root_->initialise(true);

  // The case that the user didn't want to configure/wanted to quit
  if (win == 0)
    closeApplication();

  return win;
}

void Application::closeApplication()
{
  Network::instance()->disconnect();
}

void Application::initializeResources()
{
  Ogre::ConfigFile config;
  Ogre::String section, type, arch;

  config.load(resource_path_ + "resources.cfg");

  Ogre::ConfigFile::SectionIterator itr = config.getSectionIterator();

  while (itr.hasMoreElements()) {
    section = itr.peekNextKey();

    Ogre::ConfigFile::SettingsMultiMap* settings = itr.getNext();
    Ogre::ConfigFile::SettingsMultiMap::iterator i;

    for (i = settings->begin(); i != settings->end(); ++i) {
      type = i->first;
      arch = i->second;

      #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE

        // OS X does not set the working directory relative to the app,
        // In order to make things portable on OS X we need to provide
        // the loading with it's own bundle path location

        if (!Ogre::StringUtil::startsWith(arch, "/", false))
    	    arch = String(macBundlePath() + "/" + arch);
      #endif

      ResourceGroupManager::getSingleton().addResourceLocation(arch, type, section);
    }
  }
}

Input* Application::initializeInput(Ogre::Root* root, Ogre::RenderWindow* window)
{
  Input* i = new Input(window);
  root->addFrameListener(i);
  return i;
}

Ogre::SceneManager* Application::initializeSceneManager()
{
  Ogre::SceneManager *mgr = root_->createSceneManager(ST_GENERIC, "ExampleSMInstance");
  Graphics::instance()->setSceneManager(mgr);
  Engine::instance()->setSceneManager(mgr);

  return mgr;
}

void Application::initializeViewport()
{
  // Create one viewport, entire window
  Viewport* vp = window_->addViewport(Graphics::instance()->camera());

  vp->setBackgroundColour(ColourValue(0,0,0));

  // Alter the camera aspect ratio to match the viewport
  Graphics::instance()->camera()->setAspectRatio(Real(vp->getActualWidth()) / Real(vp->getActualHeight()));
}

Ogre::String Application::getResourcePath()
{
  #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
    return macBundlePath() + "/Contents/Resources/";
  #else
    return "";
  #endif
}

Ogre::String Application::getConfigPath()
{
  return getResourcePath();
}

void Application::initializeInterface()
{
  // Prevent a nasty Mac OS X bug with setLogFilename.
  new NullLogger;

  // Initialize the GUI system.
  CEGUI::OgreRenderer &renderer = CEGUI::OgreRenderer::bootstrapSystem(*window_);

  CEGUI::SchemeManager::getSingleton().create("TaharezLook.scheme");
  CEGUI::FontManager::getSingleton().create("DejaVuSans-10.font");
  CEGUI::System::getSingleton().setDefaultMouseCursor("TaharezLook", "MouseArrow");
  CEGUI::Window *root = CEGUI::WindowManager::getSingleton().loadWindowLayout("gui/test.layout");

  CEGUI::System::getSingleton().setGUISheet(root);

  CEGUI::Window *quitButton = CEGUI::WindowManager::getSingleton().getWindow("quitButton");
  quitButton->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&Application::handleQuit, this));
}

<commit_msg>Test.<commit_after>/* Copyright (c) 2011 Cody Miller, Daniel Norris, Brett Hitchcock.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *****************************************************************************/

#include "Application.h"

#include <CEGUI.h>
#include "Application/NullLogger.h"

#include <RendererModules/Ogre/CEGUIOgreRenderer.h>

#include <boost/asio.hpp>
#include <boost/thread.hpp>

Application::Application()
  : resource_path_ (getResourcePath()),
    config_path_ (getConfigPath())
{
  // Initialize the root system
  root_.reset(initializeRoot(resource_path_, config_path_, resource_path_));

  // Initialize the window
  window_ = initializeWindow();

  // Set up references to all the resources
  initializeResources();

  // Set up the scene manager
  scene_manager_ = initializeSceneManager();

  // Create a new camera
  Graphics::instance()->constructCamera();

  // Constructs the viewports
  initializeViewport();

  // Initialize the input subsystem
  input_system_.reset(initializeInput(root_.get(), window_));

  // Set default mipmap level
  TextureManager::getSingleton().setDefaultNumMipmaps(5);

  // Create any resource listeners (for loading screens)
  //createResourceListener();

  // Load resources
  ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

  // Create the scene
  Graphics::instance()->setup();

  // Add event listeners
  root_->addFrameListener(Engine::instance());

  // Give the Engine what it needs to function
  Engine::instance()->setWindow( window_ );
  Engine::instance()->bindCamera( false ); //Active camera.

  // Initialize the user interface
  //initializeInterface();

  // Connect to the remote server if we're able to
  //initializeNetwork();

  // Add event handling functions
  handler_mappings["LocalMovePlayer"] = &Engine::handleLocalMovePlayer;
  handler_mappings["LocalRotatePlayer"] = &Engine::handleLocalRotatePlayer;
  handler_mappings["LocalUDCamera"] = &Engine::handleLocalUDCamera;
  handler_mappings["LocalLRCamera"] = &Engine::handleLocalLRCamera;
  handler_mappings["LocalZoomCamera"] = &Engine::handleLocalZoomCamera;
  handler_mappings["LocalFireCannon"] = &Engine::handleLocalFireCannon;
  handler_mappings["NetworkCreateEntity"] = &Engine::handleNetworkCreateEntity;
  handler_mappings["NetworkDestroyEntity"]= &Engine::handleNetworkDestroyEntity;
  handler_mappings["NetworkMoveEntity"] = &Engine::handleNetworkMoveEntity;
  handler_mappings["NetworkRotateEntity"] = &Engine::handleNetworkRotateEntity;
  handler_mappings["NetworkDamagePlayer"] = &Engine::handleNetworkDamagePlayer;
  handler_mappings["NetworkSetAmbient"] = &Engine::handleNetworkSetAmbient;

}

Application::~Application()
{
  // The boost::shared_ptrs free what needs to be freed here.
}

bool Application::handleQuit(const CEGUI::EventArgs& args)
{
  exit(1);
//  Graphics::instance()->rotateCamera(0.01, 0.0);
}

void Application::go()
{
  root_->startRendering();

  // clean up
  //destroyScene();
}

Ogre::Root* Application::initializeRoot(const Ogre::String& plugin,
                                        const Ogre::String& config,
                                        const Ogre::String& log)
{
  Ogre::Root *r = OGRE_NEW Root( plugin + "plugins.cfg", config + "ogre.cfg", log + "Ogre.log");

  if (r == 0)
    throw "Could not initialize Ogre::Root!";

  return r;
}

void Application::initializeNetwork()
{
  Ogre::ConfigFile *network_config = new Ogre::ConfigFile;

  network_config->load(getConfigPath() + "network.cfg");
  const Ogre::String address = network_config->getSetting("Address");
  const Ogre::String port = network_config->getSetting("Port");

  Network::instance()->connect(address.c_str(), port.c_str());

  // This is necessary to have the networking branch off on its own thread.
  thread_ = boost::thread(boost::bind(&asio::io_service::run, &Network::service()));
}

Ogre::RenderWindow* Application::initializeWindow()
{
  Ogre::RenderWindow* win = NULL;

  if (root_->showConfigDialog())
    win = root_->initialise(true);

  // The case that the user didn't want to configure/wanted to quit
  if (win == 0)
    closeApplication();

  return win;
}

void Application::closeApplication()
{
  Network::instance()->disconnect();
}

void Application::initializeResources()
{
  Ogre::ConfigFile config;
  Ogre::String section, type, arch;

  config.load(resource_path_ + "resources.cfg");

  Ogre::ConfigFile::SectionIterator itr = config.getSectionIterator();

  while (itr.hasMoreElements()) {
    section = itr.peekNextKey();

    Ogre::ConfigFile::SettingsMultiMap* settings = itr.getNext();
    Ogre::ConfigFile::SettingsMultiMap::iterator i;

    for (i = settings->begin(); i != settings->end(); ++i) {
      type = i->first;
      arch = i->second;

      #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE

        // OS X does not set the working directory relative to the app,
        // In order to make things portable on OS X we need to provide
        // the loading with it's own bundle path location

        if (!Ogre::StringUtil::startsWith(arch, "/", false))
    	    arch = String(macBundlePath() + "/" + arch);
      #endif

      ResourceGroupManager::getSingleton().addResourceLocation(arch, type, section);
    }
  }
}

Input* Application::initializeInput(Ogre::Root* root, Ogre::RenderWindow* window)
{
  Input* i = new Input(window);
  root->addFrameListener(i);
  return i;
}

Ogre::SceneManager* Application::initializeSceneManager()
{
  Ogre::SceneManager *mgr = root_->createSceneManager(ST_GENERIC, "ExampleSMInstance");
  Graphics::instance()->setSceneManager(mgr);
  Engine::instance()->setSceneManager(mgr);

  return mgr;
}

void Application::initializeViewport()
{
  // Create one viewport, entire window
  Viewport* vp = window_->addViewport(Graphics::instance()->camera());

  vp->setBackgroundColour(ColourValue(0,0,0));

  // Alter the camera aspect ratio to match the viewport
  Graphics::instance()->camera()->setAspectRatio(Real(vp->getActualWidth()) / Real(vp->getActualHeight()));
}

Ogre::String Application::getResourcePath()
{
  #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
    return macBundlePath() + "/Contents/Resources/";
  #else
    return "";
  #endif
}

Ogre::String Application::getConfigPath()
{
  return getResourcePath();
}

void Application::initializeInterface()
{
  // Prevent a nasty Mac OS X bug with setLogFilename.
  new NullLogger;

  // Initialize the GUI system.
  CEGUI::OgreRenderer &renderer = CEGUI::OgreRenderer::bootstrapSystem(*window_);

  CEGUI::SchemeManager::getSingleton().create("TaharezLook.scheme");
  CEGUI::FontManager::getSingleton().create("DejaVuSans-10.font");
  CEGUI::System::getSingleton().setDefaultMouseCursor("TaharezLook", "MouseArrow");
  CEGUI::Window *root = CEGUI::WindowManager::getSingleton().loadWindowLayout("gui/test.layout");

  CEGUI::System::getSingleton().setGUISheet(root);

  CEGUI::Window *quitButton = CEGUI::WindowManager::getSingleton().getWindow("quitButton");
  quitButton->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&Application::handleQuit, this));
}

<|endoftext|>