<commit_before>#include <errno.h>

#include <QtGlobal>

#ifndef Q_OS_WIN32
    #include <unistd.h>
    #include <sys/stat.h>
#endif

#include <QCoreApplication>
#include <QTextStream>
#include <QStringList>
#include <QFileInfo>

#include "httpdaemon.h"
#include "logging.h"
#include "configuration.h"

int main(int argc, char *argv[])
{
    openlog("http-daemon", LOG_ODELAY, LOG_DAEMON);

    #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
        qInstallMessageHandler(qtOutputToLog);
    #else
        qInstallMsgHandler(qtOutputToLog);
    #endif

    QCoreApplication a(argc, argv);
    a.setObjectName("main app");

    QTextStream out(stdout);
    QTextStream err(stderr);

    #ifndef CONFIG_DIR
        #define CONFIG_DIR "";
    #endif

    Configuration c(CONFIG_DIR CONFIG_FILE_NAME);

    if(!c.read()){
        syslog(LOG_ERR, "Cannot read configuration file at: %s", c.getSettingsPath().toStdString().c_str());
        return 1;
    }

    if(!c.check()){
        syslog(LOG_ERR, "Invalid configuration file at: %s", c.getSettingsPath().toStdString().c_str());
        return 1;
    }

#ifndef Q_OS_WIN32
    pid_t pid = fork();

    if(-1 == pid){
        err << strerror(errno);
        syslog(LOG_ERR, strerror(errno));

        return 1;
    }

    if(pid > 0){
        out << "Successfully forked child with PID: " << pid;
        syslog(LOG_INFO, "Successfully forked child with PID: %i", pid);

        return 0;
    }

    //TODO: become a user (configured via http-daemon.conf)
    umask(0);
    pid_t sid = setsid();

    if(-1 == sid){
        syslog(LOG_ERR, "setsid() failed: %s", strerror(errno));
        return 1;
    }

    if(-1 == chdir("/")){
        syslog(LOG_ERR, "chdir() failed: %s", strerror(errno));
        return 1;
    }

    //TODO: figure out why if I enable these s.listen will fail, create a POC
    //close(STDIN_FILENO);
    //close(STDOUT_FILENO);
    //close(STDERR_FILENO);
#endif

    bool ok;
    int port = Configuration::get("port", 80).toInt(&ok);

    if(!ok){
        port = 80;
    }

    HTTPDaemon s;
    s.setObjectName("HTTPDaemon");

    if(!s.listen(QHostAddress(Configuration::get("address").toString()), port)){
         syslog(LOG_ERR, "Cannot start the server: %s", s.errorString().toStdString().c_str());
         return 1;
    }
    else{
        syslog(LOG_NOTICE, "Listening on %s:%i", s.serverAddress().toString().toStdString().c_str(), s.serverPort());
        syslog(LOG_INFO, "Document root is in: %s\nPlugin root is in: %s",
            Configuration::get("documentroot").toString().toStdString().c_str(),
            Configuration::get("pluginroot").toString().toStdString().c_str());
    }

    return a.exec();
}
<commit_msg>cleanup of syslog calls<commit_after>#include <errno.h>

#include <QtGlobal>

#ifndef Q_OS_WIN32
    #include <unistd.h>
    #include <sys/stat.h>
#endif

#include <QCoreApplication>
#include <QTextStream>
#include <QStringList>
#include <QFileInfo>

#include "httpdaemon.h"
#include "logging.h"
#include "configuration.h"

int main(int argc, char *argv[])
{
    openlog("http-daemon", LOG_ODELAY, LOG_DAEMON);
    atexit(closelog);

    #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
        qInstallMessageHandler(qtOutputToLog);
    #else
        qInstallMsgHandler(qtOutputToLog);
    #endif

    QCoreApplication a(argc, argv);
    a.setObjectName("main app");

    QTextStream out(stdout);
    QTextStream err(stderr);

    #ifndef CONFIG_DIR
        #define CONFIG_DIR "";
    #endif

    Configuration c(CONFIG_DIR CONFIG_FILE_NAME);

    if(!c.read()){
        syslog(LOG_ERR, "Cannot read configuration file at: %s", c.getSettingsPath().toStdString().c_str());
        return 1;
    }

    if(!c.check()){
        syslog(LOG_ERR, "Invalid configuration file at: %s", c.getSettingsPath().toStdString().c_str());
        return 1;
    }

#ifndef Q_OS_WIN32
    pid_t pid = fork();

    if(-1 == pid){
        err << strerror(errno);
        syslog(LOG_ERR, strerror(errno));

        return 1;
    }

    if(pid > 0){
        out << "Successfully forked child with PID: " << pid << endl;
        syslog(LOG_INFO, "Successfully forked child with PID: %i", pid);

        return 0;
    }

    //TODO: become a user (configured via http-daemon.conf)
    umask(0);
    pid_t sid = setsid();

    if(-1 == sid){
        syslog(LOG_ERR, "setsid() failed: %m");
        return 1;
    }

    if(-1 == chdir("/")){
        syslog(LOG_ERR, "chdir() failed: %m");
        return 1;
    }

    //TODO: figure out why if I enable these s.listen will fail, create a POC
    //close(STDIN_FILENO);
    //close(STDOUT_FILENO);
    //close(STDERR_FILENO);
#endif

    bool ok;
    int port = Configuration::get("port", 80).toInt(&ok);

    if(!ok){
        port = 80;
    }

    HTTPDaemon s;
    s.setObjectName("HTTPDaemon");

    if(!s.listen(QHostAddress(Configuration::get("address").toString()), port)){
         syslog(LOG_ERR, "Cannot start the server: %s", s.errorString().toStdString().c_str());
         return 1;
    }
    else{
        syslog(LOG_NOTICE, "Listening on %s:%i", s.serverAddress().toString().toStdString().c_str(), s.serverPort());
        syslog(LOG_INFO, "Document root is in: %s\nPlugin root is in: %s",
            Configuration::get("documentroot").toString().toStdString().c_str(),
            Configuration::get("pluginroot").toString().toStdString().c_str());
    }

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


<commit_before>#include <Disp.h>
#include <GPIO.h>
#include <IRadio.h>

#include <iostream>
#include <unistd.h>
#include <signal.h>
#include <sstream>
#include <string>

// FUNCTION PROTOTYPING
void msleep( unsigned milisec );
void sig_handler( int sig );

// GLOBAL VARIABLES
bool ctrl_c_pressed = false;

int main()
{
	if( signal(SIGINT, sig_handler) == SIG_ERR )
		std::cout << "Can't catch SIGINT" << std::endl;

	GPIO* led1 = new GPIO(4, OUT);
	GPIO* led2 = new GPIO(3, OUT);
	GPIO* led3 = new GPIO(2, OUT);

	GPIO* button1 = new GPIO(17, IN, 0.5);
	GPIO* button2 = new GPIO(27, IN, 0.5);
	GPIO* button3 = new GPIO(22, IN, 0.5);

	Disp* lcd = new Disp{14,15,18,11,23,24,9,25,8,7,10};
	std::string line1{}, line2{}, str{};

	IRadio* rstream = new IRadio();
	rstream->startStream();

	std::string welcomeMessageLine1 = "  Welcome to:   ";
	std::string welcomeMessageLine2 = "  Mats' iRadio  ";
	line1 = welcomeMessageLine1;
	line2 = welcomeMessageLine2;

	std::chrono::time_point<std::chrono::system_clock> start_1, start_2;
	std::chrono::duration<double> elapsed_time;
	start_1 = start_2 = std::chrono::system_clock::now();

	while(1)
	{
		led1->setValue( button1->getValue() );
		led2->setValue( button2->getValue() );
		led3->setValue( button3->getValue() );

		elapsed_time = std::chrono::system_clock::now() - start_1;
		if( elapsed_time.count() >= 15.0 )
		{
			start_1 = std::chrono::system_clock::now();

			if( !rstream->streamIsRunning() )
			{
				line1 = welcomeMessageLine1;
				line2 = welcomeMessageLine2;
			}
			else
			{
				rstream->getStreamInfos();
				if( rstream->streamHasChanged() )
				{
					line1 = "[" + std::to_string(rstream->getStreamNr()) + "] " + rstream->getStreamName() + "   ";
					line2 = rstream->getInterpret() + " - " + rstream->getTitle()  + "   ";
				}
			}
		}

		elapsed_time = std::chrono::system_clock::now() - start_2;
		if( elapsed_time.count() >= 1.0 )
		{
			start_2 = std::chrono::system_clock::now();
			if( lcd->disp_job==lcd->no_job )
			{
				if( !line1.empty() )
				{
					if( line1.size()<DISP_LINE_LENGTH+3 )
					{
						str = line1.substr(0,DISP_LINE_LENGTH);
						lcd->writeText( &str, 1 );
					}
					else
					{
						str = line1.substr(0,DISP_LINE_LENGTH);
						line1 = line1.substr(1) + line1.at(0);
						lcd->writeText( &str, 1 );
					}
				}
				if( !line2.empty() )
				{
					if( line2.size()<DISP_LINE_LENGTH+3 )
					{
						str = line2.substr(0,DISP_LINE_LENGTH);
						lcd->writeText( &str, 2 );
					}
					else
					{
						str = line2.substr(0,DISP_LINE_LENGTH);
						line2 = line2.substr(1) + line2.at(0);
						lcd->writeText( &str, 2 );
					}
				}
			}
		}

		lcd->process();

		if( !button1->getDebouncedValue() )
			rstream->decreaseStreamNr();
		if( !button2->getDebouncedValue() )
			rstream->stopOrResumeStream();
		if( !button3->getDebouncedValue() )
			rstream->increaseStreamNr();

		if( ctrl_c_pressed )
			break;
	}

	delete lcd;
	delete led1; delete led2; delete led3;
	delete button1; delete button2; delete button3;
	delete rstream;
}

void msleep( unsigned milisec )
{
	for(unsigned i=0; i<milisec; ++i)
		usleep( 1000 );
}

void sig_handler( int sig )
{
	if (sig == SIGINT)
		ctrl_c_pressed = true;
}
<commit_msg>Key order changed, print out stream, title and interpet info to the console<commit_after>#include <Disp.h>
#include <GPIO.h>
#include <IRadio.h>

#include <iostream>
#include <unistd.h>
#include <signal.h>
#include <sstream>
#include <string>

// FUNCTION PROTOTYPING
void msleep( unsigned milisec );
void sig_handler( int sig );

// GLOBAL VARIABLES
bool ctrl_c_pressed = false;

int main()
{
	if( signal(SIGINT, sig_handler) == SIG_ERR )
		std::cout << "Can't catch SIGINT" << std::endl;

	GPIO* led1 = new GPIO(4, OUT);
	GPIO* led2 = new GPIO(3, OUT);
	GPIO* led3 = new GPIO(2, OUT);

	GPIO* button1 = new GPIO(17, IN, 0.5);
	GPIO* button2 = new GPIO(27, IN, 0.5);
	GPIO* button3 = new GPIO(22, IN, 0.5);

	Disp* lcd = new Disp{14,15,18,11,23,24,9,25,8,7,10};
	std::string line1{}, line2{}, str{};

	IRadio* rstream = new IRadio();
	rstream->startStream();

	std::string welcomeMessageLine1 = "  Welcome to:   ";
	std::string welcomeMessageLine2 = "  Mats' iRadio  ";
	line1 = welcomeMessageLine1;
	line2 = welcomeMessageLine2;

	std::chrono::time_point<std::chrono::system_clock> start_1, start_2;
	std::chrono::duration<double> elapsed_time;
	start_1 = start_2 = std::chrono::system_clock::now();

	while(1)
	{
		led1->setValue( button1->getValue() );
		led2->setValue( button2->getValue() );
		led3->setValue( button3->getValue() );

		elapsed_time = std::chrono::system_clock::now() - start_1;
		if( elapsed_time.count() >= 15.0 )
		{
			start_1 = std::chrono::system_clock::now();

			if( !rstream->streamIsRunning() )
			{
				line1 = welcomeMessageLine1;
				line2 = welcomeMessageLine2;
			}
			else
			{
				rstream->getStreamInfos();
				if( rstream->streamHasChanged() )
				{
					line1 = "[" + std::to_string(rstream->getStreamNr()) + "] " + rstream->getStreamName() + "   ";
					line2 = rstream->getInterpret() + " - " + rstream->getTitle()  + "   ";

					std::cout << "[" << rstream->getStreamNr() << "] " <<  rstream->getStreamName() << ", " << rstream->getInterpret() << " - " << rstream->getTitle() << "\n";
				}
			}
		}

		elapsed_time = std::chrono::system_clock::now() - start_2;
		if( elapsed_time.count() >= 1.0 )
		{
			start_2 = std::chrono::system_clock::now();
			if( lcd->disp_job==lcd->no_job )
			{
				if( !line1.empty() )
				{
					if( line1.size()<DISP_LINE_LENGTH+3 )
					{
						str = line1.substr(0,DISP_LINE_LENGTH);
						lcd->writeText( &str, 1 );
					}
					else
					{
						str = line1.substr(0,DISP_LINE_LENGTH);
						line1 = line1.substr(1) + line1.at(0);
						lcd->writeText( &str, 1 );
					}
				}
				if( !line2.empty() )
				{
					if( line2.size()<DISP_LINE_LENGTH+3 )
					{
						str = line2.substr(0,DISP_LINE_LENGTH);
						lcd->writeText( &str, 2 );
					}
					else
					{
						str = line2.substr(0,DISP_LINE_LENGTH);
						line2 = line2.substr(1) + line2.at(0);
						lcd->writeText( &str, 2 );
					}
				}
			}
		}

		lcd->process();

		if( !button1->getDebouncedValue() )
			rstream->increaseStreamNr();
		if( !button2->getDebouncedValue() )
			rstream->stopOrResumeStream();
		if( !button3->getDebouncedValue() )
			rstream->decreaseStreamNr();

		if( ctrl_c_pressed )
			break;
	}

	delete lcd;
	delete led1; delete led2; delete led3;
	delete button1; delete button2; delete button3;
	delete rstream;
}

void msleep( unsigned milisec )
{
	for(unsigned i=0; i<milisec; ++i)
		usleep( 1000 );
}

void sig_handler( int sig )
{
	if (sig == SIGINT)
		ctrl_c_pressed = true;
}
<|endoftext|>


<commit_before>b8eb051e-2747-11e6-87ba-e0f84713e7b8<commit_msg>more fixes<commit_after>b98234ab-2747-11e6-9292-e0f84713e7b8<|endoftext|>


<commit_before>/*This source code copyrighted by Lazy Foo' Productions (2004-2013)
and may not be redistributed without written permission.*/
//Version: 002

/* NOTE: When compiling on windows, ensure that the linker search paths
         include both freeglut\bin and freeglut\lib
         */

#include "LUtil.h"

void runMainLoop( int val );
/*
Pre Condition:
 -Initialized freeGLUT
Post Condition:
 -Calls the main loop functions and sets itself to be called back in 1000 / SCREEN_FPS milliseconds
Side Effects:
 -Sets glutTimerFunc
*/

int main( int argc, char* args[] )
{
    //Initialize FreeGLUT
    glutInit( &argc, args );

    //Create OpenGL 2.1 context
    glutInitContextVersion( 2, 1 );

    //Create Double Buffered Window
    glutInitDisplayMode( GLUT_DOUBLE );
    glutInitWindowSize( SCREEN_WIDTH, SCREEN_HEIGHT );

    glutCreateWindow( "OpenGL" );
//glutFullScreen();
    //Do post window/context creation initialization
    if( !initGL() )
    {
        printf( "Unable to initialize graphics library!\n" );
        return 1;
    }
    //Set keyboard handler
    glutKeyboardFunc( handleKeyDown );
    glutKeyboardUpFunc( handleKeyUp );

    //Set rendering function
    //glutDisplayFunc( render );

    //Set main loop
    glutTimerFunc( 1000 / SCREEN_FPS, runMainLoop, 0 );

    initGamespace();

    //Start GLUT main loop
    glutMainLoop();

    return 0;
}

void runMainLoop( int val )
{

    int timeNowMs = glutGet(GLUT_ELAPSED_TIME);

    //Frame logic
    update(timeNowMs);
    render();

    //Run frame one more time
    glutTimerFunc( 1000 / SCREEN_FPS, runMainLoop, val );
}
<commit_msg>uncommented glutDisplayFunc(render) so program doesn't crash<commit_after>/*This source code copyrighted by Lazy Foo' Productions (2004-2013)
and may not be redistributed without written permission.*/
//Version: 002

/* NOTE: When compiling on windows, ensure that the linker search paths
         include both freeglut\bin and freeglut\lib
         */

#include "LUtil.h"

void runMainLoop( int val );
/*
Pre Condition:
 -Initialized freeGLUT
Post Condition:
 -Calls the main loop functions and sets itself to be called back in 1000 / SCREEN_FPS milliseconds
Side Effects:
 -Sets glutTimerFunc
*/

int main( int argc, char* args[] )
{
    //Initialize FreeGLUT
    glutInit( &argc, args );

    //Create OpenGL 2.1 context
    glutInitContextVersion( 2, 1 );

    //Create Double Buffered Window
    glutInitDisplayMode( GLUT_DOUBLE );
    glutInitWindowSize( SCREEN_WIDTH, SCREEN_HEIGHT );

    glutCreateWindow( "OpenGL" );
//glutFullScreen();
    //Do post window/context creation initialization
    if( !initGL() )
    {
        printf( "Unable to initialize graphics library!\n" );
        return 1;
    }
    //Set keyboard handler
    glutKeyboardFunc( handleKeyDown );
    glutKeyboardUpFunc( handleKeyUp );

    //Set rendering function (This is required, else crash with error "No display callback registered for window 1"
    glutDisplayFunc( render );

    //Set main loop
    glutTimerFunc( 1000 / SCREEN_FPS, runMainLoop, 0 );

    initGamespace();

    //Start GLUT main loop
    glutMainLoop();

    return 0;
}

void runMainLoop( int val )
{

    int timeNowMs = glutGet(GLUT_ELAPSED_TIME);

    //Frame logic
    update(timeNowMs);
    render();

    //Run frame one more time
    glutTimerFunc( 1000 / SCREEN_FPS, runMainLoop, val );
}
<|endoftext|>


<commit_before>#include <irrlicht/irrlicht.h>
#include <irrlicht/driverChoice.h>
#include "controlterm.cpp"

const char* disp = ":1";

//#pragma comment(lib, "Irrlicht.lib")

using namespace irr;
//using namespace core;
//using namespace scene;
//using namespace video;
//using namespace io;
//using namespace gui;
//
enum {
  ID_IsNotPickable = 0,

  IDFlag_IsSolid = 1 << 0,

  IDFlag_IsInteractable = 1 << 1
};

X11Display xdisp(disp);

class VREventReceiver : public IEventReceiver {
  public:
    virtual bool OnEvent(const SEvent& event){
      if(event.EventType == irr::EET_KEY_INPUT_EVENT){
        if(IsModKey(event.KeyInput.Key)){
          if(event.KeyInput.PressedDown){
            //FIXME: shit sometimes gets weird here
            CurrentMod |= mapKeyCode(event.KeyInput.Key);
          } else {
            CurrentMod &= ~mapKeyCode(event.KeyInput.Key);
          }
        } else {
          KeyIsDown[event.KeyInput.Key] = event.KeyInput.PressedDown;
          xdisp.sendKeyEvent(mapKeyCode(event.KeyInput.Key), event.KeyInput.PressedDown, CurrentMod);
        }
      }
      return false;
    }
    virtual bool IsKeyDown(EKEY_CODE keyCode) const {
      return KeyIsDown[keyCode];
    }
  private:
    bool KeyIsDown[KEY_KEY_CODES_COUNT];
    // FIXME: can initialise to nonzero
    int CurrentMod;
};

int main() {
  // Uses driverChoiceConsole() from driverChoice.h

  VREventReceiver receiver;
  IrrlichtDevice *device = createDevice(driverChoiceConsole(), core::dimension2d<u32>(512, 384), 16, false, false, false, &receiver);
  device->setWindowCaption(L"Grimmware VRHackspace::Mk I");

  // set up video driver, scene manager and gui environment
  video::IVideoDriver* driver = device->getVideoDriver();
  scene::ISceneManager* smgr = device->getSceneManager();
  gui::IGUIEnvironment* guienv = device->getGUIEnvironment();

  video::SMaterial selectMaterial;
  selectMaterial.Wireframe = true;
  selectMaterial.Lighting = false;

  scene::IBillboardSceneNode * bill = smgr->addBillboardSceneNode();
  bill->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR );
  bill->setMaterialTexture(0, driver->getTexture("media/particle.jpg"));
  bill->setMaterialFlag(video::EMF_LIGHTING, false);
  bill->setMaterialFlag(video::EMF_ZBUFFER, false);
  bill->setSize(core::dimension2d<f32>(20.0f, 20.0f));
  bill->setID(ID_IsNotPickable); // This ensures that we don't accidentally ray-pick it

  // Set up terminal
  scene::IMeshSceneNode *cube = smgr->addCubeSceneNode(15.0f, 0, -1, core::vector3df(10,-10,10), core::vector3df(0,0,0), core::vector3df(4, 4, 1));
  cube->setMaterialFlag(video::EMF_LIGHTING, true);
  if(cube){
    scene::ITriangleSelector* selector = smgr->createTriangleSelectorFromBoundingBox( cube );
    cube->setTriangleSelector( selector );
    selector->drop();
  }
  scene::ITriangleSelector* cubeSelector = cube->getTriangleSelector();

  // Add lighting
  scene::ISceneNode* light = smgr->addLightSceneNode(0, core::vector3df(10,20,20),
      video::SColorf(1.0f, 0.6f, 0.7f, 1.0f), 800.0f);

  scene::IMeshSceneNode *room = smgr->addCubeSceneNode(15.0f, 0, -1, core::vector3df(10,-10,10), core::vector3df(0,0,0), core::vector3df(30, 30, 30));
  smgr->getMeshManipulator()->flipSurfaces(room->getMesh());
  room->setMaterialFlag(video::EMF_LIGHTING, false);
  room->setMaterialTexture(0, driver->getTexture("media/texture.jpg"));
  room->setTriangleSelector(smgr->createTriangleSelector( room->getMesh(), room ));

  bool yesLevel = true;
  int collideablesNumber = 3;
  scene::ITriangleSelector* collideables[collideablesNumber];
  collideables[0] = cubeSelector;
  collideables[1] = room->getTriangleSelector();

  scene::IMetaTriangleSelector* cameraCollisionSelector =
    smgr->createMetaTriangleSelector();
  if(yesLevel){
    // Create the level and the collision levelSelector
    device->getFileSystem()->addFileArchive("models/map-20kdm2.pk3");
    scene::IAnimatedMesh* levelMesh = smgr->getMesh("20kdm2.bsp");
    scene::IMeshSceneNode* levelNode = 0;
    scene::ITriangleSelector* levelSelector = 0;
    if (levelMesh) {
      levelNode = smgr->addOctreeSceneNode(levelMesh->getMesh(0), 0, IDFlag_IsSolid);
//        node = smgr->addMeshSceneNode(mesh->getMesh(0));
      if(levelNode){
        levelNode->setMaterialFlag(video::EMF_LIGHTING, true);
        levelNode->setPosition(core::vector3df(-1350,-130,-1400));
        levelSelector = smgr->createOctreeTriangleSelector(
                   levelNode->getMesh(), levelNode, 128);
        collideables[2] = levelSelector;
        levelNode->setTriangleSelector(levelSelector);
        levelSelector->drop(); // As soon as we're done with the levelSelector, drop it.
      }
    }
  } else {
    collideablesNumber = 2;
  }
  for(int i=0; i<collideablesNumber; i++){
    cameraCollisionSelector->addTriangleSelector(collideables[i]);
  }

  //Create camera and pin it to the floor
  scene::ICameraSceneNode *camera = smgr->addCameraSceneNodeFPS(0, 100.0f, .3f, ID_IsNotPickable, 0, 0, true, 3.f);
  camera->setPosition(core::vector3df(50,50,-60));

  //Add collision to the camera
  scene::ISceneNodeAnimator* levelAnim = smgr->createCollisionResponseAnimator(
    cameraCollisionSelector, camera, core::vector3df(30,50,30),
    core::vector3df(0,-10,0), core::vector3df(0,30,0));
  camera->addAnimator(levelAnim);
  levelAnim->drop();  // And likewise, drop the animator when we're done referring to it.

  device->getCursorControl()->setVisible(false);
  //camera->setTarget(cube->getAbsolutePosition());
  int lastFPS = -1;
  video::ITexture * texture;
  scene::ISceneNode* lastSelectedSceneNode = NULL;
  while(device->run()) {
    device->getVideoDriver()->removeTexture(texture);
    texture = driver->getTexture("/tmp/vrhs/shot.png");
    cube->setMaterialTexture(0, texture);
    // Make the pointy pointer thingy
    core::line3d<f32> ray;
    ray.start = camera->getPosition();
    ray.end = ray.start + (camera->getTarget() - ray.start).normalize() * 1000.0f;

    scene::ISceneCollisionManager* collMan = smgr->getSceneCollisionManager();

    core::vector3df intersection;
    core::triangle3df hitTriangle;

    driver->beginScene(true, true, video::SColor(255,100,101,140));
    scene::ISceneNode * selectedSceneNode =
      collMan->getSceneNodeAndCollisionPointFromRay(
          ray,
          intersection,
          hitTriangle,
          IDFlag_IsInteractable,
          0);

    if(lastSelectedSceneNode) lastSelectedSceneNode->setMaterialFlag(video::EMF_LIGHTING, true);
    if(selectedSceneNode)
    {
      bill->setPosition(intersection);
      driver->setTransform(video::ETS_WORLD, core::matrix4());
      driver->setMaterial(selectMaterial);
      driver->draw3DTriangle(hitTriangle, video::SColor(0, 255, 0, 0));
      selectedSceneNode->setMaterialFlag(video::EMF_LIGHTING, false);
      lastSelectedSceneNode = selectedSceneNode;
    }

    smgr->drawAll();
    guienv->drawAll();
    driver->endScene();
  }
  device->drop();
  return 0;

}
<commit_msg>Some weird shit going on<commit_after>#include <irrlicht/irrlicht.h>
#include <irrlicht/driverChoice.h>
#include "controlterm.cpp"

const char* disp = ":1";

//#pragma comment(lib, "Irrlicht.lib")

using namespace irr;
//using namespace core;
//using namespace scene;
//using namespace video;
//using namespace io;
//using namespace gui;
//
enum {
  ID_IsNotPickable = 0,

  IDFlag_IsSolid = 1 << 0,

  IDFlag_IsInteractable = 1 << 1
};

X11Display xdisp(disp);

class VREventReceiver : public IEventReceiver {
  public:
    virtual bool OnEvent(const SEvent& event){
      if(event.EventType == irr::EET_KEY_INPUT_EVENT){
        if(IsModKey(event.KeyInput.Key)){
          if(event.KeyInput.PressedDown){
            //FIXME: shit sometimes gets weird here
            CurrentMod |= mapKeyCode(event.KeyInput.Key);
          } else {
            CurrentMod &= ~mapKeyCode(event.KeyInput.Key);
          }
        } else {
          KeyIsDown[event.KeyInput.Key] = event.KeyInput.PressedDown;
          xdisp.sendKeyEvent(mapKeyCode(event.KeyInput.Key), event.KeyInput.PressedDown, CurrentMod);
        }
      }
      return false;
    }
    virtual bool IsKeyDown(EKEY_CODE keyCode) const {
      return KeyIsDown[keyCode];
    }
  private:
    bool KeyIsDown[KEY_KEY_CODES_COUNT];
    // FIXME: can initialise to nonzero
    int CurrentMod;
};

int main() {
  // Uses driverChoiceConsole() from driverChoice.h

  VREventReceiver receiver;
  IrrlichtDevice *device = createDevice(driverChoiceConsole(), core::dimension2d<u32>(512, 384), 16, false, false, false, &receiver);
  device->setWindowCaption(L"Grimmware VRHackspace::Mk I");

  // set up video driver, scene manager and gui environment
  video::IVideoDriver* driver = device->getVideoDriver();
  scene::ISceneManager* smgr = device->getSceneManager();
  gui::IGUIEnvironment* guienv = device->getGUIEnvironment();

  video::SMaterial selectMaterial;
  selectMaterial.Wireframe = true;
  selectMaterial.Lighting = false;

  scene::IBillboardSceneNode * bill = smgr->addBillboardSceneNode();
  bill->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR );
  bill->setMaterialTexture(0, driver->getTexture("media/particle.jpg"));
  bill->setMaterialFlag(video::EMF_LIGHTING, false);
  bill->setMaterialFlag(video::EMF_ZBUFFER, false);
  bill->setSize(core::dimension2d<f32>(20.0f, 20.0f));
  bill->setID(ID_IsNotPickable); // This ensures that we don't accidentally ray-pick it

  // Set up terminal
  scene::IMeshSceneNode *terminal = smgr->addCubeSceneNode(15.0f, 0, -1, core::vector3df(10,-10,10), core::vector3df(0,0,0), core::vector3df(4, 4, 1));
  terminal->setMaterialFlag(video::EMF_LIGHTING, true);
  terminal->setMaterialFlag(video::EMF_NORMALIZE_NORMALS, true);
  terminal->setTriangleSelector( smgr->createTriangleSelector( terminal->getMesh(), terminal ));

  // Add lighting
  scene::ISceneNode* light = smgr->addLightSceneNode(0, core::vector3df(10,10,10),
      video::SColorf(1.0f, 0.6f, 0.7f, 1.0f), 800.0f);
  light->addAnimator(smgr->createFlyCircleAnimator(core::vector3df(0,150,0),250.0f));

  light = smgr->addBillboardSceneNode(light, core::dimension2d<f32>(50, 50));
  light->setMaterialFlag(video::EMF_LIGHTING, false);
  light->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR);
  light->setMaterialTexture(0, driver->getTexture("media/particle.jpg"));

  // Metal room
  scene::IMeshSceneNode *room = smgr->addCubeSceneNode(15.0f, 0, IDFlag_IsSolid, core::vector3df(10,160,30), core::vector3df(0,0,0), core::vector3df(30, 30, 30));
  smgr->getMeshManipulator()->flipSurfaces(room->getMesh());
  //smgr->getMeshManipulator()->recalculateNormals(room->getMeshBuffer()); maybe this?
  room->setMaterialFlag(video::EMF_LIGHTING, true);
  room->setMaterialFlag(video::EMF_NORMALIZE_NORMALS, true);
  room->setMaterialFlag(video::EMF_BACK_FACE_CULLING, false);
  room->setMaterialTexture(0, driver->getTexture("media/texture.jpg"));
  room->setTriangleSelector(smgr->createTriangleSelector( room->getMesh(), room ));

  scene::IMeshSceneNode *room2 = smgr->addCubeSceneNode(15.0f, 0, IDFlag_IsSolid, core::vector3df(10,160,30), core::vector3df(0,0,0), core::vector3df(3, 3, 3));
  room2->setMaterialFlag(video::EMF_LIGHTING, true);
  room2->setMaterialTexture(0, driver->getTexture("media/texture.jpg"));
  room2->setTriangleSelector(smgr->createTriangleSelector( room2->getMesh(), room2 ));

  bool yesLevel = false;
  int collideablesNumber = 3;
  scene::ITriangleSelector* collideables[collideablesNumber];
  collideables[0] = terminal->getTriangleSelector();
  collideables[1] = room->getTriangleSelector();

  scene::IMetaTriangleSelector* cameraCollisionSelector =
    smgr->createMetaTriangleSelector();
  if(yesLevel){
    // Create the level and the collision levelSelector
    device->getFileSystem()->addFileArchive("models/map-20kdm2.pk3");
    scene::IAnimatedMesh* levelMesh = smgr->getMesh("20kdm2.bsp");
    scene::IMeshSceneNode* levelNode = 0;
    scene::ITriangleSelector* levelSelector = 0;
    if (levelMesh) {
      levelNode = smgr->addOctreeSceneNode(levelMesh->getMesh(0), 0, IDFlag_IsSolid);
//        node = smgr->addMeshSceneNode(mesh->getMesh(0));
      if(levelNode){
        levelNode->setMaterialFlag(video::EMF_LIGHTING, true);
        levelNode->setPosition(core::vector3df(-1350,-130,-1400));
        levelSelector = smgr->createOctreeTriangleSelector(
                   levelNode->getMesh(), levelNode, 128);
        collideables[2] = levelSelector;
        levelNode->setTriangleSelector(levelSelector);
        levelSelector->drop(); // As soon as we're done with the levelSelector, drop it.
      }
    }
  } else {
    collideablesNumber = 2;
  }
  for(int i=0; i<collideablesNumber; i++){
    cameraCollisionSelector->addTriangleSelector(collideables[i]);
  }

  //Create camera and pin it to the floor
  scene::ICameraSceneNode *camera = smgr->addCameraSceneNodeFPS(0, 100.0f, .3f, ID_IsNotPickable, 0, 0, true, 3.f);
  camera->setPosition(core::vector3df(50,50,-60));

  //Add collision to the camera
  scene::ISceneNodeAnimator* levelAnim = smgr->createCollisionResponseAnimator(
    cameraCollisionSelector, camera, core::vector3df(30,50,30),
    core::vector3df(0,-10,0), core::vector3df(0,30,0));
  camera->addAnimator(levelAnim);
  levelAnim->drop();  // And likewise, drop the animator when we're done referring to it.

  device->getCursorControl()->setVisible(false);
  //camera->setTarget(terminal->getAbsolutePosition());
  int lastFPS = -1;
  video::ITexture * texture;
  scene::ISceneNode* lastSelectedSceneNode = NULL;
  while(device->run()) {
    device->getVideoDriver()->removeTexture(texture);
    texture = driver->getTexture("/tmp/vrhs/shot.png");
    terminal->setMaterialTexture(0, texture);
    // Make the pointy pointer thingy
    core::line3d<f32> ray;
    ray.start = camera->getPosition();
    ray.end = ray.start + (camera->getTarget() - ray.start).normalize() * 1000.0f;

    scene::ISceneCollisionManager* collMan = smgr->getSceneCollisionManager();

    core::vector3df intersection;
    core::triangle3df hitTriangle;

    driver->beginScene(true, true, video::SColor(255,100,101,140));
    scene::ISceneNode * selectedSceneNode =
      collMan->getSceneNodeAndCollisionPointFromRay(
          ray,
          intersection,
          hitTriangle,
          IDFlag_IsInteractable,
          0);

    if(lastSelectedSceneNode) lastSelectedSceneNode->setMaterialFlag(video::EMF_LIGHTING, true);
    if(selectedSceneNode)
    {
      bill->setPosition(intersection);
      driver->setTransform(video::ETS_WORLD, core::matrix4());
      driver->setMaterial(selectMaterial);
      driver->draw3DTriangle(hitTriangle, video::SColor(0, 255, 0, 0));
      selectedSceneNode->setMaterialFlag(video::EMF_LIGHTING, false);
      lastSelectedSceneNode = selectedSceneNode;
    }

    smgr->drawAll();
    guienv->drawAll();
    driver->endScene();
  }
  device->drop();
  return 0;

}
<|endoftext|>


<commit_before>#include "Arduino.h"

int SER_Pin = 8;   //pin 14 on the 75HC595
int RCLK_Pin = 9;  //pin 12 on the 75HC595
int SRCLK_Pin = 10; //pin 11 on the 75HC595
int counter = 0;

//How many of the shift registers - change this
#define number_of_74hc595s 1

//do not touch
#define numOfRegisterPins number_of_74hc595s * 8

boolean registers[numOfRegisterPins];

void clearRegisters();
void writeRegisters();
void row(int i);
void col(int i);

void setup()
{
	pinMode(SER_Pin, OUTPUT);
	pinMode(RCLK_Pin, OUTPUT);
	pinMode(SRCLK_Pin, OUTPUT);

	//reset all register pins
	clearRegisters();
	writeRegisters();
	Serial.begin(115200);
}

//set all register pins to LOW
void clearRegisters()
{
	for(int i = numOfRegisterPins - 1; i >=  0; i--)
	{
		registers[i] = LOW;
	}
}

//Set and display registers
//Only call AFTER all values are set how you would like (slow otherwise)
void writeRegisters()
{
	digitalWrite(RCLK_Pin, LOW);
	for(int i = numOfRegisterPins - 1; i >=  0; i--)
	{
		digitalWrite(SRCLK_Pin, LOW);

		int val = registers[i];

		digitalWrite(SER_Pin, val);
		digitalWrite(SRCLK_Pin, HIGH);

	}
	digitalWrite(RCLK_Pin, HIGH);
}

void setRegisterPin(int index, int value)
{
	registers[index] = value;
}

int a[] = {1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0};

void loop()
{
	clearRegisters();
	writeRegisters();

	if (counter == 4) counter = 0;
	row(counter);

	for (int i = counter * 4; i < counter * 4 + 4; ++i)
	{
		if (a[i] == 1) col(i - counter * 4);
	}

	writeRegisters();
	delay(5);

	if (counter < 4) counter ++;
	else counter = 0;
}

void row(int i)
{
	setRegisterPin(i, HIGH);
}

void col(int i)
{
	setRegisterPin(i + 4, HIGH);
}	<commit_msg>Working bitshift array<commit_after>/**
 * @author wezside
 * Based on the code from Bildr (http://bildr.org/2011/02/74hc595/)
 */

#include "Arduino.h"

int SER_Pin = 8;   //pin 14 on the 75HC595
int RCLK_Pin = 9;  //pin 12 on the 75HC595
int SRCLK_Pin = 10; //pin 11 on the 75HC595
int counter = 0;

// 1001 0110 0000 0110
char a[] = {9, 6, 0, 6};

//How many of the shift registers - change this
#define number_of_74hc595s 1

//do not touch
#define numOfRegisterPins number_of_74hc595s * 8

boolean registers[numOfRegisterPins];

void clearRegisters();
void writeRegisters();
void row(int i);
void col(int i);

void setup()
{
	a[0] = a[0] >> 4;
	pinMode(SER_Pin, OUTPUT);
	pinMode(RCLK_Pin, OUTPUT);
	pinMode(SRCLK_Pin, OUTPUT);

	//reset all register pins
	clearRegisters();
	writeRegisters();
	Serial.begin(115200);
}

//set all register pins to LOW
void clearRegisters()
{
	for(int i = numOfRegisterPins - 1; i >=  0; i--)
	{
		registers[i] = LOW;
	}
}

//Set and display registers
//Only call AFTER all values are set how you would like (slow otherwise)
void writeRegisters()
{
	digitalWrite(RCLK_Pin, LOW);
	for(int i = numOfRegisterPins - 1; i >=  0; i--)
	{
		digitalWrite(SRCLK_Pin, LOW);
		int val = registers[i];
		digitalWrite(SER_Pin, val);
		digitalWrite(SRCLK_Pin, HIGH);

	}
	digitalWrite(RCLK_Pin, HIGH);
}

void setRegisterPin(int index, int value)
{
	registers[index] = value;
}

void loop()
{
	clearRegisters();
	writeRegisters();

	if (counter == 4) counter = 0;
	row(counter);

	for (int i = 0; i < 4; ++i)
	{
		if (a[counter] & 1 << i) col(i);
	}

	writeRegisters();
	delay(5);

	if (counter < 4) counter ++;
	else counter = 0;
}

void row(int i)
{
	setRegisterPin(i, HIGH);
}

void col(int i)
{
	setRegisterPin(i + 4, HIGH);
}	<|endoftext|>


<commit_before>dddb882b-4b02-11e5-a33a-28cfe9171a43<commit_msg>more bug fix<commit_after>dde8690a-4b02-11e5-90ca-28cfe9171a43<|endoftext|>


<commit_before>451676a6-ad5a-11e7-b8a6-ac87a332f658<commit_msg>I'm done<commit_after>463da0b8-ad5a-11e7-b200-ac87a332f658<|endoftext|>


<commit_before>#include <chrono>
#include <thread>
#include <iostream>
#include "DataStructures/XMLMemoryUnit.h"
#include "Tools/CURLTools.h"
#include "DataStructures/Game.h"
#include "Tools/XMLppTools.h"
#include "Hardware/CharacterDisplayHD44780.h"
#include "DataStructures/MLBDate.h"

using namespace std;
using namespace Glib;

int main() {
    std::locale::global(std::locale("")); //Required by ustring

    XMLMemoryUnit scoreboardToday;
    Game * seaVS = new Game();
    MLBDate * today = new MLBDate(5,25,2016);
    CharacterDisplayHD44780 * disp = new CharacterDisplayHD44780();

    const ustring urlScoreboard = "http://gd2.mlb.com/components/game/mlb" + today->MLBDateString() + "scoreboard.xml";
    const ustring team = "sea"; //TODO: Enum of the possible IDs

    CURLTools::RetrieveXMLFile(urlScoreboard, &scoreboardToday); //Pull XML from MLB API

    XMLppTools::populateGameFromScoreboardXML(seaVS, &scoreboardToday, team); //Take XML and populate the Game Object
    //TODO: Need to handle double headers, this only handles the first game (lowish priority at the moment)

    //Grab game score
    //GDB finds an erroneous "statement always true" here, suppressing warning for now
#pragma clang diagnostic push
#pragma ide diagnostic ignored "OCDFAInspection"
    if(seaVS != NULL) {
        cout << "Game found" << endl;
        const ustring gameScoreboard = "http://gd2.mlb.com/components/game/mlb" + today->MLBDateString() + "gid_" + seaVS->gameID + "/boxscore.xml";

        for(int i = 0; i < 480; i++) { //Runs for a maximum of 4 hours for now
            XMLMemoryUnit gameboard;

            cout << "Polling for score (attempt " << i << ")" << endl;
            CURLTools::RetrieveXMLFile(gameScoreboard, &gameboard);

            XMLppTools::populateScoreboardXML(seaVS, &gameboard);

            cout << seaVS->away->code << endl;
            cout << seaVS->home->code << endl;

            disp->SendMessage(seaVS->away->code, disp->LINE1);
            disp->SendMessage(seaVS->home->code, disp->LINE2);

            delete(gameboard); //Clear it out

            this_thread::sleep_for(chrono::seconds(30)); //Poll every 30 seconds
        }
    } else {
        cout << "Game not found, Mariners may not play today?" << endl;
        disp->SendMessage("No game today!",disp->LINE0);
    }
#pragma clang diagnostic pop

    return EXIT_SUCCESS;
}<commit_msg>delete needs a memory address<commit_after>#include <chrono>
#include <thread>
#include <iostream>
#include "DataStructures/XMLMemoryUnit.h"
#include "Tools/CURLTools.h"
#include "DataStructures/Game.h"
#include "Tools/XMLppTools.h"
#include "Hardware/CharacterDisplayHD44780.h"
#include "DataStructures/MLBDate.h"

using namespace std;
using namespace Glib;

int main() {
    std::locale::global(std::locale("")); //Required by ustring

    XMLMemoryUnit scoreboardToday;
    Game * seaVS = new Game();
    MLBDate * today = new MLBDate(5,25,2016);
    CharacterDisplayHD44780 * disp = new CharacterDisplayHD44780();

    const ustring urlScoreboard = "http://gd2.mlb.com/components/game/mlb" + today->MLBDateString() + "scoreboard.xml";
    const ustring team = "sea"; //TODO: Enum of the possible IDs

    CURLTools::RetrieveXMLFile(urlScoreboard, &scoreboardToday); //Pull XML from MLB API

    XMLppTools::populateGameFromScoreboardXML(seaVS, &scoreboardToday, team); //Take XML and populate the Game Object
    //TODO: Need to handle double headers, this only handles the first game (lowish priority at the moment)

    //Grab game score
    //GDB finds an erroneous "statement always true" here, suppressing warning for now
#pragma clang diagnostic push
#pragma ide diagnostic ignored "OCDFAInspection"
    if(seaVS != NULL) {
        cout << "Game found" << endl;
        const ustring gameScoreboard = "http://gd2.mlb.com/components/game/mlb" + today->MLBDateString() + "gid_" + seaVS->gameID + "/boxscore.xml";

        for(int i = 0; i < 480; i++) { //Runs for a maximum of 4 hours for now
            XMLMemoryUnit gameboard;

            cout << "Polling for score (attempt " << i << ")" << endl;
            CURLTools::RetrieveXMLFile(gameScoreboard, &gameboard);

            XMLppTools::populateScoreboardXML(seaVS, &gameboard);

            cout << seaVS->away->code << endl;
            cout << seaVS->home->code << endl;

            disp->SendMessage(seaVS->away->code, disp->LINE1);
            disp->SendMessage(seaVS->home->code, disp->LINE2);

            delete(&gameboard); //Clear it out

            this_thread::sleep_for(chrono::seconds(30)); //Poll every 30 seconds
        }
    } else {
        cout << "Game not found, Mariners may not play today?" << endl;
        disp->SendMessage("No game today!",disp->LINE0);
    }
#pragma clang diagnostic pop

    return EXIT_SUCCESS;
}<|endoftext|>


<commit_before>db86dc1e-4b02-11e5-8341-28cfe9171a43<commit_msg>oh my, I hate charles<commit_after>db94ac99-4b02-11e5-ba43-28cfe9171a43<|endoftext|>


<commit_before>/**
 *  @file SurfPhase.cpp
 *  Definitions for a simple thermodynamic model of a surface phase
 *  derived from ThermoPhase,  assuming an ideal solution model
 *  (see \ref thermoprops and class
 *  \link Cantera::SurfPhase SurfPhase\endlink).
 */
// Copyright 2002  California Institute of Technology

#include "cantera/thermo/SurfPhase.h"
#include "cantera/thermo/EdgePhase.h"
#include "cantera/thermo/ThermoFactory.h"
#include "cantera/base/stringUtils.h"
#include "cantera/base/ctml.h"
#include "cantera/base/vec_functions.h"

using namespace std;

namespace Cantera
{
SurfPhase::SurfPhase(doublereal n0):
    m_press(OneAtm)
{
    setSiteDensity(n0);
    setNDim(2);
}

SurfPhase::SurfPhase(const std::string& infile, std::string id_) :
    m_press(OneAtm)
{
    XML_Node* root = get_XML_File(infile);
    if (id_ == "-") {
        id_ = "";
    }
    XML_Node* xphase = get_XML_NameID("phase", std::string("#")+id_, root);
    if (!xphase) {
        throw CanteraError("SurfPhase::SurfPhase",
                           "Couldn't find phase name in file:" + id_);
    }
    // Check the model name to ensure we have compatibility
    string model = xphase->child("thermo")["model"];
    if (model != "Surface" && model != "Edge") {
        throw CanteraError("SurfPhase::SurfPhase",
                           "thermo model attribute must be Surface or Edge");
    }
    importPhase(*xphase, this);
}

SurfPhase::SurfPhase(XML_Node& xmlphase) :
    m_press(OneAtm)
{
    string model = xmlphase.child("thermo")["model"];
    if (model != "Surface" && model != "Edge") {
        throw CanteraError("SurfPhase::SurfPhase",
                           "thermo model attribute must be Surface or Edge");
    }
    importPhase(xmlphase, this);
}

SurfPhase::SurfPhase(const SurfPhase& right) :
    m_n0(right.m_n0),
    m_logn0(right.m_logn0),
    m_press(right.m_press)
{
    operator=(right);
}

SurfPhase& SurfPhase::operator=(const SurfPhase& right)
{
    if (&right != this) {
        ThermoPhase::operator=(right);
        m_n0         = right.m_n0;
        m_logn0      = right.m_logn0;
        m_press      = right.m_press;
        m_h0         = right.m_h0;
        m_s0         = right.m_s0;
        m_cp0        = right.m_cp0;
        m_mu0        = right.m_mu0;
        m_work       = right.m_work;
        m_logsize    = right.m_logsize;
    }
    return *this;
}

ThermoPhase* SurfPhase::duplMyselfAsThermoPhase() const
{
    return new SurfPhase(*this);
}

doublereal SurfPhase::enthalpy_mole() const
{
    if (m_n0 <= 0.0) {
        return 0.0;
    }
    _updateThermo();
    return mean_X(m_h0);
}

doublereal SurfPhase::intEnergy_mole() const
{
    return enthalpy_mole();
}

doublereal SurfPhase::entropy_mole() const
{
    _updateThermo();
    doublereal s = 0.0;
    for (size_t k = 0; k < m_kk; k++) {
        s += moleFraction(k) * (m_s0[k] -
            GasConstant * log(std::max(concentration(k) * size(k)/m_n0, SmallNumber)));
    }
    return s;
}

doublereal SurfPhase::cp_mole() const
{
    _updateThermo();
    return mean_X(m_cp0);
}

doublereal SurfPhase::cv_mole() const
{
    return cp_mole();
}

void SurfPhase::getPartialMolarEnthalpies(doublereal* hbar) const
{
    getEnthalpy_RT(hbar);
    doublereal rt = GasConstant * temperature();
    for (size_t k = 0; k < m_kk; k++) {
        hbar[k] *= rt;
    }
}

void SurfPhase::getPartialMolarEntropies(doublereal* sbar) const
{
    getEntropy_R(sbar);
    for (size_t k = 0; k < m_kk; k++) {
        sbar[k] *= GasConstant;
    }
}

void SurfPhase::getPartialMolarCp(doublereal* cpbar) const
{
    getCp_R(cpbar);
    for (size_t k = 0; k < m_kk; k++) {
        cpbar[k] *= GasConstant;
    }
}

// HKM 9/1/11  The partial molar volumes returned here are really partial molar areas.
//             Partial molar volumes for this phase should actually be equal to zero.
void SurfPhase::getPartialMolarVolumes(doublereal* vbar) const
{
    getStandardVolumes(vbar);
}

void SurfPhase::getStandardChemPotentials(doublereal* mu0) const
{
    _updateThermo();
    copy(m_mu0.begin(), m_mu0.end(), mu0);
}

void SurfPhase::getChemPotentials(doublereal* mu) const
{
    _updateThermo();
    copy(m_mu0.begin(), m_mu0.end(), mu);
    getActivityConcentrations(DATA_PTR(m_work));
    for (size_t k = 0; k < m_kk; k++) {
        mu[k] += GasConstant * temperature() *
                 (log(m_work[k]) - logStandardConc(k));
    }
}

void SurfPhase::getActivityConcentrations(doublereal* c) const
{
    getConcentrations(c);
}

doublereal SurfPhase::standardConcentration(size_t k) const
{
    return m_n0/size(k);
}

doublereal SurfPhase::logStandardConc(size_t k) const
{
    return m_logn0 - m_logsize[k];
}

void SurfPhase::setParameters(int n, doublereal* const c)
{
    if (n != 1) {
        throw CanteraError("SurfPhase::setParameters",
                           "Bad value for number of parameter");
    }
    setSiteDensity(c[0]);
}

void SurfPhase::getPureGibbs(doublereal* g) const
{
    _updateThermo();
    copy(m_mu0.begin(), m_mu0.end(), g);
}

void SurfPhase::getGibbs_RT(doublereal* grt) const
{
    _updateThermo();
    scale(m_mu0.begin(), m_mu0.end(), grt, 1.0/(GasConstant*temperature()));
}

void SurfPhase::getEnthalpy_RT(doublereal* hrt) const
{
    _updateThermo();
    scale(m_h0.begin(), m_h0.end(), hrt, 1.0/(GasConstant*temperature()));
}

void SurfPhase::getEntropy_R(doublereal* sr) const
{
    _updateThermo();
    scale(m_s0.begin(), m_s0.end(), sr, 1.0/GasConstant);
}

void SurfPhase::getCp_R(doublereal* cpr) const
{
    _updateThermo();
    scale(m_cp0.begin(), m_cp0.end(), cpr, 1.0/GasConstant);
}

void SurfPhase::getStandardVolumes(doublereal* vol) const
{
    _updateThermo();
    for (size_t k = 0; k < m_kk; k++) {
        vol[k] = 1.0/standardConcentration(k);
    }
}

void SurfPhase::getGibbs_RT_ref(doublereal* grt) const
{
    getGibbs_RT(grt);
}

void SurfPhase::getEnthalpy_RT_ref(doublereal* hrt) const
{
    getEnthalpy_RT(hrt);
}

void SurfPhase::getEntropy_R_ref(doublereal* sr) const
{
    getEntropy_R(sr);
}

void SurfPhase::getCp_R_ref(doublereal* cprt) const
{
    getCp_R(cprt);
}

void SurfPhase::initThermo()
{
    ThermoPhase::initThermo();
    m_h0.resize(m_kk);
    m_s0.resize(m_kk);
    m_cp0.resize(m_kk);
    m_mu0.resize(m_kk);
    m_work.resize(m_kk);
    vector_fp cov(m_kk, 0.0);
    cov[0] = 1.0;
    setCoverages(DATA_PTR(cov));
    m_logsize.resize(m_kk);
    for (size_t k = 0; k < m_kk; k++) {
        m_logsize[k] = log(size(k));
    }
}

void SurfPhase::setSiteDensity(doublereal n0)
{
    if (n0 <= 0.0) {
        throw CanteraError("SurfPhase::setSiteDensity",
                           "Site density must be positive. Got " + fp2str(n0));
    }
    m_n0 = n0;
    m_logn0 = log(m_n0);
}

void SurfPhase::setCoverages(const doublereal* theta)
{
    double sum = 0.0;
    for (size_t k = 0; k < m_kk; k++) {
        sum += theta[k];
    }
    if (sum <= 0.0) {
        for (size_t k = 0; k < m_kk; k++) {
            cout << "theta(" << k << ") = " << theta[k] << endl;
        }
        throw CanteraError("SurfPhase::setCoverages",
                           "Sum of Coverage fractions is zero or negative");
    }
    for (size_t k = 0; k < m_kk; k++) {
        m_work[k] = m_n0*theta[k]/(sum*size(k));
    }
    /*
     * Call the Phase:: class function
     * setConcentrations.
     */
    setConcentrations(DATA_PTR(m_work));
}

void SurfPhase::setCoveragesNoNorm(const doublereal* theta)
{
    for (size_t k = 0; k < m_kk; k++) {
        m_work[k] = m_n0*theta[k]/(size(k));
    }
    /*
     * Call the Phase:: class function
     * setConcentrations.
     */
    setConcentrations(DATA_PTR(m_work));
}

void SurfPhase::getCoverages(doublereal* theta) const
{
    getConcentrations(theta);
    for (size_t k = 0; k < m_kk; k++) {
        theta[k] *= size(k)/m_n0;
    }
}

void SurfPhase::setCoveragesByName(const std::string& cov)
{
    setCoveragesByName(parseCompString(cov, speciesNames()));
}

void SurfPhase::setCoveragesByName(const compositionMap& cov)
{
    vector_fp cv(m_kk, 0.0);
    bool ifound = false;
    for (size_t k = 0; k < m_kk; k++) {
        double c = getValue(cov, speciesName(k), 0.0);
        if (c > 0.0) {
            ifound = true;
            cv[k] = c;
        }
    }
    if (!ifound) {
        throw CanteraError("SurfPhase::setCoveragesByName",
                           "Input coverages are all zero or negative");
    }
    setCoverages(DATA_PTR(cv));
}

void SurfPhase::_updateThermo(bool force) const
{
    doublereal tnow = temperature();
    if (m_tlast != tnow || force) {
        m_spthermo->update(tnow, DATA_PTR(m_cp0), DATA_PTR(m_h0),
                           DATA_PTR(m_s0));
        m_tlast = tnow;
        for (size_t k = 0; k < m_kk; k++) {
            m_h0[k] *= GasConstant * tnow;
            m_s0[k] *= GasConstant;
            m_cp0[k] *= GasConstant;
            m_mu0[k] = m_h0[k] - tnow*m_s0[k];
        }
        m_tlast = tnow;
    }
}

void SurfPhase::setParametersFromXML(const XML_Node& eosdata)
{
    eosdata._require("model","Surface");
    doublereal n = getFloat(eosdata, "site_density", "toSI");
    setSiteDensity(n);
}

void SurfPhase::setStateFromXML(const XML_Node& state)
{

    double t;
    if (getOptionalFloat(state, "temperature", t, "temperature")) {
        setTemperature(t);
    }

    if (state.hasChild("coverages")) {
        string comp = getChildValue(state,"coverages");
        setCoveragesByName(comp);
    }
}

EdgePhase::EdgePhase(doublereal n0) : SurfPhase(n0)
{
    setNDim(1);
}

EdgePhase::EdgePhase(const EdgePhase& right) :
    SurfPhase(right.m_n0)
{
    setNDim(1);
    *this = right;
}

EdgePhase& EdgePhase::operator=(const EdgePhase& right)
{
    if (&right != this) {
        SurfPhase::operator=(right);
        setNDim(1);
    }
    return *this;
}

ThermoPhase* EdgePhase::duplMyselfAsThermoPhase() const
{
    return new EdgePhase(*this);
}

void EdgePhase::setParametersFromXML(const XML_Node& eosdata)
{
    eosdata._require("model","Edge");
    doublereal n = getFloat(eosdata, "site_density", "toSI");
    setSiteDensity(n);
}

}
<commit_msg>Remove unnecessary printing from SurfPhase::setCoverages<commit_after>/**
 *  @file SurfPhase.cpp
 *  Definitions for a simple thermodynamic model of a surface phase
 *  derived from ThermoPhase,  assuming an ideal solution model
 *  (see \ref thermoprops and class
 *  \link Cantera::SurfPhase SurfPhase\endlink).
 */
// Copyright 2002  California Institute of Technology

#include "cantera/thermo/SurfPhase.h"
#include "cantera/thermo/EdgePhase.h"
#include "cantera/thermo/ThermoFactory.h"
#include "cantera/base/stringUtils.h"
#include "cantera/base/ctml.h"
#include "cantera/base/vec_functions.h"

using namespace std;

namespace Cantera
{
SurfPhase::SurfPhase(doublereal n0):
    m_press(OneAtm)
{
    setSiteDensity(n0);
    setNDim(2);
}

SurfPhase::SurfPhase(const std::string& infile, std::string id_) :
    m_press(OneAtm)
{
    XML_Node* root = get_XML_File(infile);
    if (id_ == "-") {
        id_ = "";
    }
    XML_Node* xphase = get_XML_NameID("phase", std::string("#")+id_, root);
    if (!xphase) {
        throw CanteraError("SurfPhase::SurfPhase",
                           "Couldn't find phase name in file:" + id_);
    }
    // Check the model name to ensure we have compatibility
    string model = xphase->child("thermo")["model"];
    if (model != "Surface" && model != "Edge") {
        throw CanteraError("SurfPhase::SurfPhase",
                           "thermo model attribute must be Surface or Edge");
    }
    importPhase(*xphase, this);
}

SurfPhase::SurfPhase(XML_Node& xmlphase) :
    m_press(OneAtm)
{
    string model = xmlphase.child("thermo")["model"];
    if (model != "Surface" && model != "Edge") {
        throw CanteraError("SurfPhase::SurfPhase",
                           "thermo model attribute must be Surface or Edge");
    }
    importPhase(xmlphase, this);
}

SurfPhase::SurfPhase(const SurfPhase& right) :
    m_n0(right.m_n0),
    m_logn0(right.m_logn0),
    m_press(right.m_press)
{
    operator=(right);
}

SurfPhase& SurfPhase::operator=(const SurfPhase& right)
{
    if (&right != this) {
        ThermoPhase::operator=(right);
        m_n0         = right.m_n0;
        m_logn0      = right.m_logn0;
        m_press      = right.m_press;
        m_h0         = right.m_h0;
        m_s0         = right.m_s0;
        m_cp0        = right.m_cp0;
        m_mu0        = right.m_mu0;
        m_work       = right.m_work;
        m_logsize    = right.m_logsize;
    }
    return *this;
}

ThermoPhase* SurfPhase::duplMyselfAsThermoPhase() const
{
    return new SurfPhase(*this);
}

doublereal SurfPhase::enthalpy_mole() const
{
    if (m_n0 <= 0.0) {
        return 0.0;
    }
    _updateThermo();
    return mean_X(m_h0);
}

doublereal SurfPhase::intEnergy_mole() const
{
    return enthalpy_mole();
}

doublereal SurfPhase::entropy_mole() const
{
    _updateThermo();
    doublereal s = 0.0;
    for (size_t k = 0; k < m_kk; k++) {
        s += moleFraction(k) * (m_s0[k] -
            GasConstant * log(std::max(concentration(k) * size(k)/m_n0, SmallNumber)));
    }
    return s;
}

doublereal SurfPhase::cp_mole() const
{
    _updateThermo();
    return mean_X(m_cp0);
}

doublereal SurfPhase::cv_mole() const
{
    return cp_mole();
}

void SurfPhase::getPartialMolarEnthalpies(doublereal* hbar) const
{
    getEnthalpy_RT(hbar);
    doublereal rt = GasConstant * temperature();
    for (size_t k = 0; k < m_kk; k++) {
        hbar[k] *= rt;
    }
}

void SurfPhase::getPartialMolarEntropies(doublereal* sbar) const
{
    getEntropy_R(sbar);
    for (size_t k = 0; k < m_kk; k++) {
        sbar[k] *= GasConstant;
    }
}

void SurfPhase::getPartialMolarCp(doublereal* cpbar) const
{
    getCp_R(cpbar);
    for (size_t k = 0; k < m_kk; k++) {
        cpbar[k] *= GasConstant;
    }
}

// HKM 9/1/11  The partial molar volumes returned here are really partial molar areas.
//             Partial molar volumes for this phase should actually be equal to zero.
void SurfPhase::getPartialMolarVolumes(doublereal* vbar) const
{
    getStandardVolumes(vbar);
}

void SurfPhase::getStandardChemPotentials(doublereal* mu0) const
{
    _updateThermo();
    copy(m_mu0.begin(), m_mu0.end(), mu0);
}

void SurfPhase::getChemPotentials(doublereal* mu) const
{
    _updateThermo();
    copy(m_mu0.begin(), m_mu0.end(), mu);
    getActivityConcentrations(DATA_PTR(m_work));
    for (size_t k = 0; k < m_kk; k++) {
        mu[k] += GasConstant * temperature() *
                 (log(m_work[k]) - logStandardConc(k));
    }
}

void SurfPhase::getActivityConcentrations(doublereal* c) const
{
    getConcentrations(c);
}

doublereal SurfPhase::standardConcentration(size_t k) const
{
    return m_n0/size(k);
}

doublereal SurfPhase::logStandardConc(size_t k) const
{
    return m_logn0 - m_logsize[k];
}

void SurfPhase::setParameters(int n, doublereal* const c)
{
    if (n != 1) {
        throw CanteraError("SurfPhase::setParameters",
                           "Bad value for number of parameter");
    }
    setSiteDensity(c[0]);
}

void SurfPhase::getPureGibbs(doublereal* g) const
{
    _updateThermo();
    copy(m_mu0.begin(), m_mu0.end(), g);
}

void SurfPhase::getGibbs_RT(doublereal* grt) const
{
    _updateThermo();
    scale(m_mu0.begin(), m_mu0.end(), grt, 1.0/(GasConstant*temperature()));
}

void SurfPhase::getEnthalpy_RT(doublereal* hrt) const
{
    _updateThermo();
    scale(m_h0.begin(), m_h0.end(), hrt, 1.0/(GasConstant*temperature()));
}

void SurfPhase::getEntropy_R(doublereal* sr) const
{
    _updateThermo();
    scale(m_s0.begin(), m_s0.end(), sr, 1.0/GasConstant);
}

void SurfPhase::getCp_R(doublereal* cpr) const
{
    _updateThermo();
    scale(m_cp0.begin(), m_cp0.end(), cpr, 1.0/GasConstant);
}

void SurfPhase::getStandardVolumes(doublereal* vol) const
{
    _updateThermo();
    for (size_t k = 0; k < m_kk; k++) {
        vol[k] = 1.0/standardConcentration(k);
    }
}

void SurfPhase::getGibbs_RT_ref(doublereal* grt) const
{
    getGibbs_RT(grt);
}

void SurfPhase::getEnthalpy_RT_ref(doublereal* hrt) const
{
    getEnthalpy_RT(hrt);
}

void SurfPhase::getEntropy_R_ref(doublereal* sr) const
{
    getEntropy_R(sr);
}

void SurfPhase::getCp_R_ref(doublereal* cprt) const
{
    getCp_R(cprt);
}

void SurfPhase::initThermo()
{
    ThermoPhase::initThermo();
    m_h0.resize(m_kk);
    m_s0.resize(m_kk);
    m_cp0.resize(m_kk);
    m_mu0.resize(m_kk);
    m_work.resize(m_kk);
    vector_fp cov(m_kk, 0.0);
    cov[0] = 1.0;
    setCoverages(DATA_PTR(cov));
    m_logsize.resize(m_kk);
    for (size_t k = 0; k < m_kk; k++) {
        m_logsize[k] = log(size(k));
    }
}

void SurfPhase::setSiteDensity(doublereal n0)
{
    if (n0 <= 0.0) {
        throw CanteraError("SurfPhase::setSiteDensity",
                           "Site density must be positive. Got " + fp2str(n0));
    }
    m_n0 = n0;
    m_logn0 = log(m_n0);
}

void SurfPhase::setCoverages(const doublereal* theta)
{
    double sum = 0.0;
    for (size_t k = 0; k < m_kk; k++) {
        sum += theta[k];
    }
    if (sum <= 0.0) {
        throw CanteraError("SurfPhase::setCoverages",
                           "Sum of Coverage fractions is zero or negative");
    }
    for (size_t k = 0; k < m_kk; k++) {
        m_work[k] = m_n0*theta[k]/(sum*size(k));
    }
    /*
     * Call the Phase:: class function
     * setConcentrations.
     */
    setConcentrations(DATA_PTR(m_work));
}

void SurfPhase::setCoveragesNoNorm(const doublereal* theta)
{
    for (size_t k = 0; k < m_kk; k++) {
        m_work[k] = m_n0*theta[k]/(size(k));
    }
    /*
     * Call the Phase:: class function
     * setConcentrations.
     */
    setConcentrations(DATA_PTR(m_work));
}

void SurfPhase::getCoverages(doublereal* theta) const
{
    getConcentrations(theta);
    for (size_t k = 0; k < m_kk; k++) {
        theta[k] *= size(k)/m_n0;
    }
}

void SurfPhase::setCoveragesByName(const std::string& cov)
{
    setCoveragesByName(parseCompString(cov, speciesNames()));
}

void SurfPhase::setCoveragesByName(const compositionMap& cov)
{
    vector_fp cv(m_kk, 0.0);
    bool ifound = false;
    for (size_t k = 0; k < m_kk; k++) {
        double c = getValue(cov, speciesName(k), 0.0);
        if (c > 0.0) {
            ifound = true;
            cv[k] = c;
        }
    }
    if (!ifound) {
        throw CanteraError("SurfPhase::setCoveragesByName",
                           "Input coverages are all zero or negative");
    }
    setCoverages(DATA_PTR(cv));
}

void SurfPhase::_updateThermo(bool force) const
{
    doublereal tnow = temperature();
    if (m_tlast != tnow || force) {
        m_spthermo->update(tnow, DATA_PTR(m_cp0), DATA_PTR(m_h0),
                           DATA_PTR(m_s0));
        m_tlast = tnow;
        for (size_t k = 0; k < m_kk; k++) {
            m_h0[k] *= GasConstant * tnow;
            m_s0[k] *= GasConstant;
            m_cp0[k] *= GasConstant;
            m_mu0[k] = m_h0[k] - tnow*m_s0[k];
        }
        m_tlast = tnow;
    }
}

void SurfPhase::setParametersFromXML(const XML_Node& eosdata)
{
    eosdata._require("model","Surface");
    doublereal n = getFloat(eosdata, "site_density", "toSI");
    setSiteDensity(n);
}

void SurfPhase::setStateFromXML(const XML_Node& state)
{

    double t;
    if (getOptionalFloat(state, "temperature", t, "temperature")) {
        setTemperature(t);
    }

    if (state.hasChild("coverages")) {
        string comp = getChildValue(state,"coverages");
        setCoveragesByName(comp);
    }
}

EdgePhase::EdgePhase(doublereal n0) : SurfPhase(n0)
{
    setNDim(1);
}

EdgePhase::EdgePhase(const EdgePhase& right) :
    SurfPhase(right.m_n0)
{
    setNDim(1);
    *this = right;
}

EdgePhase& EdgePhase::operator=(const EdgePhase& right)
{
    if (&right != this) {
        SurfPhase::operator=(right);
        setNDim(1);
    }
    return *this;
}

ThermoPhase* EdgePhase::duplMyselfAsThermoPhase() const
{
    return new EdgePhase(*this);
}

void EdgePhase::setParametersFromXML(const XML_Node& eosdata)
{
    eosdata._require("model","Edge");
    doublereal n = getFloat(eosdata, "site_density", "toSI");
    setSiteDensity(n);
}

}
<|endoftext|>


<commit_before>#include <iostream>
#include <string.h>
#include <cstring>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <stack>
#include "class.h"
using namespace std;

connector parse(string input)
{
    connector returner;
    string leftinput, rightinput, conntype;
    int parenlayer=0;
    int sharpindex=input.size()-1;
    bool quote=false;

    for(string::iterator i=input.begin(); i!=input.end(); i++)
    {

    }

    return;
}

int main()
{
    string inputs;

    while(getline(cin, inputs))
    {
        connector *toexecute=parse(inputs);
        toexecute->evaluate();
    }

    return 0;
}
<commit_msg>updated main, able to execute commands<commit_after>#include <iostream>
#include <string.h>
#include <cstring>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <stack>
#include <boost/tokenizer.hpp>
#include "class.h"

using namespace std;
/*Helper function that checks to see whether or not the inputed string
 *contains a single command without any parenthesis or connector. Also
 *eliminates any comments from the input.
*/
void checkString(string &s, bool &hasPar, bool &hasConn)
{
    bool quoteFound = false;
    for (unsigned i = 0; i < s.size(); ++i)
    {
        if (s.at(i) == '(' && !quoteFound)
        {
            hasPar = true;
        }
        else if (s.at(i) == ';' && !quoteFound)
        {
            hasConn = true;
        }
        else if (s.at(i) == '&' && !quoteFound)
        {
            ++i;
            if (i < s.size() && s.at(i) == '&')
            {
                hasConn = true;
            }
        }
        else if (s.at(i) == '|' && !quoteFound)
        {
            ++i;
            if (i < s.size() && s.at(i) == '|')
            {
                hasConn = true;
            }
        }
        else if (s.at(i) == '#' && !quoteFound)
        {
            s = s.substr(0, i);
            while (s.at(s.size() - 1) == ' ')
            {
                s = s.substr(0, s.size() - 1);
            }
            return;
        }
        else if (s.at(i) == '\"')
        {
            quoteFound = !quoteFound;
        }
    }
}

/*Helper function that removes any useless parenthesis. These include
 *the following: (echo a && echo b), (echo a). This function checks to
 *see if it is possible to lose the outer parenthesis without affecting
 *execution and does so if possible.
 */
void removeUselessPar(string &s)
{
    if (s.at(0) == '(' && s.at(s.size() - 1) == ')')
    {
        string temp = s.substr(1, s.size() - 2);
        int leftPar = 0;
        int rightPar = 0;
        for (unsigned i = 0; i < temp.size(); ++i)
        {
            if (temp.at(i) == '(')
            {
                ++leftPar;
            }
            if (temp.at(i) == ')')
            {
                ++rightPar;
            }
            if (rightPar > leftPar)
            {
                return;
            }
        }
        if (leftPar == rightPar)
        {
            s = temp;
        }
        if (temp.find('(') == string::npos && temp.find(')') == string::npos)
        {
            s = temp;
        }
    }
}

/*This function splits a concatenated string of commands based on connectors.
 *If no connector is found the string is left alone. If a connector is found
 *the string is split in two along the index of the connector found.
 */
void parseCommands(string s, string &left, string &right, string &c)
{
    int parCount = 0;
    bool quoteFound = false;
    for (unsigned i = s.size() - 1; i > 0; --i)
    {
        if (s.at(i) == '(' && !quoteFound)
        {
            parCount++;
        }
        else if (s.at(i) == ')' && !quoteFound)
        {
            parCount--;
        }
        else if ((s.at(i) == ';' && !quoteFound) && parCount == 0)
        {
            left = s.substr(0, i);
            right = s.substr(i + 1, s.size());
            c = ";";
            return;
        }
        else if (s.at(i) == '&' && !quoteFound)
        {
            --i;
            if ((i >= 0 && s.at(i) == '&') && parCount == 0)
            {
                left = s.substr(0, i);
                right = s.substr(i+2, s.size());
                c = "&&";
                return;
            }
        }
        else if ((s.at(i) == '|' && !quoteFound) && parCount == 0)
        {
            --i;
            if ((i >= 0) && s.at(i) == '|')
            {
                left = s.substr(0,i);
                right = s.substr(i+2, s.size());
                c = "||";
                return;
            }
        }
        else if (s.at(i) == '\"')
        {
            quoteFound = !quoteFound;
        }
    }
}
//Removes unnecessay spaces from beginning and end of string. Helper function.
void removeSpaces(string &s)
{
    while (s.at(0) == ' ')
    {
        s = s.substr(1, s.size());
    }
    while (s.at(s.size() - 1) == ' ')
    {
        s = s.substr(0, s.size() - 1);
    }
}

//Creates a tree from the concatenated commands. Returns a pointer to the root.
//Inner nodes consist of connector objects, while leaves consist of command
//objects.
connector * createTree(string s)
{
    bool hasPar = false;
    bool hasConn = false;
    string c = "";
    string left = "";
    string right = "";
    checkString(s, hasPar, hasConn);
    if (!hasPar && !hasConn) //Checks to see if a string is a single command.
    {
        if (s == "exit") //If string contains 'exit' creates an object that will exit.
        {
            terminator *e = new terminator();
            return e;
        }
        else //Make a command object that will execute when it evaluates.
        {
            commands *c = new commands(s);
            return c;
        }
    }
    removeUselessPar(s); //Removes useless parenthesis.
    parseCommands(s, left, right, c); //Splits list of commands into smaller lists.
    //Create objects based on the connector found. Set left and right child by
    //continuing to parse the strings.
    if (c == ";")
    {
        always *con = new always();
        removeSpaces(left);
        removeSpaces(right);
        con->addLeft(createTree(left));
        con->addRight(createTree(right));
        return con;
    }
    else if (c == "&&")
    {
        ampersand *con = new ampersand();
        removeSpaces(left);
        removeSpaces(right);
        con->addLeft(createTree(left));
        con->addRight(createTree(right));
        return con;
    }
    else
    {
        pipes *con = new pipes();
        removeSpaces(left);
        removeSpaces(right);
        con->addLeft(createTree(left));
        con->addRight(createTree(right));
        return con;
    }
}

int main()
{
    char HOSTNAME[128];
    gethostname(HOSTNAME, sizeof HOSTNAME);
    string input;
    while(input != "exit")
    {
        cout << getlogin() << "@" << HOSTNAME << "$ ";
        getline(cin, input);
        connector *c = createTree(input);
        c->evaluate();
    }
    return 0;
}
<|endoftext|>


<commit_before>7dce365c-ad5b-11e7-9879-ac87a332f658<commit_msg>The previous fix has been fixed<commit_after>7e374a7a-ad5b-11e7-b83b-ac87a332f658<|endoftext|>


<commit_before>7039a1f8-4b02-11e5-a0ec-28cfe9171a43<commit_msg>GOD DAMNED IT!<commit_after>70478f47-4b02-11e5-9651-28cfe9171a43<|endoftext|>


<commit_before>7ef3f954-2749-11e6-96ec-e0f84713e7b8<commit_msg>more fixes<commit_after>7efeb36b-2749-11e6-af4b-e0f84713e7b8<|endoftext|>


<commit_before>#include "plugins/VisPlugin.h"
#include "VampHost.h"
#include "GUI.h"
#include <iostream>
#include <dlfcn.h>
#include <png.h>
#include <sstream>
#include <string>
#include <sndfile.h>
#include <tclap/CmdLine.h>

#define BYTES_PER_PIXEL 4

using std::cout;
using std::cerr;
using std::endl;
using std::string;

int writePNG(const char* filename, int width, int height, unsigned char *buffer)
{
  // convert 2d array into array of pointers
  unsigned char* row_pointers[height];
  for (int i=0; i<height; i++)
    row_pointers[i] = &buffer[i*width*BYTES_PER_PIXEL];

  // open file for writing
  FILE *fp = fopen(filename, "wb");
  if (!fp) {
    cerr << "Could not open file to write PNG." << endl;
    return 1;
  }

  // set up PNG struct
  png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
                                                NULL, NULL, NULL);
  if (!png_ptr) {
    cerr << "Could not allocate PNG write struct." << endl;
    fclose(fp);
    return 1;
  }

  // set up PNG info struct
  png_infop info_ptr = png_create_info_struct(png_ptr);
  if (!info_ptr) {
    cerr << "Could not allocate PNG info struct." << endl;
    fclose(fp);
    return 1;
  }

  // initialise PNG writing
  png_init_io(png_ptr, fp);

  // write header
  png_set_IHDR(png_ptr, info_ptr, width, height,
      8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
      PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);

  // write image
  png_set_rows(png_ptr, info_ptr, row_pointers);
  png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_BGR, NULL);

  // clean up
  png_destroy_write_struct(&png_ptr, &info_ptr);
  fclose(fp);

  return 0;
}

int main(int argc, char** argv)
{
  bool verbose;
  string pngfile, visplugin, wavfile;

  // parse command line arguments
  try
  {
    TCLAP::CmdLine cmd("Audio visualiser", ' ', "0.1");
    TCLAP::UnlabeledValueArg<string> wavFileArg("wavFile",
        "Path of audio file", true, "", "string");
    TCLAP::ValueArg<string> visPluginArg("p", "visPlugin",
        "Path of visualization plugin", true, "", "string");
    TCLAP::ValueArg<string> pngFileArg("o", "pngFile",
        "File to save output PNG", false, "", "string");
    TCLAP::SwitchArg verboseArg("V", "verbose", "Enable verbose output",
        false);

    cmd.add(wavFileArg);
    cmd.add(visPluginArg);
    cmd.add(pngFileArg);
    cmd.add(verboseArg);

    cmd.parse(argc, argv);

    wavfile = wavFileArg.getValue();
    visplugin = visPluginArg.getValue();
    pngfile = pngFileArg.getValue();
    verbose = verboseArg.getValue();

  } catch (TCLAP::ArgException &e)
  {
    cerr << "ERROR: " << e.error() << " for arg " << e.argId() << endl;
    return 1;
  }

  // load the test library
  if (verbose) cout << " * Loading visualization plugin...";
  void* handle = dlopen(visplugin.c_str(), RTLD_LAZY);
  if (!handle) {
    cerr << "ERROR: Cannot load library: " << dlerror() << endl;
    return 1;
  }

  // reset errors
  dlerror();

  // load the symbols
  create_t* create_plugin = (create_t*) dlsym(handle, "create");
  const char* dlsym_error = dlerror();
  if (dlsym_error) {
    cerr << "ERROR: Cannot load symbol create: " << dlsym_error << endl;
    dlclose(handle);
    return 1;
  }
  destroy_t* destroy_plugin = (destroy_t*) dlsym(handle, "destroy");
  dlsym_error = dlerror();
  if (dlsym_error) {
    cerr << "ERROR: Cannot load symbol destroy: " << dlsym_error << endl;
    dlclose(handle);
    return 1;
  }

  // create an instance of the class
  VisPlugin* test = create_plugin();
  if (verbose) cout << " [done]" << endl;

  // open .wav file
  if (verbose) cout << " * Loading audio file...";
  SNDFILE *sndfile;
  SF_INFO sfinfo;
  memset(&sfinfo, 0, sizeof(SF_INFO));
  sndfile = sf_open(wavfile.c_str(), SFM_READ, &sfinfo);
  if (!sndfile) {
    cerr << ": ERROR: Failed to open input file \""
      << wavfile << "\": " << sf_strerror(sndfile) << endl;
    destroy_plugin(test);
    dlclose(handle);
    return 1;
  }
  if (verbose) cout << " [done]" << endl;

  // find and parse vamp plugin name
  if (verbose) cout << " * Loading Vamp plugins...";
  istringstream ss(test->getVampPlugin());
  string vampGroup, vampPlugin, vampOutput;
  getline( ss, vampGroup, ':' );
  getline( ss, vampPlugin, ':' );
  getline( ss, vampOutput, ':' );

  // initialise vamp host
  VampHost host(sndfile, sfinfo, vampGroup+":"+vampPlugin);
  if (host.findOutputNumber(vampOutput) < 0) {
    cerr << "ERROR: Requested Vamp output could not be found." << endl;
    destroy_plugin(test);
    dlclose(handle);
    return 1;
  }
  if (verbose) cout << " [done]" << endl;

  // process audio file
  if (verbose) cout << " * Processing audio...";
  vector<Plugin::FeatureSet> results;
  if (host.run(results)) {
    cerr << "ERROR: Vamp plugin could not process audio." << endl;
    destroy_plugin(test);
    dlclose(handle);
    return 1;
  }
  if (verbose) cout << " [done]" << endl;

  if (verbose) cout << " * Refactoring data...";
  Plugin::FeatureSet resultsFilt;
  //TODO for each output
  Plugin::FeatureList featList;
  int outNum = host.findOutputNumber(vampOutput);
  for (unsigned int i=0; i<results.size(); i++)
  {
    Plugin::FeatureList feats = results.at(i)[0];
    if (feats.size() >= (unsigned int)outNum+1)
      featList.push_back(feats.at(outNum));
  }
  resultsFilt[0] = featList;
  if (verbose) cout << " [done]" << endl;

  // set up memory for bitmap
  if (verbose) cout << " * Generating image...";
  int width=800;
  int height=300;
  unsigned char buffer[width*height*BYTES_PER_PIXEL];

  // get bitmap from library
  if (test->ARGB(resultsFilt, width, height, buffer)) {
    cerr << "ERROR: Plugin failed to produce bitmap." << endl;
    destroy_plugin(test);
    dlclose(handle);
    return 1;
  }
  if (verbose) cout << " [done]" << endl;

  if (pngfile != "")
  {
    if (verbose) cout << " * Writing PNG...";
    if (writePNG(pngfile.c_str(), width, height, buffer)) {
      cerr << "ERROR: Failed to write PNG." << endl;
      destroy_plugin(test);
      dlclose(handle);
      return 1;
    }
    if (verbose) cout << " [done]" << endl;
  }
  else
  {
    if (verbose) cout << " * Displaying image...";
    GUI window(width, height, buffer);
    if (verbose) cout << " [done]" << endl;
  }

  // clean up
  destroy_plugin(test);
  dlclose(handle);
}
<commit_msg>Program now parses width and height from command line arguments.<commit_after>#include "plugins/VisPlugin.h"
#include "VampHost.h"
#include "GUI.h"
#include <iostream>
#include <dlfcn.h>
#include <png.h>
#include <sstream>
#include <string>
#include <sndfile.h>
#include <tclap/CmdLine.h>
#include <stdexcept>

#define BYTES_PER_PIXEL 4

using std::cout;
using std::cerr;
using std::endl;
using std::string;

int writePNG(const char* filename, int width, int height, unsigned char *buffer)
{
  // convert 2d array into array of pointers
  unsigned char* row_pointers[height];
  for (int i=0; i<height; i++)
    row_pointers[i] = &buffer[i*width*BYTES_PER_PIXEL];

  // open file for writing
  FILE *fp = fopen(filename, "wb");
  if (!fp) {
    cerr << "Could not open file to write PNG." << endl;
    return 1;
  }

  // set up PNG struct
  png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
                                                NULL, NULL, NULL);
  if (!png_ptr) {
    cerr << "Could not allocate PNG write struct." << endl;
    fclose(fp);
    return 1;
  }

  // set up PNG info struct
  png_infop info_ptr = png_create_info_struct(png_ptr);
  if (!info_ptr) {
    cerr << "Could not allocate PNG info struct." << endl;
    fclose(fp);
    return 1;
  }

  // initialise PNG writing
  png_init_io(png_ptr, fp);

  // write header
  png_set_IHDR(png_ptr, info_ptr, width, height,
      8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
      PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);

  // write image
  png_set_rows(png_ptr, info_ptr, row_pointers);
  png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_BGR, NULL);

  // clean up
  png_destroy_write_struct(&png_ptr, &info_ptr);
  fclose(fp);

  return 0;
}

int main(int argc, char** argv)
{
  bool verbose;
  string pngfile, visplugin, wavfile, size;
  int width=0, height=0;

  // parse command line arguments
  try
  {
    TCLAP::CmdLine cmd("Audio visualiser", ' ', "0.1");
    TCLAP::UnlabeledValueArg<string> wavFileArg("wavFile",
        "Path of audio file", true, "", "filename.wav");
    TCLAP::ValueArg<string> visPluginArg("p", "visPlugin",
        "Path of visualization plugin", true, "", "library.so");
    TCLAP::ValueArg<string> pngFileArg("o", "pngFile",
        "File to save output PNG", false, "", "filename.png");
    TCLAP::ValueArg<string> sizeArg("s", "size",
        "Size of output image in pixels", false, "600x200",
        "width>x<height");
    TCLAP::SwitchArg verboseArg("V", "verbose", "Enable verbose output",
        false);

    cmd.add(wavFileArg);
    cmd.add(visPluginArg);
    cmd.add(pngFileArg);
    cmd.add(sizeArg);
    cmd.add(verboseArg);

    // parse arguments
    cmd.parse(argc, argv);
    wavfile = wavFileArg.getValue();
    visplugin = visPluginArg.getValue();
    pngfile = pngFileArg.getValue();
    size = sizeArg.getValue();
    verbose = verboseArg.getValue();

    // parse size
    istringstream ss(size);
    string widthStr, heightStr;
    getline( ss, widthStr, 'x' );
    getline( ss, heightStr );
    istringstream(widthStr) >> width;
    istringstream(heightStr) >> height;

    // check size is valid
    if (width <= 0 || height <= 0)
    {
      cerr << "ERROR: Could not parse size argument." << endl;
      return 1;
    }

  } catch (TCLAP::ArgException &e)
  {
    cerr << "ERROR: " << e.error() << " for arg " << e.argId() << endl;
    return 1;
  }

  // load the test library
  if (verbose) cout << " * Loading visualization plugin...";
  void* handle = dlopen(visplugin.c_str(), RTLD_LAZY);
  if (!handle) {
    cerr << "ERROR: Cannot load library: " << dlerror() << endl;
    return 1;
  }

  // reset errors
  dlerror();

  // load the symbols
  create_t* create_plugin = (create_t*) dlsym(handle, "create");
  const char* dlsym_error = dlerror();
  if (dlsym_error) {
    cerr << "ERROR: Cannot load symbol create: " << dlsym_error << endl;
    dlclose(handle);
    return 1;
  }
  destroy_t* destroy_plugin = (destroy_t*) dlsym(handle, "destroy");
  dlsym_error = dlerror();
  if (dlsym_error) {
    cerr << "ERROR: Cannot load symbol destroy: " << dlsym_error << endl;
    dlclose(handle);
    return 1;
  }

  // create an instance of the class
  VisPlugin* test = create_plugin();
  if (verbose) cout << " [done]" << endl;

  // open .wav file
  if (verbose) cout << " * Loading audio file...";
  SNDFILE *sndfile;
  SF_INFO sfinfo;
  memset(&sfinfo, 0, sizeof(SF_INFO));
  sndfile = sf_open(wavfile.c_str(), SFM_READ, &sfinfo);
  if (!sndfile) {
    cerr << ": ERROR: Failed to open input file \""
      << wavfile << "\": " << sf_strerror(sndfile) << endl;
    destroy_plugin(test);
    dlclose(handle);
    return 1;
  }
  if (verbose) cout << " [done]" << endl;

  // find and parse vamp plugin name
  if (verbose) cout << " * Loading Vamp plugins...";
  istringstream ss(test->getVampPlugin());
  string vampGroup, vampPlugin, vampOutput;
  getline( ss, vampGroup, ':' );
  getline( ss, vampPlugin, ':' );
  getline( ss, vampOutput, ':' );

  // initialise vamp host
  VampHost host(sndfile, sfinfo, vampGroup+":"+vampPlugin);
  if (host.findOutputNumber(vampOutput) < 0) {
    cerr << "ERROR: Requested Vamp output could not be found." << endl;
    destroy_plugin(test);
    dlclose(handle);
    return 1;
  }
  if (verbose) cout << " [done]" << endl;

  // process audio file
  if (verbose) cout << " * Processing audio...";
  vector<Plugin::FeatureSet> results;
  if (host.run(results)) {
    cerr << "ERROR: Vamp plugin could not process audio." << endl;
    destroy_plugin(test);
    dlclose(handle);
    return 1;
  }
  if (verbose) cout << " [done]" << endl;

  if (verbose) cout << " * Refactoring data...";
  Plugin::FeatureSet resultsFilt;
  //TODO for each output
  Plugin::FeatureList featList;
  int outNum = host.findOutputNumber(vampOutput);
  for (unsigned int i=0; i<results.size(); i++)
  {
    Plugin::FeatureList feats = results.at(i)[0];
    if (feats.size() >= (unsigned int)outNum+1)
      featList.push_back(feats.at(outNum));
  }
  resultsFilt[0] = featList;
  if (verbose) cout << " [done]" << endl;

  // set up memory for bitmap
  if (verbose) cout << " * Generating image...";
  unsigned char buffer[width*height*BYTES_PER_PIXEL];

  // get bitmap from library
  if (test->ARGB(resultsFilt, width, height, buffer)) {
    cerr << "ERROR: Plugin failed to produce bitmap." << endl;
    destroy_plugin(test);
    dlclose(handle);
    return 1;
  }
  if (verbose) cout << " [done]" << endl;

  if (pngfile != "")
  {
    if (verbose) cout << " * Writing PNG...";
    if (writePNG(pngfile.c_str(), width, height, buffer)) {
      cerr << "ERROR: Failed to write PNG." << endl;
      destroy_plugin(test);
      dlclose(handle);
      return 1;
    }
    if (verbose) cout << " [done]" << endl;
  }
  else
  {
    if (verbose) cout << " * Displaying image...";
    GUI window(width, height, buffer);
    if (verbose) cout << " [done]" << endl;
  }

  // clean up
  destroy_plugin(test);
  dlclose(handle);
}
<|endoftext|>


<commit_before>#include <cstdio>
#include <string>
#include <memory>
#include <allegro5/allegro.h>
#include <allegro5/allegro_image.h>
#include <allegro5/allegro_primitives.h>
#define boolean enet_boolean
#include <enet/enet.h>

#undef boolean

#include "inputcatcher.h"
#include "engine.h"
#include "renderer.h"
#include "datastructures.h"
#include "global_constants.h"
#include "visuals/mainmenu.h"
#include "networking/servernetworker.h"
#include "networking/clientnetworker.h"
#include "global.h"
#include "configloader.h"

long int getmillisec();

int main(int argc, char **argv)
{
    try
    {
        // Initialize logging
        std::unique_ptr<PrintLogger> default_logger(new PrintLogger());
        Global::provide_logging(default_logger.get());

        // Load the settings config
        ConfigLoader settings_configloader;
        nlohmann::json settings = settings_configloader.open("settings.json");
        Global::provide_settings(&settings);

        // Initialize Allegro
        if (!al_init())
        {
            Global::logging().panic(__FILE__, __LINE__, "Allegro initialization failed");
        }

        // Initialize the Allegro Image addon, used to load sprites and maps
        if (!al_init_image_addon())
        {
            Global::logging().panic(__FILE__, __LINE__, "Allegro image addon initialization failed");
        }

        // Initialize primitives for drawing
        if (!al_init_primitives_addon())
        {
            Global::logging().panic(__FILE__, __LINE__, "Allegro primitives addon initialization failed");
        }

        // Initialize keyboard modules
        if (!al_install_keyboard())
        {
            Global::logging().panic(__FILE__, __LINE__, "Allegro keyboard initialization failed");
        }

        // Initialize mouse
        if (!al_install_mouse())
        {
            Global::logging().panic(__FILE__, __LINE__, "Allegro mouse initialization failed");
        }

        // Initialize networking system
        if (enet_initialize())
        {
            Global::logging().panic(__FILE__, __LINE__, "Enet initialization failed");
        }

        //load font
        al_init_font_addon();
        al_init_ttf_addon();

        Renderer renderer;
        ALLEGRO_DISPLAY* display = renderer.createnewdisplay();

        std::unique_ptr<MenuContainer> menus = std::unique_ptr<MenuContainer>(new MenuContainer(display));
        double lasttimeupdated = al_get_time();
        int not_finished = 1;
        while (not_finished)
        {
            if (al_get_time() - lasttimeupdated >= MENU_TIMESTEP)
            {
                not_finished = menus->run(display);
                lasttimeupdated = al_get_time();
                if (not_finished == -1)
                {
                    // Quit
                    return 0;
                }
            }
        }

        bool isserver = true;
        std::string serverip;
        int serverport = 3224;

        // Server, client, or quit?
        if (menus->action() == POSTMENUACTION::QUIT)
        {
            // Exit peacefully
            return 0;
        }
        else if (menus->action() == POSTMENUACTION::HOST_SERVER)
        {
            isserver = true;
        }
        else if (menus->action() == POSTMENUACTION::JOIN_SERVER)
        {
            isserver = false;
            serverip = menus->serverip;
            serverport = menus->serverport;
        }
        else
        {
            Global::logging().panic(__FILE__, __LINE__, "Unknown post menu status %i", menus->action());
        }

        // Clean up
        menus.reset();

        Engine engine(isserver);
        InputCatcher inputcatcher(display);
        Gamestate renderingstate(engine);

        std::unique_ptr<Networker> networker;
        if (isserver)
        {
            networker = std::unique_ptr<Networker>(new ServerNetworker(engine.sendbuffer));
            std::vector<std::string> maprotation = {"lijiang", "lijiang"};
            engine.loadrotation(maprotation);
            engine.nextmap();
            // FIXME: Hack to make sure the oldstate is properly initialized
            engine.update(0);
        }
        else
        {
            networker = std::unique_ptr<Networker>(new ClientNetworker(engine.sendbuffer, serverip, serverport));
        }

        EntityPtr myself(0);
        if (isserver)
        {
            myself = engine.currentstate->addplayer();
            Player &p = engine.currentstate->get<Player&>(myself);
            p.name = Global::settings()["Player name"];
            p.spawntimer.active = true;
        }
        else
        {
            ClientNetworker &n = reinterpret_cast<ClientNetworker&>(*networker);
            while (not n.isconnected())
            {
                n.receive(*(engine.currentstate));
            }
            myself = engine.currentstate->playerlist.at(engine.currentstate->playerlist.size()-1);
        }

        double enginetime = al_get_time();
        double networkertime = al_get_time();
        while (true)
        {
            while (al_get_time() - enginetime >= ENGINE_TIMESTEP)
            {
                networker->receive(*(engine.currentstate));
                inputcatcher.run(display, *(engine.currentstate), *networker, renderer, myself);
                engine.update(ENGINE_TIMESTEP);
                networker->sendeventdata(*(engine.currentstate));

                enginetime += ENGINE_TIMESTEP;
            }
            if (isserver)
            {
                if (al_get_time() - networkertime >= NETWORKING_TIMESTEP)
                {
                    ServerNetworker &n = reinterpret_cast<ServerNetworker&>(*networker);
                    n.sendframedata(*(engine.currentstate));

                    networkertime = al_get_time();
                }
            }
            renderingstate.interpolate(*(engine.oldstate), *(engine.currentstate), (al_get_time()-enginetime)/ENGINE_TIMESTEP);
            renderer.render(display, renderingstate, myself, *networker);
        }
    }
    catch (...)
    {
        return 0;
    }
}<commit_msg>Added rotation loading.<commit_after>#include <cstdio>
#include <string>
#include <memory>
#include <fstream>
#include <allegro5/allegro.h>
#include <allegro5/allegro_image.h>
#include <allegro5/allegro_primitives.h>
#define boolean enet_boolean
#include <enet/enet.h>

#undef boolean

#include "inputcatcher.h"
#include "engine.h"
#include "renderer.h"
#include "datastructures.h"
#include "global_constants.h"
#include "visuals/mainmenu.h"
#include "networking/servernetworker.h"
#include "networking/clientnetworker.h"
#include "global.h"
#include "configloader.h"

long int getmillisec();

int main(int argc, char **argv)
{
    try
    {
        // Initialize logging
        std::unique_ptr<PrintLogger> default_logger(new PrintLogger());
        Global::provide_logging(default_logger.get());

        // Load the settings config
        ConfigLoader settings_configloader;
        nlohmann::json settings = settings_configloader.open("settings.json");
        Global::provide_settings(&settings);

        // Initialize Allegro
        if (!al_init())
        {
            Global::logging().panic(__FILE__, __LINE__, "Allegro initialization failed");
        }

        // Initialize the Allegro Image addon, used to load sprites and maps
        if (!al_init_image_addon())
        {
            Global::logging().panic(__FILE__, __LINE__, "Allegro image addon initialization failed");
        }

        // Initialize primitives for drawing
        if (!al_init_primitives_addon())
        {
            Global::logging().panic(__FILE__, __LINE__, "Allegro primitives addon initialization failed");
        }

        // Initialize keyboard modules
        if (!al_install_keyboard())
        {
            Global::logging().panic(__FILE__, __LINE__, "Allegro keyboard initialization failed");
        }

        // Initialize mouse
        if (!al_install_mouse())
        {
            Global::logging().panic(__FILE__, __LINE__, "Allegro mouse initialization failed");
        }

        // Initialize networking system
        if (enet_initialize())
        {
            Global::logging().panic(__FILE__, __LINE__, "Enet initialization failed");
        }

        //load font
        al_init_font_addon();
        al_init_ttf_addon();

        Renderer renderer;
        ALLEGRO_DISPLAY* display = renderer.createnewdisplay();

        std::unique_ptr<MenuContainer> menus = std::unique_ptr<MenuContainer>(new MenuContainer(display));
        double lasttimeupdated = al_get_time();
        int not_finished = 1;
        while (not_finished)
        {
            if (al_get_time() - lasttimeupdated >= MENU_TIMESTEP)
            {
                not_finished = menus->run(display);
                lasttimeupdated = al_get_time();
                if (not_finished == -1)
                {
                    // Quit
                    return 0;
                }
            }
        }

        bool isserver = true;
        std::string serverip;
        int serverport = 3224;

        // Server, client, or quit?
        if (menus->action() == POSTMENUACTION::QUIT)
        {
            // Exit peacefully
            return 0;
        }
        else if (menus->action() == POSTMENUACTION::HOST_SERVER)
        {
            isserver = true;
        }
        else if (menus->action() == POSTMENUACTION::JOIN_SERVER)
        {
            isserver = false;
            serverip = menus->serverip;
            serverport = menus->serverport;
        }
        else
        {
            Global::logging().panic(__FILE__, __LINE__, "Unknown post menu status %i", menus->action());
        }

        // Clean up
        menus.reset();

        Engine engine(isserver);
        InputCatcher inputcatcher(display);
        Gamestate renderingstate(engine);

        std::unique_ptr<Networker> networker;
        if (isserver)
        {
            networker = std::unique_ptr<Networker>(new ServerNetworker(engine.sendbuffer));
            std::ifstream maprotationfile("maprotation.json");
            if (not maprotationfile.good())
            {
                Global::logging().panic(__FILE__, __LINE__, "maprotation.json was not found.");
            }
            nlohmann::json maprotationdata;
            maprotationdata << maprotationfile;
            maprotationfile.close();
            std::vector<std::string> maprotation = maprotationdata["maps"];
            engine.loadrotation(maprotation);
            engine.nextmap();
            // FIXME: Hack to make sure the oldstate is properly initialized
            engine.update(0);
        }
        else
        {
            networker = std::unique_ptr<Networker>(new ClientNetworker(engine.sendbuffer, serverip, serverport));
        }

        EntityPtr myself(0);
        if (isserver)
        {
            myself = engine.currentstate->addplayer();
            Player &p = engine.currentstate->get<Player&>(myself);
            p.name = Global::settings()["Player name"];
            p.spawntimer.active = true;
        }
        else
        {
            ClientNetworker &n = reinterpret_cast<ClientNetworker&>(*networker);
            while (not n.isconnected())
            {
                n.receive(*(engine.currentstate));
            }
            myself = engine.currentstate->playerlist.at(engine.currentstate->playerlist.size()-1);
        }

        double enginetime = al_get_time();
        double networkertime = al_get_time();
        while (true)
        {
            while (al_get_time() - enginetime >= ENGINE_TIMESTEP)
            {
                networker->receive(*(engine.currentstate));
                inputcatcher.run(display, *(engine.currentstate), *networker, renderer, myself);
                engine.update(ENGINE_TIMESTEP);
                networker->sendeventdata(*(engine.currentstate));

                enginetime += ENGINE_TIMESTEP;
            }
            if (isserver)
            {
                if (al_get_time() - networkertime >= NETWORKING_TIMESTEP)
                {
                    ServerNetworker &n = reinterpret_cast<ServerNetworker&>(*networker);
                    n.sendframedata(*(engine.currentstate));

                    networkertime = al_get_time();
                }
            }
            renderingstate.interpolate(*(engine.oldstate), *(engine.currentstate), (al_get_time()-enginetime)/ENGINE_TIMESTEP);
            renderer.render(display, renderingstate, myself, *networker);
        }
    }
    catch (...)
    {
        return 0;
    }
}<|endoftext|>


<commit_before>744a5407-ad58-11e7-af69-ac87a332f658<commit_msg>Adding stuff<commit_after>74a0cea8-ad58-11e7-8947-ac87a332f658<|endoftext|>