<commit_before>
#include "RooStats/HistFactory/Measurement.h"
#include "RooStats/HistFactory/MakeModelAndMeasurementsFast.h"
#include "TFile.h"
#include "TROOT.h"

using namespace RooStats;
using namespace HistFactory;

/*

 A ROOT script demonstrating
 an example of writing a HistFactory
 model using c++ only.

 This example was written to match
 the example.xml analysis in
 $ROOTSYS/tutorials/histfactory/

 Written by George Lewis

 */

void example() {

  std::string InputFile = "./example.root";
  // in case the file is not found
  TFile * ifile = TFile::Open(InputFile.c_str());
  if (!ifile) {
     std::cout << "Input file is not found - run prepareHistFactory script " << std::endl;
     gROOT->ProcessLine(".! prepareHistFactory .");
  }

  // Create the measurement
  Measurement meas("meas", "meas");

  meas.SetOutputFilePrefix( "./results/example_UsingC" );
  meas.SetPOI( "SigXsecOverSM" );
  meas.AddConstantParam("alpha_syst1");
  meas.AddConstantParam("Lumi");

  meas.SetLumi( 1.0 );
  meas.SetLumiRelErr( 0.10 );
  meas.SetExportOnly( false );
  meas.SetBinHigh( 2 );

  // Create a channel

  Channel chan( "channel1" );
  chan.SetData( "data", InputFile );
  chan.SetStatErrorConfig( 0.05, "Poisson" );

  // Now, create some samples

  // Create the signal sample
  Sample signal( "signal", "signal", InputFile );
  signal.AddOverallSys( "syst1",  0.95, 1.05 );
  signal.AddNormFactor( "SigXsecOverSM", 1, 0, 3 );
  chan.AddSample( signal );

  // Background 1
  Sample background1( "background1", "background1", InputFile );
  background1.ActivateStatError( "background1_statUncert", InputFile );
  background1.AddOverallSys( "syst2", 0.95, 1.05  );
  chan.AddSample( background1 );

  // Background 1
  Sample background2( "background2", "background2", InputFile );
  background2.ActivateStatError();
  background2.AddOverallSys( "syst3", 0.95, 1.05  );
  chan.AddSample( background2 );

  // Done with this channel
  // Add it to the measurement:
  meas.AddChannel( chan );

  // Collect the histograms from their files,
  // print some output,
  meas.CollectHistograms();
  meas.PrintTree();

  // One can print XML code to an
  // output directory:
  // meas.PrintXML( "xmlFromCCode", meas.GetOutputFilePrefix() );

  // Now, do the measurement
  MakeModelAndMeasurementFast( meas );

}
<commit_msg>Revert the change of example.C on the location of the date file.<commit_after>
#include "RooStats/HistFactory/Measurement.h"
#include "RooStats/HistFactory/MakeModelAndMeasurementsFast.h"
#include "TFile.h"
#include "TROOT.h"

using namespace RooStats;
using namespace HistFactory;

/*

 A ROOT script demonstrating
 an example of writing a HistFactory
 model using c++ only.

 This example was written to match
 the example.xml analysis in
 $ROOTSYS/tutorials/histfactory/

 Written by George Lewis

 */

void example() {

  std::string InputFile = ".data/example.root";
  // in case the file is not found
  TFile * ifile = TFile::Open(InputFile.c_str());
  if (!ifile) {
     std::cout << "Input file is not found - run prepareHistFactory script " << std::endl;
     gROOT->ProcessLine(".! prepareHistFactory .");
  }

  // Create the measurement
  Measurement meas("meas", "meas");

  meas.SetOutputFilePrefix( "./results/example_UsingC" );
  meas.SetPOI( "SigXsecOverSM" );
  meas.AddConstantParam("alpha_syst1");
  meas.AddConstantParam("Lumi");

  meas.SetLumi( 1.0 );
  meas.SetLumiRelErr( 0.10 );
  meas.SetExportOnly( false );
  meas.SetBinHigh( 2 );

  // Create a channel

  Channel chan( "channel1" );
  chan.SetData( "data", InputFile );
  chan.SetStatErrorConfig( 0.05, "Poisson" );

  // Now, create some samples

  // Create the signal sample
  Sample signal( "signal", "signal", InputFile );
  signal.AddOverallSys( "syst1",  0.95, 1.05 );
  signal.AddNormFactor( "SigXsecOverSM", 1, 0, 3 );
  chan.AddSample( signal );

  // Background 1
  Sample background1( "background1", "background1", InputFile );
  background1.ActivateStatError( "background1_statUncert", InputFile );
  background1.AddOverallSys( "syst2", 0.95, 1.05  );
  chan.AddSample( background1 );

  // Background 1
  Sample background2( "background2", "background2", InputFile );
  background2.ActivateStatError();
  background2.AddOverallSys( "syst3", 0.95, 1.05  );
  chan.AddSample( background2 );

  // Done with this channel
  // Add it to the measurement:
  meas.AddChannel( chan );

  // Collect the histograms from their files,
  // print some output,
  meas.CollectHistograms();
  meas.PrintTree();

  // One can print XML code to an
  // output directory:
  // meas.PrintXML( "xmlFromCCode", meas.GetOutputFilePrefix() );

  // Now, do the measurement
  MakeModelAndMeasurementFast( meas );

}
<|endoftext|>


<commit_before>
<commit_msg>open file for a single output<commit_after>#include<iostream>
#include<fstream>
#include<ctime>
#include<cstring>
using namespace std;

const string OUT_DIR = "outputs";

string get_file_name(){
	return "CODES_"+to_string(time(NULL))+".txt";
}

int main(){

	string filename=get_file_name();
	cout<<"output at file : "<<filename<<endl;

	string outputPath=".\\" + OUT_DIR + "\\" + filename;
	ofstream outFile;
	outFile.open(outputPath);

	if(outFile != NULL){

		//process files of codes

		outFile.close();
		cout<<"Writing Completed !";
	}
	else{
		cout<<"Error opening file : "<<outputPath<<endl;
		cout<<"Progream failed!";
	}
	return 0;
}
<|endoftext|>


<commit_before>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "InteriorExplorerState.h"
#include "IAppCameraController.h"
#include "InteriorExplorerSetupState.h"
#include "InteriorExplorerStreamState.h"
#include "InteriorExplorerViewingState.h"
#include "InteriorExplorerExitingState.h"
#include "InteriorSelectionModel.h"
#include "IAppModeModel.h"
#include "InteriorsCameraController.h"
#include "GpsGlobeCameraController.h"
#include "GlobeCameraController.h"
#include "CameraHelpers.h"
#include "EcefTangentBasis.h"
#include "NativeUIFactories.h"
#include "IAlertBoxFactory.h"
#include "LatLongAltitude.h"
#include "MyPinCreationModel.h"
#include "MyPinCreationStage.h"
#include "InteriorExplorerUserInteractionModel.h"
#include "ITourService.h"

namespace ExampleApp
{
    namespace AppModes
    {
        namespace States
        {
            namespace SdkModel
            {
                InteriorExplorerState::InteriorExplorerState(AppCamera::SdkModel::IAppCameraController& cameraController,
                                                             Eegeo::Resources::Interiors::InteriorSelectionModel& interiorSelectionModel,
                                                             Eegeo::Resources::Interiors::InteriorInteractionModel& interiorInteractionModel,
                                                             int interiorCameraHandle,
                                                             Tours::SdkModel::ITourService& tourService,
                                                             Eegeo::Streaming::CameraFrustumStreamingVolume& cameraFrustumStreamingVolume,
                                                             InteriorsExplorer::SdkModel::InteriorVisibilityUpdater& interiorVisibilityUpdater,
                                                             InteriorsExplorer::SdkModel::InteriorsExplorerModel& interiorsExplorerModel,
                                                             InteriorsExplorer::SdkModel::InteriorExplorerUserInteractionModel& interiorExplorerUserInteractionModel,
                                                             AppModes::SdkModel::IAppModeModel& appModeModel,
                                                             Eegeo::Camera::GlobeCamera::GpsGlobeCameraController& worldCameraController,
                                                             Eegeo::Resources::Interiors::InteriorsCameraController& interiorsCameraController,
                                                             Eegeo::UI::NativeUIFactories& nativeUIFactories,
                                                             MyPinCreation::SdkModel::IMyPinCreationModel& myPinCreationModel)
                : m_tourService(tourService)
                , m_tourStartedCallback(this, &InteriorExplorerState::OnTourStarted)
                , m_interiorExplorerUserInteractionModel(interiorExplorerUserInteractionModel)
                , m_appModeModel(appModeModel)
                , m_worldCameraController(worldCameraController)
                , m_interiorsCameraController(interiorsCameraController)
                , m_nativeUIFactories(nativeUIFactories)
                , m_failAlertHandler(this, &InteriorExplorerState::OnFailAlertBoxDismissed)
                , m_myPinCreationModel(myPinCreationModel)
                , m_lastEntryAttemptSuccessful(false)
                {

                    m_subStates.push_back(Eegeo_NEW(InteriorsExplorer::SdkModel::States::InteriorExplorerSetupState)(*this,
                                                                                cameraController,
                                                                                interiorCameraHandle));

                    m_subStates.push_back(Eegeo_NEW(InteriorsExplorer::SdkModel::States::InteriorExplorerStreamState)(*this,
                                                                                interiorInteractionModel,
                                                                                cameraFrustumStreamingVolume,
                                                                                interiorVisibilityUpdater));

                    m_subStates.push_back(Eegeo_NEW(InteriorsExplorer::SdkModel::States::InteriorExplorerViewingState)(*this,
                                                                                interiorsExplorerModel,
                                                                                interiorExplorerUserInteractionModel,
                                                                                cameraFrustumStreamingVolume));

                    m_subStates.push_back(Eegeo_NEW(InteriorsExplorer::SdkModel::States::InteriorExplorerExitingState)(*this,
                                                                                interiorSelectionModel,
                                                                                cameraFrustumStreamingVolume,
                                                                                interiorVisibilityUpdater,
                                                                                interiorsExplorerModel
                                                                                ));

                    m_pSubStateMachine = Eegeo_NEW(Helpers::StateMachine)(m_subStates);
                }

                InteriorExplorerState::~InteriorExplorerState()
                {
                    if(m_pSubStateMachine->GetCurrentStateIndex() >= 0)
                    {
                        m_pSubStateMachine->StopStateMachine();
                    }

                    Eegeo_DELETE m_pSubStateMachine;
                    m_pSubStateMachine = NULL;

                    for(int i = 0; i < m_subStates.size(); ++i)
                    {
                        Eegeo_DELETE m_subStates[i];
                    }

                    m_subStates.clear();
                }

                void InteriorExplorerState::Enter(int previousState)
                {
                    m_interiorExplorerUserInteractionModel.SetEnabled(false);
                    m_tourService.RegisterTourStartedCallback(m_tourStartedCallback);
                    m_myPinCreationModel.SetCreationStage(MyPinCreation::Inactive);
                    m_pSubStateMachine->StartStateMachine(0);
                }

                void InteriorExplorerState::Update(float dt)
                {
                    if(m_pSubStateMachine->GetCurrentStateIndex() >= 0)
                    {
                        m_pSubStateMachine->Update(dt);
                    }
                }

                void InteriorExplorerState::Exit(int nextState)
                {
                    Eegeo::Space::LatLongAltitude latLong = Eegeo::Space::LatLongAltitude::FromECEF(m_interiorsCameraController.GetCameraState().InterestPointEcef());
                    const float interestDistance = 500.0f;
                    m_worldCameraController.SetView(latLong.GetLatitudeInDegrees(), latLong.GetLongitudeInDegrees(),
                                                    m_interiorsCameraController.GetHeadingDegrees(),
                                                    interestDistance);
                    m_worldCameraController.GetGlobeCameraController().ApplyTilt(0.0f);

                    if(m_pSubStateMachine->GetCurrentStateIndex() >= 0)
                    {
                        m_pSubStateMachine->StopStateMachine();
                    }

                    m_tourService.UnregisterTourStartedCallback(m_tourStartedCallback);
                    m_interiorExplorerUserInteractionModel.SetEnabled(true);
                }

                void InteriorExplorerState::SetSubState(InteriorExplorerSubStates::Values stateIndex)
                {

                    m_pSubStateMachine->ChangeToState(stateIndex);
                }

                void InteriorExplorerState::ReturnToWorldMode()
                {
                    m_appModeModel.SetAppMode(AppModes::SdkModel::WorldMode);
                }

                void InteriorExplorerState::ShowFailMessage()
                {
                    m_nativeUIFactories.AlertBoxFactory().CreateSingleOptionAlertBox("Error", "We couldn't find the data for this interior", m_failAlertHandler);
                }

                void InteriorExplorerState::OnFailAlertBoxDismissed()
                {
                }

                void InteriorExplorerState::OnTourStarted()
                {
                    m_appModeModel.SetAppMode(ExampleApp::AppModes::SdkModel::TourMode);
                }

                void InteriorExplorerState::SetLastEntryAttemptSuccessful(bool successful)
                {
                    m_lastEntryAttemptSuccessful = successful;
                }

                bool InteriorExplorerState::GetLastEntryAttemptSuccessful() const
                {
                    return m_lastEntryAttemptSuccessful;
                }
            }
        }
    }
}<commit_msg>Fix for MPLY-6772. Interior camera no longer retains tilt when exiting interior. Buddy: Vimarsh<commit_after>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "InteriorExplorerState.h"
#include "IAppCameraController.h"
#include "InteriorExplorerSetupState.h"
#include "InteriorExplorerStreamState.h"
#include "InteriorExplorerViewingState.h"
#include "InteriorExplorerExitingState.h"
#include "InteriorSelectionModel.h"
#include "IAppModeModel.h"
#include "InteriorsCameraController.h"
#include "GpsGlobeCameraController.h"
#include "GlobeCameraController.h"
#include "CameraHelpers.h"
#include "EcefTangentBasis.h"
#include "NativeUIFactories.h"
#include "IAlertBoxFactory.h"
#include "LatLongAltitude.h"
#include "MyPinCreationModel.h"
#include "MyPinCreationStage.h"
#include "InteriorExplorerUserInteractionModel.h"
#include "ITourService.h"

namespace ExampleApp
{
    namespace AppModes
    {
        namespace States
        {
            namespace SdkModel
            {
                InteriorExplorerState::InteriorExplorerState(AppCamera::SdkModel::IAppCameraController& cameraController,
                                                             Eegeo::Resources::Interiors::InteriorSelectionModel& interiorSelectionModel,
                                                             Eegeo::Resources::Interiors::InteriorInteractionModel& interiorInteractionModel,
                                                             int interiorCameraHandle,
                                                             Tours::SdkModel::ITourService& tourService,
                                                             Eegeo::Streaming::CameraFrustumStreamingVolume& cameraFrustumStreamingVolume,
                                                             InteriorsExplorer::SdkModel::InteriorVisibilityUpdater& interiorVisibilityUpdater,
                                                             InteriorsExplorer::SdkModel::InteriorsExplorerModel& interiorsExplorerModel,
                                                             InteriorsExplorer::SdkModel::InteriorExplorerUserInteractionModel& interiorExplorerUserInteractionModel,
                                                             AppModes::SdkModel::IAppModeModel& appModeModel,
                                                             Eegeo::Camera::GlobeCamera::GpsGlobeCameraController& worldCameraController,
                                                             Eegeo::Resources::Interiors::InteriorsCameraController& interiorsCameraController,
                                                             Eegeo::UI::NativeUIFactories& nativeUIFactories,
                                                             MyPinCreation::SdkModel::IMyPinCreationModel& myPinCreationModel)
                : m_tourService(tourService)
                , m_tourStartedCallback(this, &InteriorExplorerState::OnTourStarted)
                , m_interiorExplorerUserInteractionModel(interiorExplorerUserInteractionModel)
                , m_appModeModel(appModeModel)
                , m_worldCameraController(worldCameraController)
                , m_interiorsCameraController(interiorsCameraController)
                , m_nativeUIFactories(nativeUIFactories)
                , m_failAlertHandler(this, &InteriorExplorerState::OnFailAlertBoxDismissed)
                , m_myPinCreationModel(myPinCreationModel)
                , m_lastEntryAttemptSuccessful(false)
                {

                    m_subStates.push_back(Eegeo_NEW(InteriorsExplorer::SdkModel::States::InteriorExplorerSetupState)(*this,
                                                                                cameraController,
                                                                                interiorCameraHandle));

                    m_subStates.push_back(Eegeo_NEW(InteriorsExplorer::SdkModel::States::InteriorExplorerStreamState)(*this,
                                                                                interiorInteractionModel,
                                                                                cameraFrustumStreamingVolume,
                                                                                interiorVisibilityUpdater));

                    m_subStates.push_back(Eegeo_NEW(InteriorsExplorer::SdkModel::States::InteriorExplorerViewingState)(*this,
                                                                                interiorsExplorerModel,
                                                                                interiorExplorerUserInteractionModel,
                                                                                cameraFrustumStreamingVolume));

                    m_subStates.push_back(Eegeo_NEW(InteriorsExplorer::SdkModel::States::InteriorExplorerExitingState)(*this,
                                                                                interiorSelectionModel,
                                                                                cameraFrustumStreamingVolume,
                                                                                interiorVisibilityUpdater,
                                                                                interiorsExplorerModel
                                                                                ));

                    m_pSubStateMachine = Eegeo_NEW(Helpers::StateMachine)(m_subStates);
                }

                InteriorExplorerState::~InteriorExplorerState()
                {
                    if(m_pSubStateMachine->GetCurrentStateIndex() >= 0)
                    {
                        m_pSubStateMachine->StopStateMachine();
                    }

                    Eegeo_DELETE m_pSubStateMachine;
                    m_pSubStateMachine = NULL;

                    for(int i = 0; i < m_subStates.size(); ++i)
                    {
                        Eegeo_DELETE m_subStates[i];
                    }

                    m_subStates.clear();
                }

                void InteriorExplorerState::Enter(int previousState)
                {
                    m_interiorExplorerUserInteractionModel.SetEnabled(false);
                    m_tourService.RegisterTourStartedCallback(m_tourStartedCallback);
                    m_myPinCreationModel.SetCreationStage(MyPinCreation::Inactive);
                    m_interiorsCameraController.SetTilt(0.0f);
                    m_pSubStateMachine->StartStateMachine(0);
                }

                void InteriorExplorerState::Update(float dt)
                {
                    if(m_pSubStateMachine->GetCurrentStateIndex() >= 0)
                    {
                        m_pSubStateMachine->Update(dt);
                    }
                }

                void InteriorExplorerState::Exit(int nextState)
                {
                    Eegeo::Space::LatLongAltitude latLong = Eegeo::Space::LatLongAltitude::FromECEF(m_interiorsCameraController.GetCameraState().InterestPointEcef());
                    const float interestDistance = 500.0f;
                    m_worldCameraController.SetView(latLong.GetLatitudeInDegrees(), latLong.GetLongitudeInDegrees(),
                                                    m_interiorsCameraController.GetHeadingDegrees(),
                                                    interestDistance);
                    m_worldCameraController.GetGlobeCameraController().ApplyTilt(0.0f);

                    if(m_pSubStateMachine->GetCurrentStateIndex() >= 0)
                    {
                        m_pSubStateMachine->StopStateMachine();
                    }

                    m_tourService.UnregisterTourStartedCallback(m_tourStartedCallback);
                    m_interiorExplorerUserInteractionModel.SetEnabled(true);
                }

                void InteriorExplorerState::SetSubState(InteriorExplorerSubStates::Values stateIndex)
                {

                    m_pSubStateMachine->ChangeToState(stateIndex);
                }

                void InteriorExplorerState::ReturnToWorldMode()
                {
                    m_appModeModel.SetAppMode(AppModes::SdkModel::WorldMode);
                }

                void InteriorExplorerState::ShowFailMessage()
                {
                    m_nativeUIFactories.AlertBoxFactory().CreateSingleOptionAlertBox("Error", "We couldn't find the data for this interior", m_failAlertHandler);
                }

                void InteriorExplorerState::OnFailAlertBoxDismissed()
                {
                }

                void InteriorExplorerState::OnTourStarted()
                {
                    m_appModeModel.SetAppMode(ExampleApp::AppModes::SdkModel::TourMode);
                }

                void InteriorExplorerState::SetLastEntryAttemptSuccessful(bool successful)
                {
                    m_lastEntryAttemptSuccessful = successful;
                }

                bool InteriorExplorerState::GetLastEntryAttemptSuccessful() const
                {
                    return m_lastEntryAttemptSuccessful;
                }
            }
        }
    }
}<|endoftext|>


<commit_before>#include "vschdfsrecord.h"
#include "hdddevice.hpp"
#include "debug.hpp"
#include "vschddone.h"
#include "factory.hpp"

extern Factory *gFactory;

VSCHdfsRecord::VSCHdfsRecord(QWidget *parent)
    : QWidget(parent)
{
	ui.setupUi(this);
	gFactory->GetHdfsRecordConf(m_Param);
	/* Setup the default value */
	setupDefaultValue();
}

void VSCHdfsRecord::setupDefaultValue()
{
    ui.lineEditNameNode->setText(m_Param.data.conf.NameNode);
    ui.lineEditPort->setText(m_Param.data.conf.Port);
    ui.lineEditUser->setText(m_Param.data.conf.User);
}

void VSCHdfsRecord::applyConfig()
{
    /* Update m_Param from UI  */
    updateParamValue(ui.lineEditNameNode, m_Param.data.conf.NameNode);
    updateParamValue(ui.lineEditPort, m_Param.data.conf.Port);
    updateParamValue(ui.lineEditUser, m_Param.data.conf.User);

    VDC_DEBUG( "%s  Line %d\n",__FUNCTION__, __LINE__);
    gFactory->SetHdfsRecordConf(m_Param);

}

<commit_msg>add hdfs<commit_after>#include "vschdfsrecord.h"
#include "hdddevice.hpp"
#include "debug.hpp"
#include "vschddone.h"
#include "factory.hpp"

extern Factory *gFactory;

VSCHdfsRecord::VSCHdfsRecord(QWidget *parent)
    : QWidget(parent)
{
	ui.setupUi(this);
	gFactory->GetHdfsRecordConf(m_Param);
	/* Setup the default value */
	setupDefaultValue();
	connect( this->ui.pushButtonApply, SIGNAL( clicked() ), this, SLOT(applyConfig()));
}

void VSCHdfsRecord::setupDefaultValue()
{
    ui.lineEditNameNode->setText(m_Param.data.conf.NameNode);
    ui.lineEditPort->setText(m_Param.data.conf.Port);
    ui.lineEditUser->setText(m_Param.data.conf.User);
}

void VSCHdfsRecord::applyConfig()
{
    /* Update m_Param from UI  */
    updateParamValue(ui.lineEditNameNode, m_Param.data.conf.NameNode);
    updateParamValue(ui.lineEditPort, m_Param.data.conf.Port);
    updateParamValue(ui.lineEditUser, m_Param.data.conf.User);

    VDC_DEBUG( "%s  Line %d\n",__FUNCTION__, __LINE__);
    gFactory->SetHdfsRecordConf(m_Param);

}

<|endoftext|>


<commit_before>#include <babylon/meshes/builders/capsule_builder.h>

#include <babylon/meshes/builders/mesh_builder_options.h>
#include <babylon/meshes/mesh.h>
#include <babylon/meshes/vertex_data.h>

namespace BABYLON {

MeshPtr CapsuleBuilder::CreateCapsule(const std::string& name, ICreateCapsuleOptions& options,
                                      Scene* scene)
{
  const auto capsule    = Mesh::New(name, scene);
  const auto vertexData = VertexData::CreateCapsule(options);
  vertexData->applyToMesh(*capsule);
  return capsule;
}

} // end of namespace BABYLON
<commit_msg>Setting default capsule create options<commit_after>#include <babylon/meshes/builders/capsule_builder.h>

#include <babylon/meshes/builders/mesh_builder_options.h>
#include <babylon/meshes/mesh.h>
#include <babylon/meshes/vertex_data.h>

namespace BABYLON {

MeshPtr CapsuleBuilder::CreateCapsule(const std::string& name, ICreateCapsuleOptions& options,
                                      Scene* scene)
{
  // Set default values
  {
    options.orientation     = options.orientation.value_or(Vector3::Up());
    options.subdivisions    = options.subdivisions.value_or(2u);
    options.tessellation    = options.tessellation.value_or(16u);
    options.height          = options.height.value_or(1.f);
    options.radius          = options.radius.value_or(0.25f);
    options.capSubdivisions = options.capSubdivisions.value_or(6u);
    options.updatable       = options.updatable.value_or(false);
  }

  const auto capsule    = Mesh::New(name, scene);
  const auto vertexData = VertexData::CreateCapsule(options);
  vertexData->applyToMesh(*capsule, options.updatable);
  return capsule;
}

} // end of namespace BABYLON
<|endoftext|>


<commit_before>#ifndef VIENNAGRID_IO_OPENDX_WRITER_GUARD
#define VIENNAGRID_IO_OPENDX_WRITER_GUARD

/* =======================================================================
   Copyright (c) 2011-2012, Institute for Microelectronics,
                            Institute for Analysis and Scientific Computing,
                            TU Wien.

                            -----------------
                     ViennaGrid - The Vienna Grid Library
                            -----------------

   Authors:      Karl Rupp                           rupp@iue.tuwien.ac.at
                 Josef Weinbub                    weinbub@iue.tuwien.ac.at

   (A list of additional contributors can be found in the PDF manual)

   License:      MIT (X11), see file LICENSE in the base directory
======================================================================= */

#include <fstream>
#include <iostream>
#include "viennagrid/forwards.h"
#include "viennagrid/io/helper.hpp"
#include "viennagrid/io/data_accessor.hpp"

/** @file opendx_writer.hpp
    @brief Provides a writer for OpenDX files
*/

namespace viennagrid
{
  namespace io
  {

    /////////////////// OpenDX export ////////////////////////////

    /** @brief Fix for a OpenDX bug: if floating-values occur, no integers (i.e. only zeros after decimal point) are allowed
     *
     * As a remedy, we add a value of 1e-5. Better to have a small error in the visualization instead of a crashed OpenDX...
     *
     * @tparam FloatingPointType  Dummy template argument to disable external linkage. Almost always float or double.
     */
    template <typename FloatingPointType>
    FloatingPointType DXfixer(FloatingPointType value)
    {
      if (value * 10000 == static_cast<long>(value * 10000))
        return value + 0.00001;

      return value;
    }

    /** @brief A helper class returning dimension-dependent attribute strings. */
    template <int DIM>
    struct DXHelper {};

    template <>
    struct DXHelper<1>
    {
      static std::string getAttributes()
      { return "attribute \"element type\" string \"line\" "; }
    };

    template <>
    struct DXHelper<2>
    {
      static std::string getAttributes()
      { return "attribute \"element type\" string \"triangles\" "; }
    };

    template <>
    struct DXHelper<3>
    {
      static std::string getAttributes()
      { return "attribute \"element type\" string \"tetrahedra\" "; }
    };

    /** @brief The OpenDX writer object. Does not support segments - always the full domain is written.
     *
     * @tparam DomainType   The ViennaGrid domain.
     */
    template <typename DomainType>
    class opendx_writer
    {
        typedef typename DomainType::config_type                         DomainConfiguration;

        typedef typename DomainConfiguration::numeric_type               CoordType;
        typedef typename DomainConfiguration::coordinate_system_tag      CoordinateSystemTag;
        typedef typename DomainConfiguration::cell_tag                   CellTag;

        typedef typename result_of::point<DomainConfiguration>::type                              PointType;
        typedef typename result_of::ncell<DomainConfiguration, 0>::type                           VertexType;
        typedef typename result_of::ncell<DomainConfiguration, CellTag::dim>::type     CellType;

        typedef typename viennagrid::result_of::const_ncell_range<DomainType, 0>::type   VertexRange;
        typedef typename viennagrid::result_of::iterator<VertexRange>::type              VertexIterator;

        typedef typename viennagrid::result_of::const_ncell_range<DomainType, CellTag::dim>::type     CellRange;
        typedef typename viennagrid::result_of::iterator<CellRange>::type                                        CellIterator;

        typedef typename viennagrid::result_of::const_ncell_range<CellType, 0>::type      VertexOnCellRange;
        typedef typename viennagrid::result_of::iterator<VertexOnCellRange>::type         VertexOnCellIterator;

      public:
        /** @brief Triggers the writing of the domain to a file
         *
         * @param domain    A ViennaGrid domain
         * @param filename  Name of the file
         */
        int operator()(DomainType const & domain, std::string const & filename)
        {
          typedef DXHelper<CoordinateSystemTag::dim>  DXHelper;

          std::ofstream writer(filename.c_str());
          if (!writer.is_open())
          {
            throw cannot_open_file_exception(filename);
            return EXIT_FAILURE;
          }

          std::size_t pointnum = viennagrid::ncells<0>(domain).size();

          writer << "object \"points\" class array type float rank 1 shape " << CoordinateSystemTag::dim << " items ";
          writer << pointnum << " data follows" << std::endl;

          //Nodes:
          VertexRange vertices = viennagrid::ncells<0>(domain);
          for (VertexIterator vit = vertices.begin();
              vit != vertices.end();
              ++vit)
          {
            PointWriter<CoordinateSystemTag::dim>::write(writer, vit->point());
            writer << std::endl;
          }
          writer << std::endl;

          //Cells:
          std::size_t cellnum = viennagrid::ncells<CellTag::dim>(domain).size();
          writer << "object \"grid_Line_One\" class array type int rank 1 shape " << (CoordinateSystemTag::dim + 1) << " items " << cellnum << " data follows" << std::endl;

          CellRange cells = viennagrid::ncells<CellTag::dim>(domain);
          for (CellIterator cit = cells.begin();
              cit != cells.end();
              ++cit)
          {
            VertexOnCellRange vertices_for_cell = viennagrid::ncells<0>(*cit);
            for (VertexOnCellIterator vocit = vertices_for_cell.begin();
                vocit != vertices_for_cell.end();
                ++vocit)
            {
              VertexType const & vertex = *vocit;
              writer << vertex.id() << " ";
            }
            writer << std::endl;
          }

          writer << DXHelper::getAttributes() << std::endl;
          writer << "attribute \"ref\" string \"positions\" " << std::endl;
          writer << std::endl;

          //set output-format:
          writer.flags(std::ios::fixed);
          writer.precision(5);

          //write quantity:
          if (vertex_data_scalar.size() > 0)
          {
            writer << "object \"VisData\" class array items " << pointnum << " data follows" << std::endl;
            //some quantity here

            for (VertexIterator vit = vertices.begin();
                vit != vertices.end();
                ++vit)
            {
              std::string value = vertex_data_scalar[0](*vit);
              writer << DXfixer(atof(value.c_str()));
              writer << std::endl;
            }

            writer << "attribute \"dep\" string \"positions\"" << std::endl;
          }
          else if (cell_data_scalar.size() > 0)
          {
            writer << "object \"VisData\" class array items " << cellnum << " data follows" << std::endl;

            //some quantity here
            for (CellIterator cit = cells.begin();
                cit != cells.end();
                ++cit)
            {
              std::string value = cell_data_scalar[0](*cit);
              writer << DXfixer(atof(value.c_str()));
              writer << std::endl;
            }
            writer << "attribute \"dep\" string \"connections\"" << std::endl;
          }

          writer << std::endl;
          writer << "object \"AttPotential\" class field " << std::endl;
          writer << "component \"data\" \"VisData\" " << std::endl;
          writer << "component \"positions\" \"points\"" << std::endl;
          writer << "component \"connections\" \"grid_Line_One\"" << std::endl;

          return EXIT_SUCCESS;

        } // operator()

        /** @brief Adds scalar data on vertices for writing to the OpenDX file. Only one quantity at a time is supported! */
        template <typename T>
        void add_scalar_data_on_vertices(T const & accessor, std::string name)
        {
          data_accessor_wrapper<VertexType> wrapper(accessor.clone());
          if (vertex_data_scalar.size() > 0)
            std::cout << "* ViennaGrid: Warning: OpenDX vertex data " << name
                      << " will be ignored, because other data is already available!" << std::endl;
          vertex_data_scalar.push_back(wrapper);
        }

        /** @brief Adds scalar data on cells for writing to the OpenDX file. Note that vertex data has precedence. Only one quantity at a time is supported! */
        template <typename T>
        void add_scalar_data_on_cells(T const & accessor, std::string name)
        {
          data_accessor_wrapper<CellType> wrapper(accessor.clone());

          if (cell_data_scalar.size() > 0)
            std::cout << "* ViennaGrid: Warning: OpenDX cell data " << name
                      << " will be ignored, because other cell data is already available!" << std::endl;

          if (vertex_data_scalar.size() > 0)
            std::cout << "* ViennaGrid: Warning: OpenDX cell data " << name
                      << " will be ignored, because other vertex data is already available!" << std::endl;

          cell_data_scalar.push_back(wrapper);
        }

      private:
        std::vector< data_accessor_wrapper<VertexType> >    vertex_data_scalar;
        std::vector< data_accessor_wrapper<CellType> >      cell_data_scalar;

    }; // opendx_writer

    /** @brief Registers scalar-valued data on vertices at the OpenDX writer. At most one data set is allowed.
      *
      * @tparam KeyType     Type of the key used with ViennaData
      * @tparam DataType    Type of the data as used with ViennaData
      * @tparam DomainType  The ViennaGrid domain type
      * @param  writer      The OpenDX writer object for which the data should be registered
      * @param  key         The key object for ViennaData
      * @param  quantity_name        Ignored. Only used for a homogeneous interface with VTK reader/writer.
      */
    template <typename KeyType, typename DataType, typename DomainType>
    opendx_writer<DomainType> & add_scalar_data_on_vertices(opendx_writer<DomainType> & writer,
                                                            KeyType const & key,
                                                            std::string quantity_name)
    {
      typedef typename DomainType::config_type                             DomainConfiguration;
      typedef typename result_of::ncell<DomainConfiguration, 0>::type      VertexType;

      data_accessor_wrapper<VertexType> wrapper(new global_scalar_data_accessor<VertexType, KeyType, DataType>(key));
      writer.add_scalar_data_on_vertices(wrapper, quantity_name);
      return writer;
    }

    /** @brief Registers scalar-valued data on cells at the OpenDX writer. Note that vertex data has precedence. At most one data set is allowed.
      *
      * @tparam KeyType     Type of the key used with ViennaData
      * @tparam DataType    Type of the data as used with ViennaData
      * @tparam DomainType  The ViennaGrid domain type
      * @param  writer      The OpenDX writer object for which the data should be registered
      * @param  key         The key object for ViennaData
      * @param  quantity_name        Ignored. Only used for a homogeneous interface with VTK reader/writer.
      */
    template <typename KeyType, typename DataType, typename DomainType>
    opendx_writer<DomainType> & add_scalar_data_on_cells(opendx_writer<DomainType> & writer,
                                                         KeyType const & key,
                                                         std::string quantity_name)
    {
      typedef typename DomainType::config_type                         DomainConfiguration;
      typedef typename DomainConfiguration::cell_tag                   CellTag;
      typedef typename result_of::ncell<DomainConfiguration, CellTag::dim>::type     CellType;

      data_accessor_wrapper<CellType> wrapper(new global_scalar_data_accessor<CellType, KeyType, DataType>(key));
      writer.add_scalar_data_on_cells(wrapper, quantity_name);
      return writer;
    }

  } //namespace io
} //namespace viennagrid

#endif

<commit_msg>adapted to new domain classes<commit_after>#ifndef VIENNAGRID_IO_OPENDX_WRITER_GUARD
#define VIENNAGRID_IO_OPENDX_WRITER_GUARD

/* =======================================================================
   Copyright (c) 2011-2012, Institute for Microelectronics,
                            Institute for Analysis and Scientific Computing,
                            TU Wien.

                            -----------------
                     ViennaGrid - The Vienna Grid Library
                            -----------------

   Authors:      Karl Rupp                           rupp@iue.tuwien.ac.at
                 Josef Weinbub                    weinbub@iue.tuwien.ac.at

   (A list of additional contributors can be found in the PDF manual)

   License:      MIT (X11), see file LICENSE in the base directory
======================================================================= */

#include <fstream>
#include <iostream>
#include "viennagrid/forwards.hpp"
#include "viennagrid/io/helper.hpp"
#include "viennagrid/io/data_accessor.hpp"

/** @file opendx_writer.hpp
    @brief Provides a writer for OpenDX files
*/

namespace viennagrid
{
  namespace io
  {

    /////////////////// OpenDX export ////////////////////////////

    /** @brief Fix for a OpenDX bug: if floating-values occur, no integers (i.e. only zeros after decimal point) are allowed
     *
     * As a remedy, we add a value of 1e-5. Better to have a small error in the visualization instead of a crashed OpenDX...
     *
     * @tparam FloatingPointType  Dummy template argument to disable external linkage. Almost always float or double.
     */
    template <typename FloatingPointType>
    FloatingPointType DXfixer(FloatingPointType value)
    {
      if (value * 10000 == static_cast<long>(value * 10000))
        return value + 0.00001;

      return value;
    }

    /** @brief A helper class returning dimension-dependent attribute strings. */
    template <int DIM>
    struct DXHelper {};

    template <>
    struct DXHelper<1>
    {
      static std::string getAttributes()
      { return "attribute \"element type\" string \"line\" "; }
    };

    template <>
    struct DXHelper<2>
    {
      static std::string getAttributes()
      { return "attribute \"element type\" string \"triangles\" "; }
    };

    template <>
    struct DXHelper<3>
    {
      static std::string getAttributes()
      { return "attribute \"element type\" string \"tetrahedra\" "; }
    };

    /** @brief The OpenDX writer object. Does not support segments - always the full domain is written.
     *
     * @tparam DomainType   The ViennaGrid domain.
     */
    template <typename CellTypeOrTag, typename DomainType>
    class opendx_writer
    {
        //typedef typename DomainType::config_type                         DomainConfiguration;

        typedef typename viennagrid::result_of::point_type<DomainType>::type PointType;
        typedef typename viennagrid::traits::value_type<PointType>::type CoordType;
        enum { geometric_dim = viennagrid::traits::static_size<PointType>::value };

        //typedef typename DomainConfiguration::numeric_type               CoordType;
        //typedef typename DomainConfiguration::coordinate_system_tag      CoordinateSystemTag;
        //typedef typename DomainConfiguration::cell_tag                   CellTag;
        typedef typename viennagrid::result_of::element_tag<CellTypeOrTag>::type CellTag;

        //typedef typename result_of::point<DomainConfiguration>::type                              PointType;
        //typedef typename result_of::point_type<DomainType>::type                                  PointType;
        typedef typename result_of::element<DomainType, viennagrid::vertex_tag>::type                           VertexType;
        typedef typename result_of::element<DomainType, CellTag>::type     CellType;

        typedef typename viennagrid::result_of::const_element_range<DomainType, viennagrid::vertex_tag>::type   VertexRange;
        typedef typename viennagrid::result_of::iterator<VertexRange>::type              VertexIterator;

        typedef typename viennagrid::result_of::const_element_range<DomainType, CellTag>::type     CellRange;
        typedef typename viennagrid::result_of::iterator<CellRange>::type                                        CellIterator;

        typedef typename viennagrid::result_of::const_element_range<CellType, viennagrid::vertex_tag>::type      VertexOnCellRange;
        typedef typename viennagrid::result_of::iterator<VertexOnCellRange>::type         VertexOnCellIterator;

      public:
        /** @brief Triggers the writing of the domain to a file
         *
         * @param domain    A ViennaGrid domain
         * @param filename  Name of the file
         */
        int operator()(DomainType const & domain, std::string const & filename)
        {
          typedef DXHelper<geometric_dim>  DXHelper;

          std::ofstream writer(filename.c_str());
          if (!writer.is_open())
          {
            throw cannot_open_file_exception(filename);
            return EXIT_FAILURE;
          }

          std::size_t pointnum = viennagrid::ncells<0>(domain).size();

          writer << "object \"points\" class array type float rank 1 shape " << geometric_dim << " items ";
          writer << pointnum << " data follows" << std::endl;

          //Nodes:
          VertexRange vertices = viennagrid::ncells<0>(domain);
          for (VertexIterator vit = vertices.begin();
              vit != vertices.end();
              ++vit)
          {
            PointWriter<geometric_dim>::write(writer, viennagrid::point( domain, *vit ) );
            writer << std::endl;
          }
          writer << std::endl;

          //Cells:
          std::size_t cellnum = viennagrid::ncells<CellTag::dim>(domain).size();
          writer << "object \"grid_Line_One\" class array type int rank 1 shape " << (geometric_dim + 1) << " items " << cellnum << " data follows" << std::endl;

          CellRange cells = viennagrid::ncells<CellTag::dim>(domain);
          for (CellIterator cit = cells.begin();
              cit != cells.end();
              ++cit)
          {
            VertexOnCellRange vertices_for_cell = viennagrid::ncells<0>(*cit);
            for (VertexOnCellIterator vocit = vertices_for_cell.begin();
                vocit != vertices_for_cell.end();
                ++vocit)
            {
              VertexType const & vertex = *vocit;
              writer << vertex.id() << " ";
            }
            writer << std::endl;
          }

          writer << DXHelper::getAttributes() << std::endl;
          writer << "attribute \"ref\" string \"positions\" " << std::endl;
          writer << std::endl;

          //set output-format:
          writer.flags(std::ios::fixed);
          writer.precision(5);

          //write quantity:
          if (vertex_data_scalar.size() > 0)
          {
            writer << "object \"VisData\" class array items " << pointnum << " data follows" << std::endl;
            //some quantity here

            for (VertexIterator vit = vertices.begin();
                vit != vertices.end();
                ++vit)
            {
              std::string value = vertex_data_scalar[0](*vit);
              writer << DXfixer(atof(value.c_str()));
              writer << std::endl;
            }

            writer << "attribute \"dep\" string \"positions\"" << std::endl;
          }
          else if (cell_data_scalar.size() > 0)
          {
            writer << "object \"VisData\" class array items " << cellnum << " data follows" << std::endl;

            //some quantity here
            for (CellIterator cit = cells.begin();
                cit != cells.end();
                ++cit)
            {
              std::string value = cell_data_scalar[0](*cit);
              writer << DXfixer(atof(value.c_str()));
              writer << std::endl;
            }
            writer << "attribute \"dep\" string \"connections\"" << std::endl;
          }

          writer << std::endl;
          writer << "object \"AttPotential\" class field " << std::endl;
          writer << "component \"data\" \"VisData\" " << std::endl;
          writer << "component \"positions\" \"points\"" << std::endl;
          writer << "component \"connections\" \"grid_Line_One\"" << std::endl;

          return EXIT_SUCCESS;

        } // operator()

        /** @brief Adds scalar data on vertices for writing to the OpenDX file. Only one quantity at a time is supported! */
        template <typename T>
        void add_scalar_data_on_vertices(T const & accessor, std::string name)
        {
          data_accessor_wrapper<VertexType> wrapper(accessor.clone());
          if (vertex_data_scalar.size() > 0)
            std::cout << "* ViennaGrid: Warning: OpenDX vertex data " << name
                      << " will be ignored, because other data is already available!" << std::endl;
          vertex_data_scalar.push_back(wrapper);
        }

        /** @brief Adds scalar data on cells for writing to the OpenDX file. Note that vertex data has precedence. Only one quantity at a time is supported! */
        template <typename T>
        void add_scalar_data_on_cells(T const & accessor, std::string name)
        {
          data_accessor_wrapper<CellType> wrapper(accessor.clone());

          if (cell_data_scalar.size() > 0)
            std::cout << "* ViennaGrid: Warning: OpenDX cell data " << name
                      << " will be ignored, because other cell data is already available!" << std::endl;

          if (vertex_data_scalar.size() > 0)
            std::cout << "* ViennaGrid: Warning: OpenDX cell data " << name
                      << " will be ignored, because other vertex data is already available!" << std::endl;

          cell_data_scalar.push_back(wrapper);
        }

      private:
        std::vector< data_accessor_wrapper<VertexType> >    vertex_data_scalar;
        std::vector< data_accessor_wrapper<CellType> >      cell_data_scalar;

    }; // opendx_writer

    /** @brief Registers scalar-valued data on vertices at the OpenDX writer. At most one data set is allowed.
      *
      * @tparam KeyType     Type of the key used with ViennaData
      * @tparam DataType    Type of the data as used with ViennaData
      * @tparam DomainType  The ViennaGrid domain type
      * @param  writer      The OpenDX writer object for which the data should be registered
      * @param  key         The key object for ViennaData
      * @param  quantity_name        Ignored. Only used for a homogeneous interface with VTK reader/writer.
      */
    template <typename KeyType, typename DataType, typename CellTypeOrTag, typename DomainType>
    opendx_writer<CellTypeOrTag, DomainType> & add_scalar_data_on_vertices(opendx_writer<CellTypeOrTag, DomainType> & writer,
                                                            KeyType const & key,
                                                            std::string quantity_name)
    {
      //typedef typename DomainType::config_type                             DomainConfiguration;
      typedef typename result_of::element<DomainType, viennagrid::vertex_tag>::type      VertexType;

      data_accessor_wrapper<VertexType> wrapper(new global_scalar_data_accessor<VertexType, KeyType, DataType>(key));
      writer.add_scalar_data_on_vertices(wrapper, quantity_name);
      return writer;
    }

    /** @brief Registers scalar-valued data on cells at the OpenDX writer. Note that vertex data has precedence. At most one data set is allowed.
      *
      * @tparam KeyType     Type of the key used with ViennaData
      * @tparam DataType    Type of the data as used with ViennaData
      * @tparam DomainType  The ViennaGrid domain type
      * @param  writer      The OpenDX writer object for which the data should be registered
      * @param  key         The key object for ViennaData
      * @param  quantity_name        Ignored. Only used for a homogeneous interface with VTK reader/writer.
      */
    template <typename KeyType, typename DataType, typename CellTypeOrTag, typename DomainType>
    opendx_writer<CellTypeOrTag, DomainType> & add_scalar_data_on_cells(opendx_writer<CellTypeOrTag, DomainType> & writer,
                                                         KeyType const & key,
                                                         std::string quantity_name)
    {
      typedef typename DomainType::config_type                         DomainConfiguration;
      typedef typename result_of::element_tag<CellTypeOrTag>::type                   CellTag;
      typedef typename result_of::element<DomainConfiguration, CellTag>::type     CellType;

      data_accessor_wrapper<CellType> wrapper(new global_scalar_data_accessor<CellType, KeyType, DataType>(key));
      writer.add_scalar_data_on_cells(wrapper, quantity_name);
      return writer;
    }

  } //namespace io
} //namespace viennagrid

#endif

<|endoftext|>


<commit_before>#include "guiwindow.h"

#include "barcolor.h"
#include "imagebackground.h"
#include "textbutton.h"
#include "group.h"
#include "multiframe.h"
#include "textitem.h"
#include "textboxdraw.h"
#include "inputnumberformatter.h"
#include "choosenbrofplayers.h"

#include "gamesprite.h"
#include "gamefont.h"

#include <mw/font.h>
#include <mw/sprite.h>
#include <mw/window.h>

#include <iostream>
#include <string>

namespace gui {

	GuiWindow::GuiWindow() : mw::Window(500,600,"MWetris","images/tetris.bmp") {
		playFrameIndex_ = multiFrame_.addFrameBack();
		highscoreFrameIndex_ = multiFrame_.addFrameBack();
		customFrameIndex_ = multiFrame_.addFrameBack();
		optionFrameIndex_ = multiFrame_.addFrameBack();

		auto background = std::make_shared<ImageBackground>(spriteBackground);
		multiFrame_.setBackground(background,0);
		multiFrame_.setBackground(background,playFrameIndex_);
		multiFrame_.setBackground(background,highscoreFrameIndex_);
		multiFrame_.setBackground(background,customFrameIndex_);
		multiFrame_.setBackground(background,optionFrameIndex_);

		hDistance_ = 30;

		initFrameMenu();
		initHighscoreFrame();
		initPlayFrame();
		initCustomPlayFrame();
		initOptionFrame();

		multiFrame_.setCurrentFrame(0);
		mw::Window::setUnicodeInputEnable(true);
		resize(500,600);

		pauseKey_ = SDLK_p;
		restartKey_ = SDLK_F2;
	}

	void GuiWindow::quit() {
		setQuiting(true);
	}

	ButtonPtr GuiWindow::createTextButton(std::string text, int size, std::function<void(GuiItem*)> onClick) {
		Color textColor(1.0,0.1,0.1);
		Color focus(0.8, 0.1, 0, 0.3);
		Color onHover(0.6, 0.1, 0.1);
		Color notHover(0.4, 0.0, 0.0,0.0);
		Color pushed(0.8, 0.0, 0, 0.7);
		ButtonPtr button(new TextButton(text, size, fontDefault,
			textColor,focus,onHover,notHover,pushed));
		button->addOnClickListener(onClick);
		return button;
	}

	TextBoxPtr GuiWindow::createTextBox(int size) {
		Color textColor(1.0,1.0,1.0);
		Color focus(0.8, 0.1, 0, 0.3);
		Color onHover(0.6, 0.1, 0.1);
		return TextBoxPtr(new TextBoxDraw(size, fontDefault, 30, textColor, focus, onHover));
	}

	void GuiWindow::initFrameMenu() {
		multiFrame_.setCurrentFrame(0);
		multiFrame_.add(std::make_shared<TextItem>("MWetris",fontDefault50,80,Color(0.9,0.2,0,0.9)),10,50,false,true);
		multiFrame_.add(std::make_shared<TextItem>("Made by Marcus Welander",fontDefault18,12,Color(0.9,0.2,0,0.9)),0,0,true,false);

		// Upper bar.
		multiFrame_.addBar(std::make_shared<BarColor>(Bar::UP,hDistance_,Color(0.5,0,0,0.30)));

		// Text is outside due to invY which dont know where the top of the text begin.
		// The bottom is put where it is supposed to but the invers not.
		ButtonPtr b1 = createTextButton("Resume", hDistance_, [&](GuiItem*) {
			multiFrame_.setCurrentFrame(playFrameIndex_);
		});
		resumeButton_ = b1;
		resumeButton_->setVisible(false);

		// Menu.
		ButtonPtr b2 = createTextButton("Play", 35, [&](GuiItem*) {
			resumeButton_->setVisible(true);
			multiFrame_.setCurrentFrame(playFrameIndex_);
			restartGame();
		});

		ButtonPtr b3 = createTextButton("Custom play", 35, [&](GuiItem*) {
			multiFrame_.setCurrentFrame(customFrameIndex_);
		});
		ButtonPtr b4 = createTextButton("Highscore", 35, [&](GuiItem*) {
			multiFrame_.setCurrentFrame(highscoreFrameIndex_);
		});
		ButtonPtr b5 = createTextButton("Options", 35, [&](GuiItem*) {
			multiFrame_.setCurrentFrame(optionFrameIndex_);
		});
		ButtonPtr b6 = createTextButton("Exit", 35, [&](GuiItem*) {
			quit();
		});
		b6->addSdlEventListener([&](GuiItem* item, const SDL_Event& sdlEvent) {
			switch (sdlEvent.type) {
			case SDL_KEYDOWN:
				SDLKey key = sdlEvent.key.keysym.sym;
				if (key == SDLK_ESCAPE) {
					quit();
					break;
				}
			}
		});

		int x = 10;
		int y = 150;
		int distance = 50;

		// In Bar.
		multiFrame_.add(b1,0,0,false,true);

		// Menu.
		multiFrame_.add(b2,x,y,false,true);
		y += distance;
		multiFrame_.add(b3,x,y,false,true);
		y += distance;
		multiFrame_.add(b4,x,y,false,true);
		y += distance;
		multiFrame_.add(b5,x,y,false,true);
		y += distance;
		multiFrame_.add(b6,x,y,false,true);
		auto textBox = createTextBox(100);
		multiFrame_.add(textBox,x+50,y+50,false,true);

		// Focus is switchable by the left and right arrow.
		GroupPtr group = std::make_shared<Group>(SDLK_UP,SDLK_DOWN);
		group->add(b1);
		group->add(b2);
		group->add(b3);
		group->add(b4);
		group->add(b5);
		group->add(b6);
		group->add(textBox);

		multiFrame_.add(group,0,0,false,false);
	}

	void GuiWindow::initPlayFrame() {
		multiFrame_.setCurrentFrame(playFrameIndex_);

		// Upper bar.
		multiFrame_.addBar(std::make_shared<BarColor>(Bar::UP,hDistance_,Color(0.5,0,0,0.30)));

		ButtonPtr b1 = createTextButton("Menu", hDistance_, [&](GuiItem* item) {
			multiFrame_.setCurrentFrame(0);
			item->setFocus(false);
		});
		b1->addSdlEventListener([&](GuiItem* item, const SDL_Event& sdlEvent) {
			switch (sdlEvent.type) {
			case SDL_KEYDOWN:
				SDLKey key = sdlEvent.key.keysym.sym;
				if (key == SDLK_ESCAPE) {
					item->click();
					break;
				}
			}
		});

		ButtonPtr b2 = createTextButton("Restart[F2]", hDistance_, [&](GuiItem* item) {
			restartGame();
			item->setFocus(false);
		});
		b2->addSdlEventListener([&](GuiItem* item, const SDL_Event& sdlEvent) {
			switch (sdlEvent.type) {
			case SDL_KEYDOWN:
				SDLKey key = sdlEvent.key.keysym.sym;
				if (key == restartKey_) {
					item->click();
					break;
				}
			}
		});

		ButtonPtr b3 = std::make_shared<ChooseNbrOfPlayers>(hDistance_);
		b3->addOnClickListener([&](GuiItem* item) {
			ChooseNbrOfPlayers* nbrOfPlayers = (ChooseNbrOfPlayers*) item;
			int nbr = 1 + nbrOfPlayers->getNbrOfPlayers();
			if (nbr > 4) {
				nbr = 1;
			}
			nbrOfPlayers->setNbrOfPlayers(nbr);
			restartLocalGame(nbr);
		});

		ButtonPtr b4 = createTextButton("Pause[P]", hDistance_, [&](GuiItem* item) {
			TextButton* textB = (TextButton*) item;
			// The game is paused?
			if (isPaused()) {
				// The game will now be unpaused.
				textB->setText("Pause[P]");
			} else {
				// The game will now be unpaused.
				textB->setText("Unpause[P]");
			}
			setPause(!isPaused());
			item->setFocus(false);
		});
		b4->addSdlEventListener([&](GuiItem* item, const SDL_Event& sdlEvent) {
			switch (sdlEvent.type) {
			case SDL_KEYDOWN:
				SDLKey key = sdlEvent.key.keysym.sym;
				if (key == pauseKey_) {
					Button* button = (Button*) item;
					button->click();
					break;
				}
			}
		});

		multiFrame_.add(b1,0,0,false,true);
		multiFrame_.add(b2,80,0,false,true);
		multiFrame_.add(b3,80 + b2->getWidth(),0,false,true);
		multiFrame_.add(b4,0,0,true,true);
	}

	void GuiWindow::initHighscoreFrame() {
		multiFrame_.setCurrentFrame(highscoreFrameIndex_);

		// Upper bar.
		multiFrame_.addBar(std::make_shared<BarColor>(Bar::UP,hDistance_,Color(0.5,0,0,0.30)));

		ButtonPtr b1 = createTextButton("Menu", hDistance_, [&](GuiItem*) {
			multiFrame_.setCurrentFrame(0);
		});
		b1->addSdlEventListener([&](GuiItem* item, const SDL_Event& sdlEvent) {
			switch (sdlEvent.type) {
			case SDL_KEYDOWN:
				SDLKey key = sdlEvent.key.keysym.sym;
				if (key == SDLK_ESCAPE) {
					item->click();
					break;
				}
			}
		});

		multiFrame_.add(b1,0,0,false,true);
	}

	void GuiWindow::initCustomPlayFrame() {
		multiFrame_.setCurrentFrame(customFrameIndex_);

		// Upper bar.
		multiFrame_.addBar(std::make_shared<BarColor>(Bar::UP,hDistance_,Color(0.5,0,0,0.30)));

		ButtonPtr menu = createTextButton("Menu", hDistance_, [&](GuiItem*) {
			multiFrame_.setCurrentFrame(0);
		});

		multiFrame_.add(menu,0,0,false,true);

		// Set board size ------------------------------------------------------
		TextItemPtr textItem(new TextItem("Width",fontDefault18,18,Color(1.0,1.0,1.0)));
		multiFrame_.add(textItem,45,50,false,true);
		customPlayWidth_ = createTextBox(35);
		customPlayWidth_->setInputFormatter(std::make_shared<InputNumberFormatter>(2));
		customPlayWidth_->setText("10");
		multiFrame_.add(customPlayWidth_,100,50,false,true);

		TextItemPtr textItem2(new TextItem("Height",fontDefault18,18,Color(1.0,1.0,1.0)));
		multiFrame_.add(textItem2,140,50,false,true);
		customPlayHeight_ = createTextBox(35);
		customPlayHeight_->setInputFormatter(std::make_shared<InputNumberFormatter>(2));
		customPlayHeight_->setText("10");
		multiFrame_.add(customPlayHeight_,200,50,false,true);

		// Set max level -----------------------------------------------------
		TextItemPtr textItem3(new TextItem("Max Level",fontDefault18,18,Color(1.0,1.0,1.0)));
		multiFrame_.add(textItem3,45,100,false,true);
		customPlaymaxLevel_ = createTextBox(35);
		customPlaymaxLevel_->setInputFormatter(std::make_shared<InputNumberFormatter>(2));
		customPlaymaxLevel_->setText("20");
		multiFrame_.add(customPlaymaxLevel_,140,100,false,true);

		// Create game -----------------------------------------------------
		auto button = createTextButton("Create game", 30, [&](GuiItem*) {
			multiFrame_.setCurrentFrame(playFrameIndex_);
			std::stringstream stream;
			stream << customPlayWidth_->getText() << " ";
			stream << customPlayHeight_->getText() << " ";
			stream << customPlaymaxLevel_->getText() << " ";
			int width, height, maxLevel;
			stream >> width >> height >> maxLevel;
			createCustomGame(width,height,maxLevel);
			resumeButton_->setVisible(true);
		});

		multiFrame_.add(button,45,150,false,true);

		// Add all items to group!
		GroupPtr group = std::make_shared<Group>(SDLK_UP,SDLK_DOWN);
		group->add(customPlayWidth_);
		group->add(customPlayHeight_);
		group->add(customPlaymaxLevel_);
		group->add(button);
		group->add(menu);

		multiFrame_.add(group,0,0,false,false);
	}

	void GuiWindow::initOptionFrame() {
		multiFrame_.setCurrentFrame(optionFrameIndex_);

		// Upper bar.
		multiFrame_.addBar(std::make_shared<BarColor>(Bar::UP,hDistance_,Color(0.5,0,0,0.30)));

		ButtonPtr b1 = createTextButton("Menu", hDistance_, [&](GuiItem*) {
			multiFrame_.setCurrentFrame(0);
		});
		b1->addSdlEventListener([&](GuiItem* item, const SDL_Event& sdlEvent) {
			switch (sdlEvent.type) {
			case SDL_KEYDOWN:
				SDLKey key = sdlEvent.key.keysym.sym;
				if (key == SDLK_ESCAPE) {
					item->click();
					break;
				}
			}
		});

		multiFrame_.add(b1,0,0,false,true);
	}

	void GuiWindow::initCreateClientFrame() {
		multiFrame_.setCurrentFrame(optionFrameIndex_);

		// Upper bar.
		multiFrame_.addBar(std::make_shared<BarColor>(Bar::UP,hDistance_,Color(0.5,0,0,0.30)));

		ButtonPtr b1 = createTextButton("Menu", hDistance_, [&](GuiItem*) {
			multiFrame_.setCurrentFrame(0);
		});
	}

	void GuiWindow::resize(int width, int height) {
		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		glViewport(0,0,width,height);
		glOrtho(0,width,0,height,-1,1);
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
	}

	// Override mw::Window
	void GuiWindow::update(Uint32 deltaTime) {
		multiFrame_.draw(deltaTime/1000.0);
		if (isUpdatingGame()) {
			updateGame(deltaTime);
		}
	}

	// Override mw::Window
	void GuiWindow::eventUpdate(const SDL_Event& windowEvent) {
		multiFrame_.eventUpdate(windowEvent);
		if (isUpdatingGame()) {
			updateGameEvent(windowEvent);
		}
	}

} // Namespace gui.<commit_msg>Fixed! Closing the window now makes it close.<commit_after>#include "guiwindow.h"

#include "barcolor.h"
#include "imagebackground.h"
#include "textbutton.h"
#include "group.h"
#include "multiframe.h"
#include "textitem.h"
#include "textboxdraw.h"
#include "inputnumberformatter.h"
#include "choosenbrofplayers.h"

#include "gamesprite.h"
#include "gamefont.h"

#include <mw/font.h>
#include <mw/sprite.h>
#include <mw/window.h>

#include <iostream>
#include <string>

namespace gui {

	GuiWindow::GuiWindow() : mw::Window(500,600,"MWetris","images/tetris.bmp") {
		playFrameIndex_ = multiFrame_.addFrameBack();
		highscoreFrameIndex_ = multiFrame_.addFrameBack();
		customFrameIndex_ = multiFrame_.addFrameBack();
		optionFrameIndex_ = multiFrame_.addFrameBack();

		auto background = std::make_shared<ImageBackground>(spriteBackground);
		multiFrame_.setBackground(background,0);
		multiFrame_.setBackground(background,playFrameIndex_);
		multiFrame_.setBackground(background,highscoreFrameIndex_);
		multiFrame_.setBackground(background,customFrameIndex_);
		multiFrame_.setBackground(background,optionFrameIndex_);

		hDistance_ = 30;

		initFrameMenu();
		initHighscoreFrame();
		initPlayFrame();
		initCustomPlayFrame();
		initOptionFrame();

		multiFrame_.setCurrentFrame(0);
		mw::Window::setUnicodeInputEnable(true);
		resize(500,600);

		pauseKey_ = SDLK_p;
		restartKey_ = SDLK_F2;
	}

	void GuiWindow::quit() {
		setQuiting(true);
	}

	ButtonPtr GuiWindow::createTextButton(std::string text, int size, std::function<void(GuiItem*)> onClick) {
		Color textColor(1.0,0.1,0.1);
		Color focus(0.8, 0.1, 0, 0.3);
		Color onHover(0.6, 0.1, 0.1);
		Color notHover(0.4, 0.0, 0.0,0.0);
		Color pushed(0.8, 0.0, 0, 0.7);
		ButtonPtr button(new TextButton(text, size, fontDefault,
			textColor,focus,onHover,notHover,pushed));
		button->addOnClickListener(onClick);
		return button;
	}

	TextBoxPtr GuiWindow::createTextBox(int size) {
		Color textColor(1.0,1.0,1.0);
		Color focus(0.8, 0.1, 0, 0.3);
		Color onHover(0.6, 0.1, 0.1);
		return TextBoxPtr(new TextBoxDraw(size, fontDefault, 30, textColor, focus, onHover));
	}

	void GuiWindow::initFrameMenu() {
		multiFrame_.setCurrentFrame(0);
		multiFrame_.add(std::make_shared<TextItem>("MWetris",fontDefault50,80,Color(0.9,0.2,0,0.9)),10,50,false,true);
		multiFrame_.add(std::make_shared<TextItem>("Made by Marcus Welander",fontDefault18,12,Color(0.9,0.2,0,0.9)),0,0,true,false);

		// Upper bar.
		multiFrame_.addBar(std::make_shared<BarColor>(Bar::UP,hDistance_,Color(0.5,0,0,0.30)));

		// Text is outside due to invY which dont know where the top of the text begin.
		// The bottom is put where it is supposed to but the invers not.
		ButtonPtr b1 = createTextButton("Resume", hDistance_, [&](GuiItem*) {
			multiFrame_.setCurrentFrame(playFrameIndex_);
		});
		resumeButton_ = b1;
		resumeButton_->setVisible(false);

		// Menu.
		ButtonPtr b2 = createTextButton("Play", 35, [&](GuiItem*) {
			resumeButton_->setVisible(true);
			multiFrame_.setCurrentFrame(playFrameIndex_);
			restartGame();
		});

		ButtonPtr b3 = createTextButton("Custom play", 35, [&](GuiItem*) {
			multiFrame_.setCurrentFrame(customFrameIndex_);
		});
		ButtonPtr b4 = createTextButton("Highscore", 35, [&](GuiItem*) {
			multiFrame_.setCurrentFrame(highscoreFrameIndex_);
		});
		ButtonPtr b5 = createTextButton("Options", 35, [&](GuiItem*) {
			multiFrame_.setCurrentFrame(optionFrameIndex_);
		});
		ButtonPtr b6 = createTextButton("Exit", 35, [&](GuiItem*) {
			quit();
		});
		b6->addSdlEventListener([&](GuiItem* item, const SDL_Event& sdlEvent) {
			switch (sdlEvent.type) {
			case SDL_QUIT:
				quit();
				break;
			case SDL_KEYDOWN:
				SDLKey key = sdlEvent.key.keysym.sym;
				if (key == SDLK_ESCAPE) {
					quit();
					break;
				}
			}
		});

		int x = 10;
		int y = 150;
		int distance = 50;

		// In Bar.
		multiFrame_.add(b1,0,0,false,true);

		// Menu.
		multiFrame_.add(b2,x,y,false,true);
		y += distance;
		multiFrame_.add(b3,x,y,false,true);
		y += distance;
		multiFrame_.add(b4,x,y,false,true);
		y += distance;
		multiFrame_.add(b5,x,y,false,true);
		y += distance;
		multiFrame_.add(b6,x,y,false,true);
		auto textBox = createTextBox(100);
		multiFrame_.add(textBox,x+50,y+50,false,true);

		// Focus is switchable by the left and right arrow.
		GroupPtr group = std::make_shared<Group>(SDLK_UP,SDLK_DOWN);
		group->add(b1);
		group->add(b2);
		group->add(b3);
		group->add(b4);
		group->add(b5);
		group->add(b6);
		group->add(textBox);

		multiFrame_.add(group,0,0,false,false);
	}

	void GuiWindow::initPlayFrame() {
		multiFrame_.setCurrentFrame(playFrameIndex_);

		// Upper bar.
		multiFrame_.addBar(std::make_shared<BarColor>(Bar::UP,hDistance_,Color(0.5,0,0,0.30)));

		ButtonPtr b1 = createTextButton("Menu", hDistance_, [&](GuiItem* item) {
			multiFrame_.setCurrentFrame(0);
			item->setFocus(false);
		});
		b1->addSdlEventListener([&](GuiItem* item, const SDL_Event& sdlEvent) {
			switch (sdlEvent.type) {
			case SDL_KEYDOWN:
				SDLKey key = sdlEvent.key.keysym.sym;
				if (key == SDLK_ESCAPE) {
					item->click();
					break;
				}
			}
		});

		ButtonPtr b2 = createTextButton("Restart[F2]", hDistance_, [&](GuiItem* item) {
			restartGame();
			item->setFocus(false);
		});
		b2->addSdlEventListener([&](GuiItem* item, const SDL_Event& sdlEvent) {
			switch (sdlEvent.type) {
			case SDL_KEYDOWN:
				SDLKey key = sdlEvent.key.keysym.sym;
				if (key == restartKey_) {
					item->click();
					break;
				}
			}
		});

		ButtonPtr b3 = std::make_shared<ChooseNbrOfPlayers>(hDistance_);
		b3->addOnClickListener([&](GuiItem* item) {
			ChooseNbrOfPlayers* nbrOfPlayers = (ChooseNbrOfPlayers*) item;
			int nbr = 1 + nbrOfPlayers->getNbrOfPlayers();
			if (nbr > 4) {
				nbr = 1;
			}
			nbrOfPlayers->setNbrOfPlayers(nbr);
			restartLocalGame(nbr);
		});

		ButtonPtr b4 = createTextButton("Pause[P]", hDistance_, [&](GuiItem* item) {
			TextButton* textB = (TextButton*) item;
			// The game is paused?
			if (isPaused()) {
				// The game will now be unpaused.
				textB->setText("Pause[P]");
			} else {
				// The game will now be unpaused.
				textB->setText("Unpause[P]");
			}
			setPause(!isPaused());
			item->setFocus(false);
		});
		b4->addSdlEventListener([&](GuiItem* item, const SDL_Event& sdlEvent) {
			switch (sdlEvent.type) {
			case SDL_KEYDOWN:
				SDLKey key = sdlEvent.key.keysym.sym;
				if (key == pauseKey_) {
					Button* button = (Button*) item;
					button->click();
					break;
				}
			}
		});

		multiFrame_.add(b1,0,0,false,true);
		multiFrame_.add(b2,80,0,false,true);
		multiFrame_.add(b3,80 + b2->getWidth(),0,false,true);
		multiFrame_.add(b4,0,0,true,true);
	}

	void GuiWindow::initHighscoreFrame() {
		multiFrame_.setCurrentFrame(highscoreFrameIndex_);

		// Upper bar.
		multiFrame_.addBar(std::make_shared<BarColor>(Bar::UP,hDistance_,Color(0.5,0,0,0.30)));

		ButtonPtr b1 = createTextButton("Menu", hDistance_, [&](GuiItem*) {
			multiFrame_.setCurrentFrame(0);
		});
		b1->addSdlEventListener([&](GuiItem* item, const SDL_Event& sdlEvent) {
			switch (sdlEvent.type) {
			case SDL_KEYDOWN:
				SDLKey key = sdlEvent.key.keysym.sym;
				if (key == SDLK_ESCAPE) {
					item->click();
					break;
				}
			}
		});

		multiFrame_.add(b1,0,0,false,true);
	}

	void GuiWindow::initCustomPlayFrame() {
		multiFrame_.setCurrentFrame(customFrameIndex_);

		// Upper bar.
		multiFrame_.addBar(std::make_shared<BarColor>(Bar::UP,hDistance_,Color(0.5,0,0,0.30)));

		ButtonPtr menu = createTextButton("Menu", hDistance_, [&](GuiItem*) {
			multiFrame_.setCurrentFrame(0);
		});

		multiFrame_.add(menu,0,0,false,true);

		// Set board size ------------------------------------------------------
		TextItemPtr textItem(new TextItem("Width",fontDefault18,18,Color(1.0,1.0,1.0)));
		multiFrame_.add(textItem,45,50,false,true);
		customPlayWidth_ = createTextBox(35);
		customPlayWidth_->setInputFormatter(std::make_shared<InputNumberFormatter>(2));
		customPlayWidth_->setText("10");
		multiFrame_.add(customPlayWidth_,100,50,false,true);

		TextItemPtr textItem2(new TextItem("Height",fontDefault18,18,Color(1.0,1.0,1.0)));
		multiFrame_.add(textItem2,140,50,false,true);
		customPlayHeight_ = createTextBox(35);
		customPlayHeight_->setInputFormatter(std::make_shared<InputNumberFormatter>(2));
		customPlayHeight_->setText("10");
		multiFrame_.add(customPlayHeight_,200,50,false,true);

		// Set max level -----------------------------------------------------
		TextItemPtr textItem3(new TextItem("Max Level",fontDefault18,18,Color(1.0,1.0,1.0)));
		multiFrame_.add(textItem3,45,100,false,true);
		customPlaymaxLevel_ = createTextBox(35);
		customPlaymaxLevel_->setInputFormatter(std::make_shared<InputNumberFormatter>(2));
		customPlaymaxLevel_->setText("20");
		multiFrame_.add(customPlaymaxLevel_,140,100,false,true);

		// Create game -----------------------------------------------------
		auto button = createTextButton("Create game", 30, [&](GuiItem*) {
			multiFrame_.setCurrentFrame(playFrameIndex_);
			std::stringstream stream;
			stream << customPlayWidth_->getText() << " ";
			stream << customPlayHeight_->getText() << " ";
			stream << customPlaymaxLevel_->getText() << " ";
			int width, height, maxLevel;
			stream >> width >> height >> maxLevel;
			createCustomGame(width,height,maxLevel);
			resumeButton_->setVisible(true);
		});

		multiFrame_.add(button,45,150,false,true);

		// Add all items to group!
		GroupPtr group = std::make_shared<Group>(SDLK_UP,SDLK_DOWN);
		group->add(customPlayWidth_);
		group->add(customPlayHeight_);
		group->add(customPlaymaxLevel_);
		group->add(button);
		group->add(menu);

		multiFrame_.add(group,0,0,false,false);
	}

	void GuiWindow::initOptionFrame() {
		multiFrame_.setCurrentFrame(optionFrameIndex_);

		// Upper bar.
		multiFrame_.addBar(std::make_shared<BarColor>(Bar::UP,hDistance_,Color(0.5,0,0,0.30)));

		ButtonPtr b1 = createTextButton("Menu", hDistance_, [&](GuiItem*) {
			multiFrame_.setCurrentFrame(0);
		});
		b1->addSdlEventListener([&](GuiItem* item, const SDL_Event& sdlEvent) {
			switch (sdlEvent.type) {
			case SDL_KEYDOWN:
				SDLKey key = sdlEvent.key.keysym.sym;
				if (key == SDLK_ESCAPE) {
					item->click();
					break;
				}
			}
		});

		multiFrame_.add(b1,0,0,false,true);
	}

	void GuiWindow::initCreateClientFrame() {
		multiFrame_.setCurrentFrame(optionFrameIndex_);

		// Upper bar.
		multiFrame_.addBar(std::make_shared<BarColor>(Bar::UP,hDistance_,Color(0.5,0,0,0.30)));

		ButtonPtr b1 = createTextButton("Menu", hDistance_, [&](GuiItem*) {
			multiFrame_.setCurrentFrame(0);
		});
	}

	void GuiWindow::resize(int width, int height) {
		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		glViewport(0,0,width,height);
		glOrtho(0,width,0,height,-1,1);
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
	}

	// Override mw::Window
	void GuiWindow::update(Uint32 deltaTime) {
		multiFrame_.draw(deltaTime/1000.0);
		if (isUpdatingGame()) {
			updateGame(deltaTime);
		}
	}

	// Override mw::Window
	void GuiWindow::eventUpdate(const SDL_Event& windowEvent) {
		multiFrame_.eventUpdate(windowEvent);
		if (isUpdatingGame()) {
			updateGameEvent(windowEvent);
		}
	}

} // Namespace gui.<|endoftext|>


<commit_before>#include "catch.hpp"
#include <cobalt/object.hpp>

using namespace cobalt;

class renderer : public basic_component<"renderer"_hash> {
public:
	renderer(bool& destroyed) : _destroyed(destroyed) {}
	virtual ~renderer() { _destroyed = true; }

	virtual void draw() const { }

private:
	bool& _destroyed;
};

class transform : public basic_component<"transform"_hash> {
public:
};

class my_component : public component {
public:
	virtual hash_type type() const noexcept override { return "my_component"_hash; }
};

TEST_CASE("object") {
	ref_ptr<object> o = new object();

	SECTION("information") {
		printf("sizeof(std::string) := %zu\n", sizeof(std::string));
		printf("sizeof(std::vector<object>) := %zu\n", sizeof(std::vector<object>));
		printf("sizeof(std::deque<object>) := %zu\n", sizeof(std::deque<object>));
		printf("sizeof(object) := %zu\n", sizeof(object));
		printf("sizeof(component) := %zu\n", sizeof(component));
		printf("sizeof(renderer) := %zu\n", sizeof(renderer));
		printf("sizeof(my_component) := %zu\n", sizeof(my_component));
	}

	SECTION("add child") {
		auto child = o->add_child(new object());

		REQUIRE(child->parent() == o.get());
	}

	SECTION("add component") {
		bool renderer_destroyed = false;
		auto r = new renderer(renderer_destroyed);

		auto c = o->add_component(r);

		SECTION("check preconditions") {
			REQUIRE(c == r);
			REQUIRE(c->object() == o.get());
			REQUIRE(renderer_destroyed == false);
		}

		SECTION("find component by component type") {
			auto f1 = (renderer*)o->find_component(renderer::component_type);

			REQUIRE(f1 == r);
			REQUIRE(o->find_component(transform::component_type) == nullptr);

			f1->draw();
		}

		SECTION("find component by component name") {
			auto f1 = (renderer*)o->find_component("renderer"_hash);

			REQUIRE(f1 == r);
			REQUIRE(o->find_component("transform"_hash) == nullptr);
			REQUIRE(o->find_component("my_component"_hash) == nullptr);

			f1->draw();
		}

		SECTION("find component with template") {
			auto f2 = o->find_component<renderer>();

			REQUIRE(f2 == r);
			REQUIRE(o->find_component<transform>() == nullptr);
			//o->find_component<my_component>(); // won't compile due to enable_if<>

			f2->draw();
		}

		SECTION("find components by component type") {
			std::vector<component*> vec;
			o->find_components(renderer::component_type, std::back_inserter(vec));

			REQUIRE(vec.size() == 1);
			REQUIRE(vec[0] == r);
		}

		SECTION("find components with template") {
			std::vector<renderer*> vec;
			o->find_components<renderer>(std::back_inserter(vec));

			REQUIRE(vec.size() == 1);
			REQUIRE(vec[0] == r);
		}

		SECTION("remove component") {
			r->remove_from_parent();

			REQUIRE(renderer_destroyed == true);
		}
	}
}
<commit_msg>Added more unit tests for object.hpp<commit_after>#include "catch.hpp"
#include <cobalt/object.hpp>

using namespace cobalt;

class renderer : public basic_component<"renderer"_hash> {
public:
	renderer(bool& destroyed) : _destroyed(destroyed) {}
	virtual ~renderer() { _destroyed = true; }

	virtual void draw() const { }

private:
	bool& _destroyed;
};

class transform : public basic_component<"transform"_hash> {
public:
};

class my_component : public component {
public:
	virtual hash_type type() const noexcept override { return "my_component"_hash; }
};

TEST_CASE("information") {
	printf("sizeof(std::string) := %zu\n", sizeof(std::string));
	printf("sizeof(std::vector<object>) := %zu\n", sizeof(std::vector<object>));
	printf("sizeof(std::deque<object>) := %zu\n", sizeof(std::deque<object>));
	printf("sizeof(object) := %zu\n", sizeof(object));
	printf("sizeof(component) := %zu\n", sizeof(component));
	printf("sizeof(renderer) := %zu\n", sizeof(renderer));
	printf("sizeof(my_component) := %zu\n", sizeof(my_component));
}

TEST_CASE("object") {
	ref_ptr<object> o = new object();

	SECTION("add child") {
		auto child = o->add_child(new object());

		REQUIRE(child->parent() == o.get());

		SECTION("remove child") {
			auto removed = o->remove_child(child);

			REQUIRE(removed.get() == child);
		}

		SECTION("self remove child") {
			child->remove_from_parent();

			REQUIRE(o->remove_child(child) == nullptr);
		}
	}

	SECTION("add component") {
		bool renderer_destroyed = false;
		auto r = new renderer(renderer_destroyed);

		auto c = o->add_component(r);

		o->add_component(new transform());

		SECTION("check preconditions") {
			REQUIRE(c == r);
			REQUIRE(c->object() == o.get());
			REQUIRE(renderer_destroyed == false);
		}

		SECTION("find component by type") {
			auto f1 = (renderer*)o->find_component(renderer::component_type);

			REQUIRE(f1 == r);
			REQUIRE_FALSE(o->find_component(transform::component_type) == nullptr);

			f1->draw(); // will compile
		}

		SECTION("find component by name") {
			auto f1 = (renderer*)o->find_component("renderer"_hash);

			REQUIRE(f1 == r);
			REQUIRE_FALSE(o->find_component("transform"_hash) == nullptr);
			REQUIRE(o->find_component("my_component"_hash) == nullptr);

			f1->draw(); // will compile
		}

		SECTION("find component with template") {
			auto f2 = o->find_component<renderer>();

			REQUIRE(f2 == r);
			REQUIRE_FALSE(o->find_component<transform>() == nullptr);
			//o->find_component<my_component>(); // won't compile due to enable_if<>

			f2->draw(); // will compile
		}

		SECTION("find components by type") {
			std::vector<component*> vec;
			o->find_components(renderer::component_type, std::back_inserter(vec));

			REQUIRE(vec.size() == 1);
			REQUIRE(vec[0] == r);
		}

		SECTION("find components with template") {
			std::vector<renderer*> vec;
			o->find_components<renderer>(std::back_inserter(vec));

			REQUIRE(vec.size() == 1);
			REQUIRE(vec[0] == r);
		}

		SECTION("remove component") {
			r->remove_from_parent();

			REQUIRE(renderer_destroyed == true);
		}
	}
}
<|endoftext|>


<commit_before><commit_msg>fix order optimizer poly_start at the cost of efficiency<commit_after><|endoftext|>


<commit_before><commit_msg>Correct Camera projection matrix<commit_after><|endoftext|>


<commit_before><commit_msg>Render: Render multiple layer of the level<commit_after><|endoftext|>


<commit_before><commit_msg>remove empty destructors in-lined on Mac, causing build errors<commit_after><|endoftext|>


<commit_before><commit_msg>Simplifications in unit tests for stencil<commit_after><|endoftext|>


<commit_before>/** \brief Utility for displaying various bits of info about a collection of MARC records.
 *  \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
 *
 *  \copyright 2015-2018 Universitätsbibliothek Tübingen.  All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <algorithm>
#include <iostream>
#include <map>
#include <stdexcept>
#include <unordered_set>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include "FileUtil.h"
#include "MARC.h"
#include "util.h"

namespace {

[[noreturn]] void Usage() {
    std::cerr << "Usage: " << ::progname << " [--do-not-abort-on-empty-subfields] marc_data\n";
    std::exit(EXIT_FAILURE);
}

void CheckFieldOrder(const MARC::Record &record) {
    std::string last_tag;
    for (const auto &field : record) {
        const std::string current_tag(field.getTag().toString());
        if (unlikely(current_tag < last_tag))
            LOG_ERROR("invalid tag order in the record with control number \"" + record.getControlNumber() + "\"!");
        last_tag = current_tag;
    }
}

void CheckDataField(const bool do_not_abort_on_empty_subfields, const MARC::Record::Field &data_field, const std::string &control_number) {
    const std::string &contents(data_field.getContents());

    if (contents.length() < 5) // Need at least 2 indicators a delimiter a subfield code + subfield contents
        LOG_ERROR("short data field in record w/ control number \"" + control_number + "\"!");

    if (contents[2] != '\x1F')
        LOG_ERROR("first subfield delimiter is missing for the record w/ control number \"" + control_number + "\"!");

    // Check the subfield structure for consistency:
    bool delimiter_seen(false), subfield_code_seen(false);
    for (const char ch : contents) {
        if (delimiter_seen) {
            delimiter_seen = false;
            subfield_code_seen = true;
        } else if (ch == '\x1F') {
            if (unlikely(subfield_code_seen)) {
                if (do_not_abort_on_empty_subfields)
                    LOG_WARNING("empty subfield in a " + data_field.getTag().toString() +"-field in the record w/ control number \""
                                + control_number + "\"!");
                else
                    LOG_ERROR("empty subfield in a " + data_field.getTag().toString() +"-field in the record w/ control number \""
                              + control_number + "\"!");
            }
            delimiter_seen = true;
        } else
            subfield_code_seen = false;
    }

    if (unlikely(delimiter_seen))
        LOG_ERROR("subfield delimiter at end of " + data_field.getTag().toString() + "-field in record w/ control number \""
                  + control_number + "\"!");
    if (unlikely(subfield_code_seen)) {
        if (do_not_abort_on_empty_subfields)
            LOG_WARNING("empty subfield at the end of a " + data_field.getTag().toString() + "-field in the record w/ control number \""
                        + control_number + "\"!");
        else
            LOG_ERROR("empty subfield at the end of a " + data_field.getTag().toString() + "-field in the record w/ control number \""
                      + control_number + "\"!");
    }
}

void CheckLocalBlockConsistency(const MARC::Record &record) {
    auto field(record.begin());

    // Skip to the beginning of the first local block:
    while (field != record.end() and field->getTag().toString() != "LOK")
        ++field;

    // Check the internal structure of each local block:
    while (field != record.end()) {
        if (field->getLocalTag() != "000")
            LOG_ERROR("local block does not start w/ a 000 pseudo tag in the record w/ control number \"" + record.getControlNumber()
                      + "\"!!");
        if (++field == record.end() or field->getLocalTag() != "001")
            LOG_ERROR("local block does not contain a 001 pseudo tag after a 000 pseudo tag in the record w/ control number \""
                      + record.getControlNumber() + "\"!!");

        std::string last_local_tag;
        while (field != record.end() and field->getLocalTag() != "000") {
            const std::string current_local_tag(field->getLocalTag());
            if (unlikely(current_local_tag < last_local_tag))
                LOG_ERROR("invalid tag order in a local block in the record with control number \"" + record.getControlNumber() + "\"!");
            last_local_tag = current_local_tag;
            ++field;
        }
    }
}

void ProcessRecords(const bool do_not_abort_on_empty_subfields, MARC::Reader * const marc_reader) {
    unsigned record_count(0);

    while (const MARC::Record record = marc_reader->read()) {
        ++record_count;

        const std::string CONTROL_NUMBER(record.getControlNumber());
        if (unlikely(CONTROL_NUMBER.empty()))
            LOG_ERROR("Record #" + std::to_string(record_count) + " is missing a control number!");

        CheckFieldOrder(record);

        MARC::Tag last_tag(std::string(MARC::Record::TAG_LENGTH, ' '));
        for (const auto &field : record) {
            if (not field.getTag().isTagOfControlField())
                CheckDataField(do_not_abort_on_empty_subfields, field, CONTROL_NUMBER);

            if (unlikely(field.getTag() < last_tag))
                LOG_ERROR("Incorrect non-alphanumeric field order in record w/ control number \"" + CONTROL_NUMBER + "\"!");
            last_tag = field.getTag();
        }

        CheckLocalBlockConsistency(record);
    }

    std::cout << "Data set contains " << record_count << " valid MARC record(s).\n";
}

} // unnamed namespace

int Main(int argc, char *argv[]) {
    ::progname = argv[0];

    if (argc < 2)
        Usage();

    bool do_not_abort_on_empty_subfields(false);
    if (std::strcmp(argv[1], "--do-not-abort-on-empty-subfields") == 0) {
        do_not_abort_on_empty_subfields = true;
        --argc, ++argv;
    }

    if (argc != 2)
        Usage();

    std::unique_ptr<MARC::Reader> marc_reader(MARC::Reader::Factory(argv[1]));
    ProcessRecords(do_not_abort_on_empty_subfields, marc_reader.get());

    return EXIT_SUCCESS;
}
<commit_msg>Update marc_check.cc<commit_after>/** \brief Utility for displaying various bits of info about a collection of MARC records.
 *  \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
 *
 *  \copyright 2015-2018 Universitätsbibliothek Tübingen.  All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <algorithm>
#include <iostream>
#include <map>
#include <stdexcept>
#include <unordered_set>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include "FileUtil.h"
#include "MARC.h"
#include "util.h"

namespace {

[[noreturn]] void Usage() {
    std::cerr << "Usage: " << ::progname << " [--do-not-abort-on-empty-subfields] marc_data\n";
    std::exit(EXIT_FAILURE);
}

void CheckFieldOrder(const MARC::Record &record) {
    std::string last_tag;
    for (const auto &field : record) {
        const std::string current_tag(field.getTag().toString());
        if (unlikely(current_tag < last_tag))
            LOG_ERROR("invalid tag order in the record with control number \"" + record.getControlNumber() + "\"!");
        last_tag = current_tag;
    }
}

void CheckDataField(const bool do_not_abort_on_empty_subfields, const MARC::Record::Field &data_field, const std::string &control_number) {
    const std::string &contents(data_field.getContents());

    if (contents.length() < 5) // Need at least 2 indicators a delimiter a subfield code + subfield contents
        LOG_ERROR("short data field in record w/ control number \"" + control_number + "\"!");

    if (contents[2] != '\x1F')
        LOG_ERROR("first subfield delimiter is missing for the record w/ control number \"" + control_number + "\"!");

    // Check the subfield structure for consistency:
    bool delimiter_seen(false), subfield_code_seen(false);
    for (const char ch : contents) {
        if (delimiter_seen) {
            delimiter_seen = false;
            subfield_code_seen = true;
        } else if (ch == '\x1F') {
            if (unlikely(subfield_code_seen)) {
                if (do_not_abort_on_empty_subfields)
                    LOG_WARNING("empty subfield in a " + data_field.getTag().toString() + "-field in the record w/ control number \""
                                + control_number + "\"!");
                else
                    LOG_ERROR("empty subfield in a " + data_field.getTag().toString() + "-field in the record w/ control number \""
                              + control_number + "\"!");
            }
            delimiter_seen = true;
        } else
            subfield_code_seen = false;
    }

    if (unlikely(delimiter_seen))
        LOG_ERROR("subfield delimiter at end of " + data_field.getTag().toString() + "-field in record w/ control number \""
                  + control_number + "\"!");
    if (unlikely(subfield_code_seen)) {
        if (do_not_abort_on_empty_subfields)
            LOG_WARNING("empty subfield at the end of a " + data_field.getTag().toString() + "-field in the record w/ control number \""
                        + control_number + "\"!");
        else
            LOG_ERROR("empty subfield at the end of a " + data_field.getTag().toString() + "-field in the record w/ control number \""
                      + control_number + "\"!");
    }
}

void CheckLocalBlockConsistency(const MARC::Record &record) {
    auto field(record.begin());

    // Skip to the beginning of the first local block:
    while (field != record.end() and field->getTag().toString() != "LOK")
        ++field;

    // Check the internal structure of each local block:
    while (field != record.end()) {
        if (field->getLocalTag() != "000")
            LOG_ERROR("local block does not start w/ a 000 pseudo tag in the record w/ control number \"" + record.getControlNumber()
                      + "\"!!");
        if (++field == record.end() or field->getLocalTag() != "001")
            LOG_ERROR("local block does not contain a 001 pseudo tag after a 000 pseudo tag in the record w/ control number \""
                      + record.getControlNumber() + "\"!!");

        std::string last_local_tag;
        while (field != record.end() and field->getLocalTag() != "000") {
            const std::string current_local_tag(field->getLocalTag());
            if (unlikely(current_local_tag < last_local_tag))
                LOG_ERROR("invalid tag order in a local block in the record with control number \"" + record.getControlNumber() + "\"!");
            last_local_tag = current_local_tag;
            ++field;
        }
    }
}

void ProcessRecords(const bool do_not_abort_on_empty_subfields, MARC::Reader * const marc_reader) {
    unsigned record_count(0);

    while (const MARC::Record record = marc_reader->read()) {
        ++record_count;

        const std::string CONTROL_NUMBER(record.getControlNumber());
        if (unlikely(CONTROL_NUMBER.empty()))
            LOG_ERROR("Record #" + std::to_string(record_count) + " is missing a control number!");

        CheckFieldOrder(record);

        MARC::Tag last_tag(std::string(MARC::Record::TAG_LENGTH, ' '));
        for (const auto &field : record) {
            if (not field.getTag().isTagOfControlField())
                CheckDataField(do_not_abort_on_empty_subfields, field, CONTROL_NUMBER);

            if (unlikely(field.getTag() < last_tag))
                LOG_ERROR("Incorrect non-alphanumeric field order in record w/ control number \"" + CONTROL_NUMBER + "\"!");
            last_tag = field.getTag();
        }

        CheckLocalBlockConsistency(record);
    }

    std::cout << "Data set contains " << record_count << " valid MARC record(s).\n";
}

} // unnamed namespace

int Main(int argc, char *argv[]) {
    ::progname = argv[0];

    if (argc < 2)
        Usage();

    bool do_not_abort_on_empty_subfields(false);
    if (std::strcmp(argv[1], "--do-not-abort-on-empty-subfields") == 0) {
        do_not_abort_on_empty_subfields = true;
        --argc, ++argv;
    }

    if (argc != 2)
        Usage();

    std::unique_ptr<MARC::Reader> marc_reader(MARC::Reader::Factory(argv[1]));
    ProcessRecords(do_not_abort_on_empty_subfields, marc_reader.get());

    return EXIT_SUCCESS;
}
<|endoftext|>