<commit_before>//
// Created by iskakoff on 19/07/16.
//
#include <iostream>

#include <edlib/EDParams.h>
#include "edlib/Hamiltonian.h"
#include "edlib/SzSymmetry.h"
#include "edlib/SOCRSStorage.h"
#include "edlib/CRSStorage.h"
#include "edlib/HubbardModel.h"
#include "edlib/GreensFunction.h"
#include "edlib/ChiLoc.h"
#include "edlib/HDF5Utils.h"
#include "edlib/SpinResolvedStorage.h"
#include "edlib/StaticObervables.h"
#include "edlib/MeshFactory.h"

int main(int argc, const char ** argv) {
#ifdef USE_MPI
  MPI_Init(&argc, (char ***) &argv);
  alps::mpi::communicator comm;
#endif
  alps::params params(argc, argv);
  EDLib::define_parameters(params);
  if(params.help_requested(std::cout)) {
    exit(0);
  }
  alps::hdf5::archive ar(params["OUTPUT_FILE"], alps::hdf5::archive::WRITE);
#ifdef USE_MPI
  if(comm.rank())
    ar.close();
#endif
  try {
#ifdef USE_MPI
    EDLib::SRSHubbardHamiltonian ham(params, comm);
#else
    EDLib::SRSHubbardHamiltonian ham(params);
#endif
    ham.diag();
    EDLib::hdf5::save_eigen_pairs(ham, ar, "results");
    EDLib::gf::GreensFunction < EDLib::SRSHubbardHamiltonian, alps::gf::matsubara_positive_mesh, alps::gf::statistics::statistics_type> greensFunction(params, ham,alps::gf::statistics::statistics_type::FERMIONIC);
    greensFunction.compute();
    greensFunction.save(ar, "results");
    EDLib::gf::ChiLoc<EDLib::SRSHubbardHamiltonian, alps::gf::matsubara_positive_mesh, alps::gf::statistics::statistics_type> susc(params, ham, alps::gf::statistics::statistics_type::BOSONIC);
    susc.compute();
    susc.save(ar, "results");
    susc.compute<EDLib::gf::NOperator<double> >();
    susc.save(ar, "results");
  } catch (std::exception & e) {
#ifdef USE_MPI
    if(comm.rank() == 0) std::cerr<<e.what();
#else
    std::cerr<<e.what();
#endif
  }
#ifdef USE_MPI
  if(!comm.rank())
#endif
  ar.close();
#ifdef USE_MPI
  MPI_Finalize();
#endif
  return 0;
}
<commit_msg>time measurements. temporary<commit_after>//
// Created by iskakoff on 19/07/16.
//
#include <iostream>

#include <edlib/EDParams.h>
#include "edlib/Hamiltonian.h"
#include "edlib/SzSymmetry.h"
#include "edlib/SOCRSStorage.h"
#include "edlib/CRSStorage.h"
#include "edlib/HubbardModel.h"
#include "edlib/GreensFunction.h"
#include "edlib/ChiLoc.h"
#include "edlib/HDF5Utils.h"
#include "edlib/SpinResolvedStorage.h"
#include "edlib/StaticObervables.h"
#include "edlib/MeshFactory.h"
#include "edlib/ExecutionStatistic.h"

int main(int argc, const char ** argv) {
#ifdef USE_MPI
  MPI_Init(&argc, (char ***) &argv);
  alps::mpi::communicator comm;
#endif
  alps::params params(argc, argv);
  EDLib::define_parameters(params);
  if(params.help_requested(std::cout)) {
    exit(0);
  }
  alps::hdf5::archive ar(params["OUTPUT_FILE"], alps::hdf5::archive::WRITE);
#ifdef USE_MPI
  if(comm.rank())
    ar.close();
#endif
  try {
#ifdef USE_MPI
    EDLib::SRSHubbardHamiltonian ham(params, comm);
#else
    EDLib::SRSHubbardHamiltonian ham(params);
#endif
    EDLib::common::statistics.registerEvent("total");
    ham.diag();
    EDLib::common::statistics.updateEvent("total");
    /*EDLib::hdf5::save_eigen_pairs(ham, ar, "results");
    EDLib::gf::GreensFunction < EDLib::SRSHubbardHamiltonian, alps::gf::matsubara_positive_mesh, alps::gf::statistics::statistics_type> greensFunction(params, ham,alps::gf::statistics::statistics_type::FERMIONIC);
    greensFunction.compute();
    greensFunction.save(ar, "results");
    EDLib::gf::ChiLoc<EDLib::SRSHubbardHamiltonian, alps::gf::matsubara_positive_mesh, alps::gf::statistics::statistics_type> susc(params, ham, alps::gf::statistics::statistics_type::BOSONIC);
    susc.compute();
    susc.save(ar, "results");
    susc.compute<EDLib::gf::NOperator<double> >();
    susc.save(ar, "results");*/
    EDLib::common::statistics.print();
  } catch (std::exception & e) {
#ifdef USE_MPI
    if(comm.rank() == 0) std::cerr<<e.what();
#else
    std::cerr<<e.what();
#endif
  }
#ifdef USE_MPI
  if(!comm.rank())
#endif
  ar.close();
#ifdef USE_MPI
  MPI_Finalize();
#endif
  return 0;
}
<|endoftext|>


<commit_before>#include <iostream.h>
#include <iomanip.h>
#include <SharedMem/MemPool.h>
#include <SharedMem/SharedType.h>
#include <Input/vjPosition/vjFlock.h>
#include <Input/ibox/ibox.h>
#include <Input/vjGlove/vjCyberGlove.h>

int main()
{
  MemPool* anSgiPool = new MemPoolSGI(1024*1024);

  C2Flock* flock = new(anSgiPool) C2Flock;
  IBox* anIbox = new(anSgiPool) IBox;
  CyberGlove* aGlove = new(anSgiPool)
          CyberGlove("/home/vr/CAVE/glove","/dev/ttyd45",38400);

  C2POS_DATA *data,*data2;

  C2IBOX_DATA *iboxData;

  char achar;
  cout << "U - Update\n"
       << "S - Start\n"
       << "X - Stop\n"
       << "Q - Quit\n"
       << "O - Output\n";
  do {
   cin >> achar;

   cout << flush;
   switch(achar) {
     case 'u':case 'U':  break;
     case 's':case 'S': flock->StartSampling();
			anIbox->StartSampling();
			aGlove->StartSampling();
			break;
     case 'x':case 'X': flock->StopSampling();
			anIbox->StopSampling();
			aGlove->StopSampling();
			break;
     case 'o':case 'O':
     for(int z = 0; z < 10; z++){
      C2GLOVE_DATA *gdata;
         flock->UpdateData();
         flock->GetData(data);
	 flock->GetData(data2);
         anIbox->UpdateData();
	 anIbox->GetData(iboxData);
	// aGlove->UpdateData();
//	 aGlove->GetData(gdata);
       system("clear");
     cout << "C2Flock------------------------------------------------------------" << endl
          << "Data: x:" << setw(10) << data->x << " Data2x:" << setw(10) << data2->x << endl
          << "      y:" << setw(10) << data->y << "      y:" << setw(10) << data2->y << endl
          << "      z:" << setw(10) << data->z << "      z:" << setw(10) << data2->z << endl
          << "    azi:" << setw(10) << data->azi << "    azi:" << setw(10) << data2->azi << endl
          << "   elev:" << setw(10) << data->elev << "   elev:" << setw(10) << data2->elev << endl
          << "   roll:" << setw(10) <<data->roll  << "   roll:" << setw(10) <<data2->roll << endl
              << endl;
     cout << "Ibox---------------------------------------------------------------" << endl
	  << " button1: " << iboxData->button[0] << endl
	  << " button2: " << iboxData->button[1] << endl
	  << " button3: " << iboxData->button[2] << endl
	  << " button4: " << iboxData->button[3] << endl << endl;
/*     cout << "Glove--------------------------------------------------------------" << endl
	  << " first finger: " << gdata->joints[0][0] << " " << gdata->joints[0][1] << " " << gdata->joints[0][2] << " " <<
		gdata->joints[0][3] << endl
	  << "second finger: " << gdata->joints[1][0] << " " << gdata->joints[1][1] << " " << gdata->joints[1][2] << " " <<
		gdata->joints[1][3] << endl
	  << " third finger: " << gdata->joints[2][0] << " " << gdata->joints[2][1] << " " << gdata->joints[2][2] << " " <<
		gdata->joints[2][3] << endl
	  << " fourth finger: " << gdata->joints[3][0] << " " << gdata->joints[3][1] << " " << gdata->joints[3][2] << " " <<
		gdata->joints[3][3] << endl;
*/
         sleep(2);
    }
     break;
   }
   cout << achar;
  } while ((achar != 'q') && (achar != 'Q'));

  flock->StopSampling();
  anIbox->StopSampling();
  aGlove->StopSampling();

  delete flock;
  delete anIbox;
  delete aGlove;
  delete anSgiPool;
  return 0;
}
<commit_msg>Brought this file a little closer to compiling with the following changes:<commit_after>#include <iostream.h>
#include <iomanip.h>
#include <SharedMem/vjMemPool.h>
//#include <SharedMem/SharedType.h>
#include <Input/vjPosition/vjFlock.h>
#include <Input/ibox/hci.h>
#include <Input/ibox/ibox.h>
#include <Input/vjInput/vjIbox.h>
#include <Input/vjGlove/vjCyberGlove.h>

int main()
{
  vjMemPool* anSgiPool = new vjSharedPool(1024*1024);

  vjFlock* flock = new(anSgiPool) vjFlock;
  vjIBox* anIbox = new(anSgiPool) vjIBox;
  vjCyberGlove* aGlove = new(anSgiPool)
          vjCyberGlove("/home/vr/CAVE/glove","/dev/ttyd45",38400);

  vjPOS_DATA *data,*data2;

  vjIBOX_DATA *iboxData;

  char achar;
  cout << "U - Update\n"
       << "S - Start\n"
       << "X - Stop\n"
       << "Q - Quit\n"
       << "O - Output\n";
  do {
   cin >> achar;

   cout << flush;
   switch(achar) {
     case 'u':case 'U':  break;
     case 's':case 'S': flock->StartSampling();
			anIbox->StartSampling();
			aGlove->StartSampling();
			break;
     case 'x':case 'X': flock->StopSampling();
			anIbox->StopSampling();
			aGlove->StopSampling();
			break;
     case 'o':case 'O':
     for(int z = 0; z < 10; z++){
      C2GLOVE_DATA *gdata;
         flock->UpdateData();
         flock->GetData(data);
	 flock->GetData(data2);
         anIbox->UpdateData();
	 anIbox->GetData(iboxData);
	// aGlove->UpdateData();
//	 aGlove->GetData(gdata);
       system("clear");
     cout << "vjFlock------------------------------------------------------------" << endl
          << "Data: x:" << setw(10) << data->pos.vec[0] << " Data2x:" << setw(10) << data2->pos.vec[0] << endl
          << "      y:" << setw(10) << data->pos.vec[1] << "      y:" << setw(10) << data2->pos.vec[1] << endl
          << "      z:" << setw(10) << data->pos.vec[2] << "      z:" << setw(10) << data2->pos.vec[2] << endl
          << "    azi:" << setw(10) << data->orient.vec[0] << "    azi:" << setw(10) << data2->orient.vec[0] << endl
          << "   elev:" << setw(10) << data->orient.vec[1] << "   elev:" << setw(10) << data2->orient.vec[1] << endl
          << "   roll:" << setw(10) <<data->orient.vec[2]  << "   roll:" << setw(10) <<data2->orient.vec[2] << endl
              << endl;
     cout << "Ibox---------------------------------------------------------------" << endl
	  << " button1: " << iboxData->button[0] << endl
	  << " button2: " << iboxData->button[1] << endl
	  << " button3: " << iboxData->button[2] << endl
	  << " button4: " << iboxData->button[3] << endl << endl;
/*     cout << "Glove--------------------------------------------------------------" << endl
	  << " first finger: " << gdata->joints[0][0] << " " << gdata->joints[0][1] << " " << gdata->joints[0][2] << " " <<
		gdata->joints[0][3] << endl
	  << "second finger: " << gdata->joints[1][0] << " " << gdata->joints[1][1] << " " << gdata->joints[1][2] << " " <<
		gdata->joints[1][3] << endl
	  << " third finger: " << gdata->joints[2][0] << " " << gdata->joints[2][1] << " " << gdata->joints[2][2] << " " <<
		gdata->joints[2][3] << endl
	  << " fourth finger: " << gdata->joints[3][0] << " " << gdata->joints[3][1] << " " << gdata->joints[3][2] << " " <<
		gdata->joints[3][3] << endl;
*/
         sleep(2);
    }
     break;
   }
   cout << achar;
  } while ((achar != 'q') && (achar != 'Q'));

  flock->StopSampling();
  anIbox->StopSampling();
  aGlove->StopSampling();

  delete flock;
  delete anIbox;
  delete aGlove;
  delete anSgiPool;
  return 0;
}
<|endoftext|>


<commit_before>// XYFunctionInterface.cpp
// Authors: Peter Loan
/*
 * Copyright (c)  2009, Stanford University. All rights reserved.
* Use of the OpenSim software in source form is permitted provided that the following
* conditions are met:
* 	1. The software is used only for non-commercial research and education. It may not
*     be used in relation to any commercial activity.
* 	2. The software is not distributed or redistributed.  Software distribution is allowed
*     only through https://simtk.org/home/opensim.
* 	3. Use of the OpenSim software or derivatives must be acknowledged in all publications,
*      presentations, or documents describing work in which OpenSim or derivatives are used.
* 	4. Credits to developers may not be removed from executables
*     created from modifications of the source.
* 	5. Modifications of source code must retain the above copyright notice, this list of
*     conditions and the following disclaimer.
*
*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
*  EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
*  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
*  SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
*  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
*  TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
*  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
*  OR BUSINESS INTERRUPTION) OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
*  WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

//=============================================================================
// INCLUDES
//=============================================================================
#include "XYFunctionInterface.h"

namespace OpenSim {

bool XYFunctionInterface::isXYFunction(Function* f)
{
	Function* func = f;
	MultiplierFunction* mf = dynamic_cast<MultiplierFunction*>(f);
	if (mf)
		func = mf->getFunction();

	if (dynamic_cast<Constant*>(func) ||
		dynamic_cast<StepFunction*>(func) ||
		dynamic_cast<PiecewiseLinearFunction*>(func) ||
		dynamic_cast<LinearFunction*>(func) ||
		dynamic_cast<SimmSpline*>(func) ||
		dynamic_cast<GCVSpline*>(func)||
		dynamic_cast<PiecewiseConstantFunction*>(func))
		return true;

	return false;
}

XYFunctionInterface::XYFunctionInterface(Function* f) :
   _functionType(typeUndefined),
	_constant(0),
   _stepFunction(0),
   _linearFunction(0),
   _natCubicSpline(0),
   _gcvSpline(0),
   _mStepFunction(0)
{
	Function* func;
	MultiplierFunction* mf = dynamic_cast<MultiplierFunction*>(f);
	if (mf) {
		func = mf->getFunction();
		_scaleFactor = mf->getScale();
	} else {
		func = f;
		_scaleFactor = 1.0;
	}

	_constant = dynamic_cast<Constant*>(func);
	if (_constant) {
		_functionType = typeConstant;
		return;
	}
	_stepFunction = dynamic_cast<StepFunction*>(func);
	if (_stepFunction) {
		_functionType = typeStepFunction;
		return;
	}
	_mStepFunction = dynamic_cast<PiecewiseConstantFunction*>(func);
	if (_mStepFunction) {
		_functionType = typePiecewiseConstantFunction;
		return;
	}
	_piecewiseLinearFunction = dynamic_cast<PiecewiseLinearFunction*>(func);
	if (_piecewiseLinearFunction) {
		_functionType = typePiecewiseLinearFunction;
		return;
	}
	_linearFunction = dynamic_cast<LinearFunction*>(func);
	if (_linearFunction) {
		_functionType = typeLinearFunction;
		return;
	}
	_natCubicSpline = dynamic_cast<SimmSpline*>(func);
	if (_natCubicSpline) {
		_functionType = typeNatCubicSpline;
		return;
	}
	_gcvSpline = dynamic_cast<GCVSpline*>(func);
	if (_gcvSpline) {
		_functionType = typeGCVSpline;
		return;
	}

	throw Exception("Object " + getName() + " of type " +
        getConcreteClassName() + " is not an XYFunction.");
}

int XYFunctionInterface::getNumberOfPoints() const
{
	switch (_functionType)
	{
		case typeConstant:
			return 0;
	   case typePiecewiseConstantFunction:
			return _mStepFunction->getNumberOfPoints();
	   case typePiecewiseLinearFunction:
		   return _piecewiseLinearFunction->getNumberOfPoints();
	   case typeLinearFunction:
		   return 2;
	    case typeNatCubicSpline:
		   return _natCubicSpline->getNumberOfPoints();
	   case typeGCVSpline:
		   return _gcvSpline->getNumberOfPoints();
		default:
			return 0;
	}
}

const double* XYFunctionInterface::getXValues() const
{
	switch (_functionType)
	{
		case typeConstant:
			return NULL;
	   case typeStepFunction:
			return NULL;
	   case typePiecewiseConstantFunction:
		    return _mStepFunction->getXValues();
	   case typePiecewiseLinearFunction:
		   return _piecewiseLinearFunction->getXValues();
	   case typeLinearFunction:
			{
				double* xValues = new double[2];
				xValues[0] = -1.0;
				xValues[1] = 1.0;
				return xValues; // possible memory leak
			}
		case typeNatCubicSpline:
		   return _natCubicSpline->getXValues();
	   case typeGCVSpline:
		   return _gcvSpline->getXValues();
		default:
			return 0;
	}
}

const double* XYFunctionInterface::getYValues() const
{
	const double* yValues = NULL;
	double* tmp = NULL;
	int numPoints = getNumberOfPoints();

	switch (_functionType)
	{
		case typeConstant:
			return NULL;
	   case typeStepFunction:
			return NULL;;
			break;
	   case typePiecewiseConstantFunction:
			yValues = _mStepFunction->getYValues();
			break;
	   case typePiecewiseLinearFunction:
		   yValues = _piecewiseLinearFunction->getYValues();
			break;
	   case typeLinearFunction:
		   tmp = new double[2];
			tmp[0] = _linearFunction->getCoefficients()[1] - _linearFunction->getCoefficients()[0];
			tmp[1] = _linearFunction->getCoefficients()[1] + _linearFunction->getCoefficients()[0];
			break;
	    case typeNatCubicSpline:
		   yValues = _natCubicSpline->getYValues();
			break;
	   case typeGCVSpline:
		   yValues = _gcvSpline->getYValues();
			break;
		default:
			return NULL;
	}

	double* scaledY = new double[numPoints];
	memcpy(scaledY, yValues, numPoints*sizeof(double));
	for (int i=0; i<numPoints; i++)
		scaledY[i] *= _scaleFactor;

	if (tmp)
		delete tmp;

	// possible memory leak
	return scaledY;
}

double XYFunctionInterface::getX(int aIndex) const
{
	switch (_functionType)
	{
		case typeConstant:
			return 0; //_constant->getX(aIndex);
	   case typeStepFunction:
			return 0; //_stepFunction->getX(aIndex);
		case typePiecewiseConstantFunction:
			return _mStepFunction->getX(aIndex);
		case typePiecewiseLinearFunction:
		   return _piecewiseLinearFunction->getX(aIndex);
	   case typeLinearFunction:
		   if (aIndex == 0)
				return -1.0;
			else if (aIndex == 1)
				return 1.0;
			else
				return 0.0;
		case typeNatCubicSpline:
		   return _natCubicSpline->getX(aIndex);
	   case typeGCVSpline:
		   return _gcvSpline->getX(aIndex);
		default:
			return 0.0;
	}
}

double XYFunctionInterface::getY(int aIndex) const
{
	switch (_functionType)
	{
		case typeConstant:
			return _constant->getValue() * _scaleFactor;
	   case typeStepFunction:
		   return SimTK::NaN;
	   case typePiecewiseConstantFunction:
		   return _mStepFunction->getY(aIndex) * _scaleFactor;
	   case typePiecewiseLinearFunction:
		   return _piecewiseLinearFunction->getY(aIndex) * _scaleFactor;
	   case typeLinearFunction:
		   if (aIndex == 0)
				return (_linearFunction->getCoefficients()[1] - _linearFunction->getCoefficients()[0]) * _scaleFactor;
			else if (aIndex == 1)
				return (_linearFunction->getCoefficients()[1] + _linearFunction->getCoefficients()[0]) * _scaleFactor;
			else
				return 0.0;
	    case typeNatCubicSpline:
		   return _natCubicSpline->getY(aIndex) * _scaleFactor;
	   case typeGCVSpline:
		   return _gcvSpline->getY(aIndex) * _scaleFactor;
		default:
			return 0.0;
	}
}

void XYFunctionInterface::setX(int aIndex, double aValue)
{
	switch (_functionType)
	{
		case typeConstant:
			break;
		case typePiecewiseConstantFunction:
		   _mStepFunction->setX(aIndex, aValue);
		   break;
	   case typePiecewiseLinearFunction:
		   _piecewiseLinearFunction->setX(aIndex, aValue);
		   break;
	   case typeLinearFunction:
		   break;
	    case typeNatCubicSpline:
		   _natCubicSpline->setX(aIndex, aValue);
		   break;
	   case typeGCVSpline:
		   _gcvSpline->setX(aIndex, aValue);
		   break;
		default:
			return;
	}
}

void XYFunctionInterface::setY(int aIndex, double aValue)
{
	aValue /= _scaleFactor;

	switch (_functionType)
	{
		case typeConstant:
			break;
	   case typePiecewiseConstantFunction:
		   _mStepFunction->setY(aIndex, aValue);
		   break;
	   case typePiecewiseLinearFunction:
		   _piecewiseLinearFunction->setY(aIndex, aValue);
		   break;
		case typeLinearFunction:
			break;
		case typeNatCubicSpline:
		   _natCubicSpline->setY(aIndex, aValue);
		   break;
	   case typeGCVSpline:
		   _gcvSpline->setY(aIndex, aValue);
		   break;
		default:
			return;
	}
}

bool XYFunctionInterface::deletePoint(int aIndex)
{
	switch (_functionType)
	{
		case typeConstant:
			return true;
	   case typeStepFunction:
		   return false;
	   case typePiecewiseConstantFunction:
		   return _mStepFunction->deletePoint(aIndex);
	   case typePiecewiseLinearFunction:
		   return _piecewiseLinearFunction->deletePoint(aIndex);
	   case typeLinearFunction:
		   return false;
		case typeNatCubicSpline:
		   return _natCubicSpline->deletePoint(aIndex);
	   case typeGCVSpline:
		   return _gcvSpline->deletePoint(aIndex);
		default:
			return true;
	}
}

bool XYFunctionInterface::deletePoints(const Array<int>& indices)
{
	switch (_functionType)
	{
		case typeConstant:
			return true;
	   case typeStepFunction:
		   return false;
	   case typePiecewiseConstantFunction:
		   return _mStepFunction->deletePoints(indices);
	   case typePiecewiseLinearFunction:
		   return _piecewiseLinearFunction->deletePoints(indices);
	   case typeLinearFunction:
		   return false;
		case typeNatCubicSpline:
		   return _natCubicSpline->deletePoints(indices);
	   case typeGCVSpline:
		   return _gcvSpline->deletePoints(indices);
		default:
			return true;
	}
}

int XYFunctionInterface::addPoint(double aX, double aY)
{
	aY /= _scaleFactor;

	switch (_functionType)
	{
		case typeConstant:
			return 1;
	   case typeStepFunction:
		   return 0;
	   case typePiecewiseConstantFunction:
		   return _mStepFunction->addPoint(aX, aY);
	   case typePiecewiseLinearFunction:
		   return _piecewiseLinearFunction->addPoint(aX, aY);
	   case typeLinearFunction:
		   return 0;
		case typeNatCubicSpline:
		   return _natCubicSpline->addPoint(aX, aY);
	   case typeGCVSpline:
		   return _gcvSpline->addPoint(aX, aY);
		default:
			return 1;
	}
}

Array<XYPoint>* XYFunctionInterface::renderAsLineSegments(int aIndex)
{
	if (_functionType == typeUndefined || _functionType == typeConstant ||
		_functionType == typeLinearFunction || aIndex < 0 || aIndex >= getNumberOfPoints() - 1)
		return NULL;

	Array<XYPoint>* xyPts = new Array<XYPoint>(XYPoint());
	const double* x = getXValues();
	const double* y = getYValues();

	if (_functionType == typeStepFunction)	{
		xyPts->append(XYPoint(x[aIndex], y[aIndex]));
		xyPts->append(XYPoint(x[aIndex+1], y[aIndex]));
		xyPts->append(XYPoint(x[aIndex+1], y[aIndex+1]));
	} else if (_functionType == typePiecewiseLinearFunction) {
		xyPts->append(XYPoint(x[aIndex], y[aIndex]));
		xyPts->append(XYPoint(x[aIndex+1], y[aIndex+1]));
	} else if (_functionType == typeNatCubicSpline) {
		// X sometimes goes slightly beyond the range due to roundoff error,
		// so do the last point separately.
		int numSegs = 20;
		for (int i=0; i<numSegs-1; i++) {
			double xValue = x[aIndex] + (double)i * (x[aIndex + 1] - x[aIndex]) / ((double)numSegs - 1.0);
			xyPts->append(XYPoint(xValue, _natCubicSpline->calcValue(SimTK::Vector(1,xValue)) * _scaleFactor));
		}
		xyPts->append(XYPoint(x[aIndex + 1], _natCubicSpline->calcValue(SimTK::Vector(1,x[aIndex+1])) * _scaleFactor));
	} else if (_functionType == typeGCVSpline) {
		// X sometimes goes slightly beyond the range due to roundoff error,
		// so do the last point separately.
		int numSegs = 20;
		for (int i=0; i<numSegs-1; i++) {
			double xValue = x[aIndex] + (double)i * (x[aIndex + 1] - x[aIndex]) / ((double)numSegs - 1.0);
			xyPts->append(XYPoint(xValue, _gcvSpline->calcValue(SimTK::Vector(1,xValue)) * _scaleFactor));
		}
		xyPts->append(XYPoint(x[aIndex + 1], _gcvSpline->calcValue(SimTK::Vector(1,x[aIndex + 1])) * _scaleFactor));
	}

	return xyPts;
}

}	// namespace
<commit_msg>Change display of PiecewiseConstantFunction in Excitation Editor to reflect actual interpretation by CMC.<commit_after>// XYFunctionInterface.cpp
// Authors: Peter Loan
/*
 * Copyright (c)  2009, Stanford University. All rights reserved.
* Use of the OpenSim software in source form is permitted provided that the following
* conditions are met:
* 	1. The software is used only for non-commercial research and education. It may not
*     be used in relation to any commercial activity.
* 	2. The software is not distributed or redistributed.  Software distribution is allowed
*     only through https://simtk.org/home/opensim.
* 	3. Use of the OpenSim software or derivatives must be acknowledged in all publications,
*      presentations, or documents describing work in which OpenSim or derivatives are used.
* 	4. Credits to developers may not be removed from executables
*     created from modifications of the source.
* 	5. Modifications of source code must retain the above copyright notice, this list of
*     conditions and the following disclaimer.
*
*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
*  EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
*  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
*  SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
*  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
*  TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
*  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
*  OR BUSINESS INTERRUPTION) OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
*  WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

//=============================================================================
// INCLUDES
//=============================================================================
#include "XYFunctionInterface.h"

namespace OpenSim {

bool XYFunctionInterface::isXYFunction(Function* f)
{
	Function* func = f;
	MultiplierFunction* mf = dynamic_cast<MultiplierFunction*>(f);
	if (mf)
		func = mf->getFunction();

	if (dynamic_cast<Constant*>(func) ||
		dynamic_cast<StepFunction*>(func) ||
		dynamic_cast<PiecewiseLinearFunction*>(func) ||
		dynamic_cast<LinearFunction*>(func) ||
		dynamic_cast<SimmSpline*>(func) ||
		dynamic_cast<GCVSpline*>(func)||
		dynamic_cast<PiecewiseConstantFunction*>(func))
		return true;

	return false;
}

XYFunctionInterface::XYFunctionInterface(Function* f) :
   _functionType(typeUndefined),
	_constant(0),
   _stepFunction(0),
   _linearFunction(0),
   _natCubicSpline(0),
   _gcvSpline(0),
   _mStepFunction(0)
{
	Function* func;
	MultiplierFunction* mf = dynamic_cast<MultiplierFunction*>(f);
	if (mf) {
		func = mf->getFunction();
		_scaleFactor = mf->getScale();
	} else {
		func = f;
		_scaleFactor = 1.0;
	}

	_constant = dynamic_cast<Constant*>(func);
	if (_constant) {
		_functionType = typeConstant;
		return;
	}
	_stepFunction = dynamic_cast<StepFunction*>(func);
	if (_stepFunction) {
		_functionType = typeStepFunction;
		return;
	}
	_mStepFunction = dynamic_cast<PiecewiseConstantFunction*>(func);
	if (_mStepFunction) {
		_functionType = typePiecewiseConstantFunction;
		return;
	}
	_piecewiseLinearFunction = dynamic_cast<PiecewiseLinearFunction*>(func);
	if (_piecewiseLinearFunction) {
		_functionType = typePiecewiseLinearFunction;
		return;
	}
	_linearFunction = dynamic_cast<LinearFunction*>(func);
	if (_linearFunction) {
		_functionType = typeLinearFunction;
		return;
	}
	_natCubicSpline = dynamic_cast<SimmSpline*>(func);
	if (_natCubicSpline) {
		_functionType = typeNatCubicSpline;
		return;
	}
	_gcvSpline = dynamic_cast<GCVSpline*>(func);
	if (_gcvSpline) {
		_functionType = typeGCVSpline;
		return;
	}

	throw Exception("Object " + getName() + " of type " +
        getConcreteClassName() + " is not an XYFunction.");
}

int XYFunctionInterface::getNumberOfPoints() const
{
	switch (_functionType)
	{
		case typeConstant:
			return 0;
	   case typePiecewiseConstantFunction:
			return _mStepFunction->getNumberOfPoints();
	   case typePiecewiseLinearFunction:
		   return _piecewiseLinearFunction->getNumberOfPoints();
	   case typeLinearFunction:
		   return 2;
	    case typeNatCubicSpline:
		   return _natCubicSpline->getNumberOfPoints();
	   case typeGCVSpline:
		   return _gcvSpline->getNumberOfPoints();
		default:
			return 0;
	}
}

const double* XYFunctionInterface::getXValues() const
{
	switch (_functionType)
	{
		case typeConstant:
			return NULL;
	   case typeStepFunction:
			return NULL;
	   case typePiecewiseConstantFunction:
		    return _mStepFunction->getXValues();
	   case typePiecewiseLinearFunction:
		   return _piecewiseLinearFunction->getXValues();
	   case typeLinearFunction:
			{
				double* xValues = new double[2];
				xValues[0] = -1.0;
				xValues[1] = 1.0;
				return xValues; // possible memory leak
			}
		case typeNatCubicSpline:
		   return _natCubicSpline->getXValues();
	   case typeGCVSpline:
		   return _gcvSpline->getXValues();
		default:
			return 0;
	}
}

const double* XYFunctionInterface::getYValues() const
{
	const double* yValues = NULL;
	double* tmp = NULL;
	int numPoints = getNumberOfPoints();

	switch (_functionType)
	{
		case typeConstant:
			return NULL;
	   case typeStepFunction:
			return NULL;;
			break;
	   case typePiecewiseConstantFunction:
			yValues = _mStepFunction->getYValues();
			break;
	   case typePiecewiseLinearFunction:
		   yValues = _piecewiseLinearFunction->getYValues();
			break;
	   case typeLinearFunction:
		   tmp = new double[2];
			tmp[0] = _linearFunction->getCoefficients()[1] - _linearFunction->getCoefficients()[0];
			tmp[1] = _linearFunction->getCoefficients()[1] + _linearFunction->getCoefficients()[0];
			break;
	    case typeNatCubicSpline:
		   yValues = _natCubicSpline->getYValues();
			break;
	   case typeGCVSpline:
		   yValues = _gcvSpline->getYValues();
			break;
		default:
			return NULL;
	}

	double* scaledY = new double[numPoints];
	memcpy(scaledY, yValues, numPoints*sizeof(double));
	for (int i=0; i<numPoints; i++)
		scaledY[i] *= _scaleFactor;

	if (tmp)
		delete tmp;

	// possible memory leak
	return scaledY;
}

double XYFunctionInterface::getX(int aIndex) const
{
	switch (_functionType)
	{
		case typeConstant:
			return 0; //_constant->getX(aIndex);
	   case typeStepFunction:
			return 0; //_stepFunction->getX(aIndex);
		case typePiecewiseConstantFunction:
			return _mStepFunction->getX(aIndex);
		case typePiecewiseLinearFunction:
		   return _piecewiseLinearFunction->getX(aIndex);
	   case typeLinearFunction:
		   if (aIndex == 0)
				return -1.0;
			else if (aIndex == 1)
				return 1.0;
			else
				return 0.0;
		case typeNatCubicSpline:
		   return _natCubicSpline->getX(aIndex);
	   case typeGCVSpline:
		   return _gcvSpline->getX(aIndex);
		default:
			return 0.0;
	}
}

double XYFunctionInterface::getY(int aIndex) const
{
	switch (_functionType)
	{
		case typeConstant:
			return _constant->getValue() * _scaleFactor;
	   case typeStepFunction:
		   return SimTK::NaN;
	   case typePiecewiseConstantFunction:
		   return _mStepFunction->getY(aIndex) * _scaleFactor;
	   case typePiecewiseLinearFunction:
		   return _piecewiseLinearFunction->getY(aIndex) * _scaleFactor;
	   case typeLinearFunction:
		   if (aIndex == 0)
				return (_linearFunction->getCoefficients()[1] - _linearFunction->getCoefficients()[0]) * _scaleFactor;
			else if (aIndex == 1)
				return (_linearFunction->getCoefficients()[1] + _linearFunction->getCoefficients()[0]) * _scaleFactor;
			else
				return 0.0;
	    case typeNatCubicSpline:
		   return _natCubicSpline->getY(aIndex) * _scaleFactor;
	   case typeGCVSpline:
		   return _gcvSpline->getY(aIndex) * _scaleFactor;
		default:
			return 0.0;
	}
}

void XYFunctionInterface::setX(int aIndex, double aValue)
{
	switch (_functionType)
	{
		case typeConstant:
			break;
		case typePiecewiseConstantFunction:
		   _mStepFunction->setX(aIndex, aValue);
		   break;
	   case typePiecewiseLinearFunction:
		   _piecewiseLinearFunction->setX(aIndex, aValue);
		   break;
	   case typeLinearFunction:
		   break;
	    case typeNatCubicSpline:
		   _natCubicSpline->setX(aIndex, aValue);
		   break;
	   case typeGCVSpline:
		   _gcvSpline->setX(aIndex, aValue);
		   break;
		default:
			return;
	}
}

void XYFunctionInterface::setY(int aIndex, double aValue)
{
	aValue /= _scaleFactor;

	switch (_functionType)
	{
		case typeConstant:
			break;
	   case typePiecewiseConstantFunction:
		   _mStepFunction->setY(aIndex, aValue);
		   break;
	   case typePiecewiseLinearFunction:
		   _piecewiseLinearFunction->setY(aIndex, aValue);
		   break;
		case typeLinearFunction:
			break;
		case typeNatCubicSpline:
		   _natCubicSpline->setY(aIndex, aValue);
		   break;
	   case typeGCVSpline:
		   _gcvSpline->setY(aIndex, aValue);
		   break;
		default:
			return;
	}
}

bool XYFunctionInterface::deletePoint(int aIndex)
{
	switch (_functionType)
	{
		case typeConstant:
			return true;
	   case typeStepFunction:
		   return false;
	   case typePiecewiseConstantFunction:
		   return _mStepFunction->deletePoint(aIndex);
	   case typePiecewiseLinearFunction:
		   return _piecewiseLinearFunction->deletePoint(aIndex);
	   case typeLinearFunction:
		   return false;
		case typeNatCubicSpline:
		   return _natCubicSpline->deletePoint(aIndex);
	   case typeGCVSpline:
		   return _gcvSpline->deletePoint(aIndex);
		default:
			return true;
	}
}

bool XYFunctionInterface::deletePoints(const Array<int>& indices)
{
	switch (_functionType)
	{
		case typeConstant:
			return true;
	   case typeStepFunction:
		   return false;
	   case typePiecewiseConstantFunction:
		   return _mStepFunction->deletePoints(indices);
	   case typePiecewiseLinearFunction:
		   return _piecewiseLinearFunction->deletePoints(indices);
	   case typeLinearFunction:
		   return false;
		case typeNatCubicSpline:
		   return _natCubicSpline->deletePoints(indices);
	   case typeGCVSpline:
		   return _gcvSpline->deletePoints(indices);
		default:
			return true;
	}
}

int XYFunctionInterface::addPoint(double aX, double aY)
{
	aY /= _scaleFactor;

	switch (_functionType)
	{
		case typeConstant:
			return 1;
	   case typeStepFunction:
		   return 0;
	   case typePiecewiseConstantFunction:
		   return _mStepFunction->addPoint(aX, aY);
	   case typePiecewiseLinearFunction:
		   return _piecewiseLinearFunction->addPoint(aX, aY);
	   case typeLinearFunction:
		   return 0;
		case typeNatCubicSpline:
		   return _natCubicSpline->addPoint(aX, aY);
	   case typeGCVSpline:
		   return _gcvSpline->addPoint(aX, aY);
		default:
			return 1;
	}
}

Array<XYPoint>* XYFunctionInterface::renderAsLineSegments(int aIndex)
{
	if (_functionType == typeUndefined || _functionType == typeConstant ||
		_functionType == typeLinearFunction || aIndex < 0 || aIndex >= getNumberOfPoints() - 1)
		return NULL;

	Array<XYPoint>* xyPts = new Array<XYPoint>(XYPoint());
	const double* x = getXValues();
	const double* y = getYValues();

	if (_functionType == typeStepFunction)	{
		xyPts->append(XYPoint(x[aIndex], y[aIndex]));
		xyPts->append(XYPoint(x[aIndex+1], y[aIndex]));
		xyPts->append(XYPoint(x[aIndex+1], y[aIndex+1]));
	} else if (_functionType == typePiecewiseLinearFunction) {
		xyPts->append(XYPoint(x[aIndex], y[aIndex]));
		xyPts->append(XYPoint(x[aIndex+1], y[aIndex+1]));
	} else if (_functionType == typeNatCubicSpline) {
		// X sometimes goes slightly beyond the range due to roundoff error,
		// so do the last point separately.
		int numSegs = 20;
		for (int i=0; i<numSegs-1; i++) {
			double xValue = x[aIndex] + (double)i * (x[aIndex + 1] - x[aIndex]) / ((double)numSegs - 1.0);
			xyPts->append(XYPoint(xValue, _natCubicSpline->calcValue(SimTK::Vector(1,xValue)) * _scaleFactor));
		}
		xyPts->append(XYPoint(x[aIndex + 1], _natCubicSpline->calcValue(SimTK::Vector(1,x[aIndex+1])) * _scaleFactor));
	} else if (_functionType == typeGCVSpline) {
		// X sometimes goes slightly beyond the range due to roundoff error,
		// so do the last point separately.
		int numSegs = 20;
		for (int i=0; i<numSegs-1; i++) {
			double xValue = x[aIndex] + (double)i * (x[aIndex + 1] - x[aIndex]) / ((double)numSegs - 1.0);
			xyPts->append(XYPoint(xValue, _gcvSpline->calcValue(SimTK::Vector(1,xValue)) * _scaleFactor));
		}
		xyPts->append(XYPoint(x[aIndex + 1], _gcvSpline->calcValue(SimTK::Vector(1,x[aIndex + 1])) * _scaleFactor));
	} else if (_functionType == typePiecewiseConstantFunction)	{
		xyPts->append(XYPoint(x[aIndex], y[aIndex]));
		xyPts->append(XYPoint(x[aIndex], y[aIndex+1]));
		xyPts->append(XYPoint(x[aIndex+1], y[aIndex+1]));
	}

	return xyPts;
}

}	// namespace
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/
/*=========================================================================
 *
 *  Portions of this file are subject to the VTK Toolkit Version 3 copyright.
 *
 *  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
 *
 *  For complete copyright, license and disclaimer of warranty information
 *  please refer to the NOTICE file at the top of the ITK source tree.
 *
 *=========================================================================*/
#ifndef itkBSplineDecompositionImageFilter_hxx
#define itkBSplineDecompositionImageFilter_hxx
#include "itkBSplineDecompositionImageFilter.h"
#include "itkImageRegionConstIteratorWithIndex.h"
#include "itkImageRegionIterator.h"
#include "itkProgressReporter.h"
#include "itkVector.h"

namespace itk
{

template< typename TInputImage, typename TOutputImage >
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::BSplineDecompositionImageFilter()

{
  this->SetSplineOrder( 3 );

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

  m_DataLength.Fill( itk::NumericTraits< typename TInputImage::SizeType::SizeValueType >::ZeroValue() );
}

template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::PrintSelf( std::ostream & os, Indent indent) const
{
  Superclass::PrintSelf(os, indent);

  os << indent << "Scratch: " << std::endl;
  for( unsigned int i = 0; i < m_Scratch.size(); ++i )
    {
    os << indent << "[" << i << "]: " << m_Scratch[i] << std::endl;
    }
  os << indent << "Data Length: " << m_DataLength << std::endl;
  os << indent << "Spline Order: " << m_SplineOrder << std::endl;
  os << indent << "SplinePoles: " << std::endl;
  for( unsigned int i = 0; i < m_SplinePoles.size(); ++i )
    {
    os << indent << "[" << i << "]" << m_SplinePoles[i] << std::endl;
    }
  os << indent << "Number Of Poles: " << m_NumberOfPoles << std::endl;
  os << indent << "Tolerance: " << m_Tolerance << std::endl;
  os << indent << "Iterator Direction: " << m_IteratorDirection << std::endl;
}

template< typename TInputImage, typename TOutputImage >
bool
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::DataToCoefficients1D()
{
  // See Unser, 1993, Part II, Equation 2.5,
  // or Unser, 1999, Box 2. for an explanation.

  double c0 = 1.0;

  if ( m_DataLength[m_IteratorDirection] == 1 ) // Required by mirror boundaries
    {
    return false;
    }

  // Compute over all gain
  for ( int k = 0; k < m_NumberOfPoles; k++ )
    {
    // Note for cubic splines lambda = 6
    c0 = c0 * ( 1.0 - m_SplinePoles[k] ) * ( 1.0 - 1.0 / m_SplinePoles[k] );
    }

  // Apply the gain
  for ( unsigned int n = 0; n < m_DataLength[m_IteratorDirection]; n++ )
    {
    m_Scratch[n] *= c0;
    }

  // Loop over all poles
  for ( int k = 0; k < m_NumberOfPoles; k++ )
    {
    // Causal initialization
    this->SetInitialCausalCoefficient(m_SplinePoles[k]);
    // Causal recursion
    for ( unsigned int n = 1; n < m_DataLength[m_IteratorDirection]; n++ )
      {
      m_Scratch[n] += m_SplinePoles[k] * m_Scratch[n - 1];
      }

    // anticausal initialization
    this->SetInitialAntiCausalCoefficient(m_SplinePoles[k]);
    // anticausal recursion
    for ( int n = m_DataLength[m_IteratorDirection] - 2; 0 <= n; n-- )
      {
      m_Scratch[n] = m_SplinePoles[k] * ( m_Scratch[n + 1] - m_Scratch[n] );
      }
    }
  return true;
}

template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::SetSplineOrder(unsigned int SplineOrder)
{
  if ( SplineOrder == m_SplineOrder )
    {
    return;
    }
  m_SplinePoles.clear();
  m_SplineOrder = SplineOrder;
  this->SetPoles();
  this->Modified();
}

template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::SetPoles()
{
  // See Unser, 1997. Part II, Table I for Pole values.
  // See also, Handbook of Medical Imaging, Processing and Analysis, Ed. Isaac
  // N. Bankman, 2000, pg. 416.
  switch ( m_SplineOrder )
    {
    case 3:
      m_NumberOfPoles = 1;
      m_SplinePoles.resize( m_NumberOfPoles );
      m_SplinePoles.at( 0 ) = std::sqrt(3.0) - 2.0;
      break;
    case 0:
      m_NumberOfPoles = 0;
      break;
    case 1:
      m_NumberOfPoles = 0;
      break;
    case 2:
      m_NumberOfPoles = 1;
      m_SplinePoles.resize( m_NumberOfPoles );
      m_SplinePoles.at( 0 ) = std::sqrt(8.0) - 3.0;
      break;
    case 4:
      m_NumberOfPoles = 2;
      m_SplinePoles.resize( m_NumberOfPoles );
      m_SplinePoles.at( 0 ) = std::sqrt( 664.0 - std::sqrt(438976.0) ) + std::sqrt(304.0) - 19.0;
      m_SplinePoles.at( 1 ) = std::sqrt( 664.0 + std::sqrt(438976.0) ) - std::sqrt(304.0) - 19.0;
      break;
    case 5:
      m_NumberOfPoles = 2;
      m_SplinePoles.resize( m_NumberOfPoles );
      m_SplinePoles.at( 0 ) = std::sqrt( 135.0 / 2.0 - std::sqrt(17745.0 / 4.0) ) + std::sqrt(105.0 / 4.0)
                         - 13.0 / 2.0;
      m_SplinePoles.at( 1 ) = std::sqrt( 135.0 / 2.0 + std::sqrt(17745.0 / 4.0) ) - std::sqrt(105.0 / 4.0)
                         - 13.0 / 2.0;
      break;
    default:
      // SplineOrder not implemented yet.
      itkExceptionMacro(<< "SplineOrder must be between 0 and 5. Requested spline order has not been implemented yet.");
      break;
    }
}

template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::SetInitialCausalCoefficient(double z)
{
  // See Unser, 1999, Box 2 for explanation
  CoeffType     sum;
  double        zn, z2n, iz;
  typename TInputImage::SizeValueType horizon;

  // Yhis initialization corresponds to mirror boundaries
  horizon = m_DataLength[m_IteratorDirection];
  zn = z;
  if ( m_Tolerance > 0.0 )
    {
    horizon = (typename TInputImage::SizeValueType)
      std::ceil( std::log(m_Tolerance) / std::log( std::fabs(z) ) );
    }
  if ( horizon < m_DataLength[m_IteratorDirection] )
    {
    // Accelerated loop
    sum = m_Scratch[0];   // verify this
    for ( unsigned int n = 1; n < horizon; n++ )
      {
      sum += zn * m_Scratch[n];
      zn *= z;
      }
    m_Scratch[0] = sum;
    }
  else
    {
    // Full loop
    iz = 1.0 / z;
    z2n = std::pow( z, (double)( m_DataLength[m_IteratorDirection] - 1L ) );
    sum = m_Scratch[0] + z2n * m_Scratch[m_DataLength[m_IteratorDirection] - 1L];
    z2n *= z2n * iz;
    for ( unsigned int n = 1; n <= ( m_DataLength[m_IteratorDirection] - 2 ); n++ )
      {
      sum += ( zn + z2n ) * m_Scratch[n];
      zn *= z;
      z2n *= iz;
      }
    m_Scratch[0] = sum / ( 1.0 - zn * zn );
    }
}

template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::SetInitialAntiCausalCoefficient(double z)
{
  // This initialization corresponds to mirror boundaries.
  // See Unser, 1999, Box 2 for explanation.
  // Also see erratum at http://bigwww.epfl.ch/publications/unser9902.html
  m_Scratch[m_DataLength[m_IteratorDirection] - 1] =
    ( z / ( z * z - 1.0 ) )
    * ( z * m_Scratch[m_DataLength[m_IteratorDirection] - 2] + m_Scratch[m_DataLength[m_IteratorDirection] - 1] );
}

template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::DataToCoefficientsND()
{
  OutputImagePointer output = this->GetOutput();

  Size< ImageDimension > size = output->GetBufferedRegion().GetSize();

  unsigned int count = output->GetBufferedRegion().GetNumberOfPixels() / size[0] * ImageDimension;

  ProgressReporter progress(this, 0, count, 10);

  // Initialize coeffient array
  this->CopyImageToImage();   // Coefficients are initialized to the input data

  // Loop through each dimension
  for ( unsigned int n = 0; n < ImageDimension; n++ )
    {
    m_IteratorDirection = n;

    // Initialize iterators
    OutputLinearIterator CIterator( output, output->GetBufferedRegion() );
    CIterator.SetDirection(m_IteratorDirection);
    // For each data vector
    while ( !CIterator.IsAtEnd() )
      {
      // Copy coefficients to scratch
      this->CopyCoefficientsToScratch(CIterator);

      // Perform 1D BSpline calculations
      this->DataToCoefficients1D();

      // Copy scratch back to coefficients.
      // Brings us back to the end of the line we were working on.
      CIterator.GoToBeginOfLine();
      this->CopyScratchToCoefficients(CIterator);   // m_Scratch = m_Image;
      CIterator.NextLine();
      progress.CompletedPixel();
      }
    }
}

template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::CopyImageToImage()
{
  using InputIterator = ImageRegionConstIteratorWithIndex< TInputImage >;
  using OutputIterator = ImageRegionIterator< TOutputImage >;
  using OutputPixelType = typename TOutputImage::PixelType;

  InputIterator  inIt( this->GetInput(), this->GetInput()->GetBufferedRegion() );
  OutputIterator outIt( this->GetOutput(), this->GetOutput()->GetBufferedRegion() );

  inIt.GoToBegin();
  outIt.GoToBegin();

  while ( !outIt.IsAtEnd() )
    {
    outIt.Set( static_cast< OutputPixelType >( inIt.Get() ) );
    ++inIt;
    ++outIt;
    }
}

template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::CopyScratchToCoefficients(OutputLinearIterator & Iter)
{
  using OutputPixelType = typename TOutputImage::PixelType;
  typename TOutputImage::SizeValueType j = 0;
  while ( !Iter.IsAtEndOfLine() )
    {
    Iter.Set( static_cast< OutputPixelType >( m_Scratch[j] ) );
    ++Iter;
    ++j;
    }
}

/**
 */
template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::CopyCoefficientsToScratch(OutputLinearIterator & Iter)
{
  typename TOutputImage::SizeValueType j = 0;

  while ( !Iter.IsAtEndOfLine() )
    {
    m_Scratch[j] = static_cast< CoeffType >( Iter.Get() );
    ++Iter;
    ++j;
    }
}

template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::GenerateInputRequestedRegion()
{
  // This filter requires all of the input image to be in the buffer
  InputImagePointer inputPtr = const_cast< TInputImage * >( this->GetInput() );

  if ( inputPtr )
    {
    inputPtr->SetRequestedRegionToLargestPossibleRegion();
    }
}

template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::EnlargeOutputRequestedRegion(DataObject *output)
{
  // This filter requires all of the input image to be in the buffer
  TOutputImage *imgData;

  imgData = dynamic_cast< TOutputImage * >( output );
  if ( imgData )
    {
    imgData->SetRequestedRegionToLargestPossibleRegion();
    }
}

template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::GenerateData()
{
  // Allocate scratch memory
  InputImageConstPointer inputPtr = this->GetInput();

  m_DataLength = inputPtr->GetBufferedRegion().GetSize();

  typename TOutputImage::SizeValueType maxLength = 0;
  for ( unsigned int n = 0; n < ImageDimension; n++ )
    {
    if ( m_DataLength[n] > maxLength )
      {
      maxLength = m_DataLength[n];
      }
    }
  m_Scratch.resize(maxLength);

  // Allocate memory for output image
  OutputImagePointer outputPtr = this->GetOutput();
  outputPtr->SetBufferedRegion( outputPtr->GetRequestedRegion() );
  outputPtr->Allocate();

  // Calculate actual output
  this->DataToCoefficientsND();

  // Clean up
  m_Scratch.clear();
}
} // namespace itk

#endif
<commit_msg>PERF: BSplineDecompositionImageFilter now calls ImageAlgorithm::Copy<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/
/*=========================================================================
 *
 *  Portions of this file are subject to the VTK Toolkit Version 3 copyright.
 *
 *  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
 *
 *  For complete copyright, license and disclaimer of warranty information
 *  please refer to the NOTICE file at the top of the ITK source tree.
 *
 *=========================================================================*/
#ifndef itkBSplineDecompositionImageFilter_hxx
#define itkBSplineDecompositionImageFilter_hxx
#include "itkBSplineDecompositionImageFilter.h"
#include "itkImageAlgorithm.h"
#include "itkProgressReporter.h"
#include "itkVector.h"

namespace itk
{

template< typename TInputImage, typename TOutputImage >
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::BSplineDecompositionImageFilter()

{
  this->SetSplineOrder( 3 );

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

  m_DataLength.Fill( itk::NumericTraits< typename TInputImage::SizeType::SizeValueType >::ZeroValue() );
}

template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::PrintSelf( std::ostream & os, Indent indent) const
{
  Superclass::PrintSelf(os, indent);

  os << indent << "Scratch: " << std::endl;
  for( unsigned int i = 0; i < m_Scratch.size(); ++i )
    {
    os << indent << "[" << i << "]: " << m_Scratch[i] << std::endl;
    }
  os << indent << "Data Length: " << m_DataLength << std::endl;
  os << indent << "Spline Order: " << m_SplineOrder << std::endl;
  os << indent << "SplinePoles: " << std::endl;
  for( unsigned int i = 0; i < m_SplinePoles.size(); ++i )
    {
    os << indent << "[" << i << "]" << m_SplinePoles[i] << std::endl;
    }
  os << indent << "Number Of Poles: " << m_NumberOfPoles << std::endl;
  os << indent << "Tolerance: " << m_Tolerance << std::endl;
  os << indent << "Iterator Direction: " << m_IteratorDirection << std::endl;
}

template< typename TInputImage, typename TOutputImage >
bool
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::DataToCoefficients1D()
{
  // See Unser, 1993, Part II, Equation 2.5,
  // or Unser, 1999, Box 2. for an explanation.

  double c0 = 1.0;

  if ( m_DataLength[m_IteratorDirection] == 1 ) // Required by mirror boundaries
    {
    return false;
    }

  // Compute over all gain
  for ( int k = 0; k < m_NumberOfPoles; k++ )
    {
    // Note for cubic splines lambda = 6
    c0 = c0 * ( 1.0 - m_SplinePoles[k] ) * ( 1.0 - 1.0 / m_SplinePoles[k] );
    }

  // Apply the gain
  for ( unsigned int n = 0; n < m_DataLength[m_IteratorDirection]; n++ )
    {
    m_Scratch[n] *= c0;
    }

  // Loop over all poles
  for ( int k = 0; k < m_NumberOfPoles; k++ )
    {
    // Causal initialization
    this->SetInitialCausalCoefficient(m_SplinePoles[k]);
    // Causal recursion
    for ( unsigned int n = 1; n < m_DataLength[m_IteratorDirection]; n++ )
      {
      m_Scratch[n] += m_SplinePoles[k] * m_Scratch[n - 1];
      }

    // anticausal initialization
    this->SetInitialAntiCausalCoefficient(m_SplinePoles[k]);
    // anticausal recursion
    for ( int n = m_DataLength[m_IteratorDirection] - 2; 0 <= n; n-- )
      {
      m_Scratch[n] = m_SplinePoles[k] * ( m_Scratch[n + 1] - m_Scratch[n] );
      }
    }
  return true;
}

template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::SetSplineOrder(unsigned int SplineOrder)
{
  if ( SplineOrder == m_SplineOrder )
    {
    return;
    }
  m_SplinePoles.clear();
  m_SplineOrder = SplineOrder;
  this->SetPoles();
  this->Modified();
}

template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::SetPoles()
{
  // See Unser, 1997. Part II, Table I for Pole values.
  // See also, Handbook of Medical Imaging, Processing and Analysis, Ed. Isaac
  // N. Bankman, 2000, pg. 416.
  switch ( m_SplineOrder )
    {
    case 3:
      m_NumberOfPoles = 1;
      m_SplinePoles.resize( m_NumberOfPoles );
      m_SplinePoles.at( 0 ) = std::sqrt(3.0) - 2.0;
      break;
    case 0:
      m_NumberOfPoles = 0;
      break;
    case 1:
      m_NumberOfPoles = 0;
      break;
    case 2:
      m_NumberOfPoles = 1;
      m_SplinePoles.resize( m_NumberOfPoles );
      m_SplinePoles.at( 0 ) = std::sqrt(8.0) - 3.0;
      break;
    case 4:
      m_NumberOfPoles = 2;
      m_SplinePoles.resize( m_NumberOfPoles );
      m_SplinePoles.at( 0 ) = std::sqrt( 664.0 - std::sqrt(438976.0) ) + std::sqrt(304.0) - 19.0;
      m_SplinePoles.at( 1 ) = std::sqrt( 664.0 + std::sqrt(438976.0) ) - std::sqrt(304.0) - 19.0;
      break;
    case 5:
      m_NumberOfPoles = 2;
      m_SplinePoles.resize( m_NumberOfPoles );
      m_SplinePoles.at( 0 ) = std::sqrt( 135.0 / 2.0 - std::sqrt(17745.0 / 4.0) ) + std::sqrt(105.0 / 4.0)
                         - 13.0 / 2.0;
      m_SplinePoles.at( 1 ) = std::sqrt( 135.0 / 2.0 + std::sqrt(17745.0 / 4.0) ) - std::sqrt(105.0 / 4.0)
                         - 13.0 / 2.0;
      break;
    default:
      // SplineOrder not implemented yet.
      itkExceptionMacro(<< "SplineOrder must be between 0 and 5. Requested spline order has not been implemented yet.");
      break;
    }
}

template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::SetInitialCausalCoefficient(double z)
{
  // See Unser, 1999, Box 2 for explanation
  CoeffType     sum;
  double        zn, z2n, iz;
  typename TInputImage::SizeValueType horizon;

  // Yhis initialization corresponds to mirror boundaries
  horizon = m_DataLength[m_IteratorDirection];
  zn = z;
  if ( m_Tolerance > 0.0 )
    {
    horizon = (typename TInputImage::SizeValueType)
      std::ceil( std::log(m_Tolerance) / std::log( std::fabs(z) ) );
    }
  if ( horizon < m_DataLength[m_IteratorDirection] )
    {
    // Accelerated loop
    sum = m_Scratch[0];   // verify this
    for ( unsigned int n = 1; n < horizon; n++ )
      {
      sum += zn * m_Scratch[n];
      zn *= z;
      }
    m_Scratch[0] = sum;
    }
  else
    {
    // Full loop
    iz = 1.0 / z;
    z2n = std::pow( z, (double)( m_DataLength[m_IteratorDirection] - 1L ) );
    sum = m_Scratch[0] + z2n * m_Scratch[m_DataLength[m_IteratorDirection] - 1L];
    z2n *= z2n * iz;
    for ( unsigned int n = 1; n <= ( m_DataLength[m_IteratorDirection] - 2 ); n++ )
      {
      sum += ( zn + z2n ) * m_Scratch[n];
      zn *= z;
      z2n *= iz;
      }
    m_Scratch[0] = sum / ( 1.0 - zn * zn );
    }
}

template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::SetInitialAntiCausalCoefficient(double z)
{
  // This initialization corresponds to mirror boundaries.
  // See Unser, 1999, Box 2 for explanation.
  // Also see erratum at http://bigwww.epfl.ch/publications/unser9902.html
  m_Scratch[m_DataLength[m_IteratorDirection] - 1] =
    ( z / ( z * z - 1.0 ) )
    * ( z * m_Scratch[m_DataLength[m_IteratorDirection] - 2] + m_Scratch[m_DataLength[m_IteratorDirection] - 1] );
}

template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::DataToCoefficientsND()
{
  OutputImagePointer output = this->GetOutput();

  Size< ImageDimension > size = output->GetBufferedRegion().GetSize();

  unsigned int count = output->GetBufferedRegion().GetNumberOfPixels() / size[0] * ImageDimension;

  ProgressReporter progress(this, 0, count, 10);

  // Initialize coeffient array
  this->CopyImageToImage();   // Coefficients are initialized to the input data

  // Loop through each dimension
  for ( unsigned int n = 0; n < ImageDimension; n++ )
    {
    m_IteratorDirection = n;

    // Initialize iterators
    OutputLinearIterator CIterator( output, output->GetBufferedRegion() );
    CIterator.SetDirection(m_IteratorDirection);
    // For each data vector
    while ( !CIterator.IsAtEnd() )
      {
      // Copy coefficients to scratch
      this->CopyCoefficientsToScratch(CIterator);

      // Perform 1D BSpline calculations
      this->DataToCoefficients1D();

      // Copy scratch back to coefficients.
      // Brings us back to the end of the line we were working on.
      CIterator.GoToBeginOfLine();
      this->CopyScratchToCoefficients(CIterator);   // m_Scratch = m_Image;
      CIterator.NextLine();
      progress.CompletedPixel();
      }
    }
}

template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::CopyImageToImage()
{
  const TInputImage* const inputImage = this->GetInput();
  TOutputImage* const outputImage = this->GetOutput();
  ImageAlgorithm::Copy(inputImage, outputImage,
    inputImage->GetBufferedRegion(), outputImage->GetBufferedRegion());
}

template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::CopyScratchToCoefficients(OutputLinearIterator & Iter)
{
  using OutputPixelType = typename TOutputImage::PixelType;
  typename TOutputImage::SizeValueType j = 0;
  while ( !Iter.IsAtEndOfLine() )
    {
    Iter.Set( static_cast< OutputPixelType >( m_Scratch[j] ) );
    ++Iter;
    ++j;
    }
}

/**
 */
template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::CopyCoefficientsToScratch(OutputLinearIterator & Iter)
{
  typename TOutputImage::SizeValueType j = 0;

  while ( !Iter.IsAtEndOfLine() )
    {
    m_Scratch[j] = static_cast< CoeffType >( Iter.Get() );
    ++Iter;
    ++j;
    }
}

template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::GenerateInputRequestedRegion()
{
  // This filter requires all of the input image to be in the buffer
  InputImagePointer inputPtr = const_cast< TInputImage * >( this->GetInput() );

  if ( inputPtr )
    {
    inputPtr->SetRequestedRegionToLargestPossibleRegion();
    }
}

template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::EnlargeOutputRequestedRegion(DataObject *output)
{
  // This filter requires all of the input image to be in the buffer
  TOutputImage *imgData;

  imgData = dynamic_cast< TOutputImage * >( output );
  if ( imgData )
    {
    imgData->SetRequestedRegionToLargestPossibleRegion();
    }
}

template< typename TInputImage, typename TOutputImage >
void
BSplineDecompositionImageFilter< TInputImage, TOutputImage >
::GenerateData()
{
  // Allocate scratch memory
  InputImageConstPointer inputPtr = this->GetInput();

  m_DataLength = inputPtr->GetBufferedRegion().GetSize();

  typename TOutputImage::SizeValueType maxLength = 0;
  for ( unsigned int n = 0; n < ImageDimension; n++ )
    {
    if ( m_DataLength[n] > maxLength )
      {
      maxLength = m_DataLength[n];
      }
    }
  m_Scratch.resize(maxLength);

  // Allocate memory for output image
  OutputImagePointer outputPtr = this->GetOutput();
  outputPtr->SetBufferedRegion( outputPtr->GetRequestedRegion() );
  outputPtr->Allocate();

  // Calculate actual output
  this->DataToCoefficientsND();

  // Clean up
  m_Scratch.clear();
}
} // namespace itk

#endif
<|endoftext|>


<commit_before>/**
 * @author Mike Bogochow
 * @version 2.4.0, Dec 8, 2015
 *
 * @file Auctioneer.cpp
 *
 * Auctioneer class implementation
 */

#include "Auctioneer.h"
#include "../lib_auction/AuctionDefs.h"
#include "../lib_auction/DebugPrinter.h"

#include "MBUtils.h"

#include <boost/algorithm/string/predicate.hpp> // starts_with
#include <chrono>
#include <thread>

Auctioneer::Auctioneer(void)
{
  numBidders = 0;
  numTargets = 0;

  roundNumber = 0;
  numRecvdBids = 0;
  bids = nullptr;
}

Auctioneer::~Auctioneer(void)
{
  if (bids != nullptr)
    delete bids;
}

bool
Auctioneer::OnNewMail(MOOSMSG_LIST &NewMail)
{
  bool ret = AuctionMOOSApp::OnNewMail(NewMail);

  MOOSMSG_LIST::reverse_iterator p;
  for(p = NewMail.rbegin(); p != NewMail.rend(); p++)
  {
    CMOOSMsg &msg = *p;
    std::string key   = msg.GetKey();

    if (boost::starts_with(key, MVAR_BID_HEADER))
    {
      int bidder = getBidder(key);
      bids[bidder] = bidFromString(msg.GetString());
      numRecvdBids += 1;
      dp.dprintf(LVL_MIN_VERB, "Got %s mail: %s\n", key.c_str(),
          msg.GetString().c_str());
    }
  }

  return ret;
}

bool
Auctioneer::Iterate(void)
{
  bool ret = AuctionMOOSApp::Iterate();

  dp.dprintf(LVL_MAX_VERB, "roundNum <= numNodes (%lu <= %lu)?\n", roundNumber, numTargets);
  if (roundNumber <= numTargets)
  {
    dp.dprintf(LVL_MID_VERB, "numReceivedBids=%i\n", numRecvdBids);

    if (roundNumber == 0)
      doNotify(MVAR_BID_START, ++roundNumber);
    else if (numRecvdBids == numBidders)
    { // All bids received for round
      WinningBid winner = { 0, MAX_VERTEX, MAX_WEIGHT };
      // Calculate winner
      for (size_t i = 0; i < numBidders; i++)
      {
        if (bids[i].second < winner.bid)
        {
          winner.winner = i;
          winner.target = bids[i].first;
          winner.bid = bids[i].second;
        }
      }

      // Send winner
      doNotify(MVAR_BID_WINNER, winningBidToString(winner));
      doNotify(MVAR_BID_START, ++roundNumber);

      numRecvdBids = 0;
    }
    else
    { // Keep sending the round number in case they didn't get the message.
      doNotify(MVAR_BID_START, roundNumber);
      if (roundNumber == 1)
        doNotify(MVAR_BID_TARGETS, targets);
    }
  }
  else
  {
    // Exit pAuctioneer
    doNotify("EXITED_NORMALLY", "pAuctioneer");
    RequestQuit();
  }

  return ret;
}

bool
Auctioneer::OnStartUp(void)
{
  bool ret;

  // DebugOutput config
  int debugLevel;
  if (!m_MissionReader.GetConfigurationParam("DebugOutput", debugLevel))
    debugLevel = LVL_OFF;
  dp.setLevel((DebugLevel)debugLevel);

  ret = AuctionMOOSApp::OnStartUp();

  if (ret)
  {
    // NumBidders config
    std::string tmp;
    if (!m_MissionReader.GetConfigurationParam("NumBidders", tmp))
      ret = MissingRequiredParam("NumBidders");
    else
    {
      numBidders = boost::lexical_cast<size_t>(tmp);
      this->bids = new Bid[numBidders];
    }

    if (ret)
    {
      // Targets config
      if (!m_MissionReader.GetConfigurationParam("Targets", targets))
        ret = MissingRequiredParam("Targets");
      else
      {
        numTargets = getStringPathSize(targets);
        numTargets += 1; // for the bidder's node
        doNotify(MVAR_BID_TARGETS, targets);
      }

      if (ret)
        RegisterVariables();
    }
  }

  return ret;
}

bool
Auctioneer::OnConnectToServer(void)
{
  bool ret = AuctionMOOSApp::OnConnectToServer();
  RegisterVariables();
  return ret;
}

void
Auctioneer::RegisterVariables(void)
{
  for (size_t i = 0; i < numBidders; i++)
  {
    std::string key = getBidVar(i);
    dp.dprintf(LVL_MIN_VERB, "Registering %s\n", key.c_str());
    m_Comms.Register(key, 0);
  }
}
<commit_msg>Auctioneer num targets adjustment no longer necessary<commit_after>/**
 * @author Mike Bogochow
 * @version 2.4.0, Dec 8, 2015
 *
 * @file Auctioneer.cpp
 *
 * Auctioneer class implementation
 */

#include "Auctioneer.h"
#include "../lib_auction/AuctionDefs.h"
#include "../lib_auction/DebugPrinter.h"

#include "MBUtils.h"

#include <boost/algorithm/string/predicate.hpp> // starts_with
#include <chrono>
#include <thread>

Auctioneer::Auctioneer(void)
{
  numBidders = 0;
  numTargets = 0;

  roundNumber = 0;
  numRecvdBids = 0;
  bids = nullptr;
}

Auctioneer::~Auctioneer(void)
{
  if (bids != nullptr)
    delete bids;
}

bool
Auctioneer::OnNewMail(MOOSMSG_LIST &NewMail)
{
  bool ret = AuctionMOOSApp::OnNewMail(NewMail);

  MOOSMSG_LIST::reverse_iterator p;
  for(p = NewMail.rbegin(); p != NewMail.rend(); p++)
  {
    CMOOSMsg &msg = *p;
    std::string key   = msg.GetKey();

    if (boost::starts_with(key, MVAR_BID_HEADER))
    {
      int bidder = getBidder(key);
      bids[bidder] = bidFromString(msg.GetString());
      numRecvdBids += 1;
      dp.dprintf(LVL_MIN_VERB, "Got %s mail: %s\n", key.c_str(),
          msg.GetString().c_str());
    }
  }

  return ret;
}

bool
Auctioneer::Iterate(void)
{
  bool ret = AuctionMOOSApp::Iterate();

  dp.dprintf(LVL_MAX_VERB, "roundNum <= numNodes (%lu <= %lu)?\n", roundNumber, numTargets);
  if (roundNumber <= numTargets)
  {
    dp.dprintf(LVL_MID_VERB, "numReceivedBids=%i\n", numRecvdBids);

    if (roundNumber == 0)
      doNotify(MVAR_BID_START, ++roundNumber);
    else if (numRecvdBids == numBidders)
    { // All bids received for round
      WinningBid winner = { 0, MAX_VERTEX, MAX_WEIGHT };
      // Calculate winner
      for (size_t i = 0; i < numBidders; i++)
      {
        if (bids[i].second < winner.bid)
        {
          winner.winner = i;
          winner.target = bids[i].first;
          winner.bid = bids[i].second;
        }
      }

      // Send winner
      doNotify(MVAR_BID_WINNER, winningBidToString(winner));
      doNotify(MVAR_BID_START, ++roundNumber);

      numRecvdBids = 0;
    }
    else
    { // Keep sending the round number in case they didn't get the message.
      doNotify(MVAR_BID_START, roundNumber);
      if (roundNumber == 1)
        doNotify(MVAR_BID_TARGETS, targets);
    }
  }
  else
  {
    // Exit pAuctioneer
    doNotify("EXITED_NORMALLY", "pAuctioneer");
    RequestQuit();
  }

  return ret;
}

bool
Auctioneer::OnStartUp(void)
{
  bool ret;

  // DebugOutput config
  int debugLevel;
  if (!m_MissionReader.GetConfigurationParam("DebugOutput", debugLevel))
    debugLevel = LVL_OFF;
  dp.setLevel((DebugLevel)debugLevel);

  ret = AuctionMOOSApp::OnStartUp();

  if (ret)
  {
    // NumBidders config
    std::string tmp;
    if (!m_MissionReader.GetConfigurationParam("NumBidders", tmp))
      ret = MissingRequiredParam("NumBidders");
    else
    {
      numBidders = boost::lexical_cast<size_t>(tmp);
      this->bids = new Bid[numBidders];
    }

    if (ret)
    {
      // Targets config
      if (!m_MissionReader.GetConfigurationParam("Targets", targets))
        ret = MissingRequiredParam("Targets");
      else
      {
        numTargets = getStringPathSize(targets);
        doNotify(MVAR_BID_TARGETS, targets);
      }

      if (ret)
        RegisterVariables();
    }
  }

  return ret;
}

bool
Auctioneer::OnConnectToServer(void)
{
  bool ret = AuctionMOOSApp::OnConnectToServer();
  RegisterVariables();
  return ret;
}

void
Auctioneer::RegisterVariables(void)
{
  for (size_t i = 0; i < numBidders; i++)
  {
    std::string key = getBidVar(i);
    dp.dprintf(LVL_MIN_VERB, "Registering %s\n", key.c_str());
    m_Comms.Register(key, 0);
  }
}
<|endoftext|>


<commit_before><commit_msg>In KMFolderTree::contentsMouseReleaseEvent make sure all code paths call the base class method KFolderTree::contentsMouseReleaseEvent.<commit_after><|endoftext|>


<commit_before>#include <benchmark/benchmark.h>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wshadow"
#pragma GCC diagnostic ignored "-Wdouble-promotion"
#include <flat_hash_map.hpp>
#pragma GCC diagnostic pop
#include <random>
#include <sparsehash/dense_hash_map>
#include <unordered_map>
#include <utils/macros.h>
#include <vector>

namespace
{
    template <typename HashTableT, typename PostInitF>
    HashTableT CreateHashTable(std::size_t iNumberElements, PostInitF&& iPostInitFunctor)
    {
        using T = typename HashTableT::key_type;

        std::uniform_int_distribution<T> randomDistribution(std::numeric_limits<T>::min(), std::numeric_limits<T>::max());
        std::mt19937_64 generator;

        HashTableT hashTable;
        iPostInitFunctor(hashTable);

        while (hashTable.size() != iNumberElements)
        {
            hashTable.emplace(randomDistribution(generator), hashTable.size());
        }

        return hashTable;
    }

    template <typename HashTableT, typename PostInitF>
    void HashTableLookup_RunBenchmark(benchmark::State& iState, PostInitF&& iPostInitFunctor)
    {
        HashTableT hashTable = CreateHashTable<HashTableT>(iState.range(0), std::forward<PostInitF>(iPostInitFunctor));

        std::vector<typename HashTableT::key_type> dataToLookup;
        dataToLookup.reserve(hashTable.size());

        for (const auto& element : hashTable)
        {
            dataToLookup.emplace_back(element.first);
        }

        std::mt19937_64 randomGenerator(235432876);
        std::shuffle(std::begin(dataToLookup), std::end(dataToLookup), randomGenerator);

        std::size_t i = 0;
        for ([[maybe_unused]] auto handler : iState)
        {
            benchmark::DoNotOptimize(hashTable.find(dataToLookup[i]));
            if (unlikely(dataToLookup.size() == ++i))
            {
                i = 0;
            }
        }
    }

    template <typename HashTableT>
    void HashTableLookup_RunBenchmark(benchmark::State& iState)
    {
        return HashTableLookup_RunBenchmark<HashTableT>(iState, [](HashTableT& iHashTable) {});
    }

    void HashTableLookup_DenseHashMapBenchmark(benchmark::State& iState)
    {
        HashTableLookup_RunBenchmark<google::dense_hash_map<std::int64_t, std::int64_t>>(iState, [](auto& iHashTable) { iHashTable.set_empty_key(-1); });
    }

    void HashTableLookup_FlatHashMapBenchmark(benchmark::State& iState)
    {
        HashTableLookup_RunBenchmark<ska::flat_hash_map<std::int64_t, std::int64_t>>(iState);
    }

    void HashTableLookup_UnorderedMapBenchmark(benchmark::State& iState)
    {
        HashTableLookup_RunBenchmark<std::unordered_map<std::int64_t, std::int64_t>>(iState);
    }

    void HashTableLookup_Arguments(benchmark::internal::Benchmark* iBenchmark)
    {
        for (double i = 10; i <= 120'000; i *= 12) // NOLINT
        {
            iBenchmark->Arg(i);
        }
    }
}

// All of the graphs are spiky. This is because all hashtables have different performance depending on the current load factor.
// Meaning depending on how full they are. When a table is 25% full lookups will be faster than when it’s 50% full.
// The reason for this is that there are more hash collisions when the table is more full.
// So you can see the cost go up until at some point the table decides that it’s too full and that it should reallocate, which makes lookups fast again.

// Another thing that we notice is that all the graphs are essentially flat on the left half of the screen.
// This is because the table fits entirely into the cache. Only when we get to the point where the data doesn’t fit into the L3 cache do we see the different graphs really diverge.
// You will only get the numbers on the left if the element you’re looking for is already in the cache.
BENCHMARK(HashTableLookup_DenseHashMapBenchmark)->Apply(HashTableLookup_Arguments); // NOLINT
BENCHMARK(HashTableLookup_FlatHashMapBenchmark)->Apply(HashTableLookup_Arguments);  // NOLINT
BENCHMARK(HashTableLookup_UnorderedMapBenchmark)->Apply(HashTableLookup_Arguments); // NOLINT
<commit_msg>Update benchmark_lookup.cpp<commit_after>#include <benchmark/benchmark.h>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wshadow"
#pragma GCC diagnostic ignored "-Wdouble-promotion"
#include <flat_hash_map.hpp>
#include <sparsehash/dense_hash_map>
#pragma GCC diagnostic pop
#include <random>
#include <unordered_map>
#include <utils/macros.h>
#include <vector>

namespace
{
    template <typename HashTableT, typename PostInitF>
    HashTableT CreateHashTable(std::size_t iNumberElements, PostInitF&& iPostInitFunctor)
    {
        using T = typename HashTableT::key_type;

        std::uniform_int_distribution<T> randomDistribution(std::numeric_limits<T>::min(), std::numeric_limits<T>::max());
        std::mt19937_64 generator;

        HashTableT hashTable;
        iPostInitFunctor(hashTable);

        while (hashTable.size() != iNumberElements)
        {
            hashTable.emplace(randomDistribution(generator), hashTable.size());
        }

        return hashTable;
    }

    template <typename HashTableT, typename PostInitF>
    void HashTableLookup_RunBenchmark(benchmark::State& iState, PostInitF&& iPostInitFunctor)
    {
        HashTableT hashTable = CreateHashTable<HashTableT>(iState.range(0), std::forward<PostInitF>(iPostInitFunctor));

        std::vector<typename HashTableT::key_type> dataToLookup;
        dataToLookup.reserve(hashTable.size());

        for (const auto& element : hashTable)
        {
            dataToLookup.emplace_back(element.first);
        }

        std::mt19937_64 randomGenerator(235432876);
        std::shuffle(std::begin(dataToLookup), std::end(dataToLookup), randomGenerator);

        std::size_t i = 0;
        for ([[maybe_unused]] auto handler : iState)
        {
            benchmark::DoNotOptimize(hashTable.find(dataToLookup[i]));
            if (unlikely(dataToLookup.size() == ++i))
            {
                i = 0;
            }
        }
    }

    template <typename HashTableT>
    void HashTableLookup_RunBenchmark(benchmark::State& iState)
    {
        return HashTableLookup_RunBenchmark<HashTableT>(iState, [](HashTableT& iHashTable) {});
    }

    void HashTableLookup_DenseHashMapBenchmark(benchmark::State& iState)
    {
        HashTableLookup_RunBenchmark<google::dense_hash_map<std::int64_t, std::int64_t>>(iState, [](auto& iHashTable) { iHashTable.set_empty_key(-1); });
    }

    void HashTableLookup_FlatHashMapBenchmark(benchmark::State& iState)
    {
        HashTableLookup_RunBenchmark<ska::flat_hash_map<std::int64_t, std::int64_t>>(iState);
    }

    void HashTableLookup_UnorderedMapBenchmark(benchmark::State& iState)
    {
        HashTableLookup_RunBenchmark<std::unordered_map<std::int64_t, std::int64_t>>(iState);
    }

    void HashTableLookup_Arguments(benchmark::internal::Benchmark* iBenchmark)
    {
        for (double i = 10; i <= 120'000; i *= 12) // NOLINT
        {
            iBenchmark->Arg(i);
        }
    }
}

// All of the graphs are spiky. This is because all hashtables have different performance depending on the current load factor.
// Meaning depending on how full they are. When a table is 25% full lookups will be faster than when it’s 50% full.
// The reason for this is that there are more hash collisions when the table is more full.
// So you can see the cost go up until at some point the table decides that it’s too full and that it should reallocate, which makes lookups fast again.

// Another thing that we notice is that all the graphs are essentially flat on the left half of the screen.
// This is because the table fits entirely into the cache. Only when we get to the point where the data doesn’t fit into the L3 cache do we see the different graphs really diverge.
// You will only get the numbers on the left if the element you’re looking for is already in the cache.
BENCHMARK(HashTableLookup_DenseHashMapBenchmark)->Apply(HashTableLookup_Arguments); // NOLINT
BENCHMARK(HashTableLookup_FlatHashMapBenchmark)->Apply(HashTableLookup_Arguments);  // NOLINT
BENCHMARK(HashTableLookup_UnorderedMapBenchmark)->Apply(HashTableLookup_Arguments); // NOLINT
<|endoftext|>


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

#ifndef __URLKEYS_HXX
#define __URLKEYS_HXX

// Defines for common keys in URL files

// ANSI version

#define A_URLSECTION_SHORTCUT   "InternetShortcut"
#define A_URLKEY_URL            "URL"
#define A_URLKEY_TITLE          "Title"
#define A_URLKEY_TARGET         "Target"
#define A_URLKEY_FRAME          "Frame"
#define A_URLKEY_OPENAS         "OpenAs"
#define A_URLKEY_SOICON         "SOIcon"
#define A_URLKEY_WIN_ICONFILE   "IconFile"
#define A_URLKEY_WIN_ICONINDEX  "IconIndex"
#define A_URLKEY_WORKDIR        "WorkingDirectory"
#define A_URLKEY_ARGUMENTS      "Arguments"
#define A_URLKEY_INTERN_ORIGURL "[URL]"

// Unicode version

#define U_URLSECTION_SHORTCUT   L"InternetShortcut"
#define U_URLKEY_URL            L"URL"
#define U_URLKEY_TITLE          L"Title"
#define U_URLKEY_TARGET         L"Target"
#define U_URLKEY_FRAME          L"Frame"
#define U_URLKEY_OPENAS         L"OpenAs"
#define U_URLKEY_SOICON         L"SOIcon"
#define U_URLKEY_WIN_ICONFILE   L"IconFile"
#define U_URLKEY_WIN_ICONINDEX  L"IconIndex"
#define U_URLKEY_WORKDIR        L"WorkingDirectory"
#define U_URLKEY_ARGUMENTS      L"Arguments"
#define U_URLKEY_INTERN_ORIGURL L"[URL]"

#   define URLSECTION_SHORTCUT  U_URLSECTION_SHORTCUT
#   define URLKEY_URL           U_URLKEY_URL
#   define URLKEY_TITLE         U_URLKEY_TITLE
#   define URLKEY_TARGET        U_URLKEY_TARGET
#   define URLKEY_FRAME         U_URLKEY_FRAME
#   define URLKEY_OPENAS        U_URLKEY_OPENAS
#   define URLKEY_SOICON        U_URLKEY_SOICON
#   define URLKEY_WIN_ICONFILE  U_URLKEY_WIN_ICONFILE
#   define URLKEY_WIN_ICONINDEX U_URLKEY_WIN_ICONINDEX
#   define URLKEY_WORKDIR       U_URLKEY_WORKDIR
#   define URLKEY_ARGUMENTS     U_URLKEY_ARGUMENTS
#   define URLKEY_INTERN_ORIGURL U_URLKEY_INTERN_ORIGURL

#endif // __URLKEYS_HXX

<commit_msg>INTEGRATION: CWS changefileheader (1.2.120); FILE MERGED 2008/03/28 15:41:14 rt 1.2.120.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: urlkeys.hxx,v $
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef __URLKEYS_HXX
#define __URLKEYS_HXX

// Defines for common keys in URL files

// ANSI version

#define A_URLSECTION_SHORTCUT   "InternetShortcut"
#define A_URLKEY_URL            "URL"
#define A_URLKEY_TITLE          "Title"
#define A_URLKEY_TARGET         "Target"
#define A_URLKEY_FRAME          "Frame"
#define A_URLKEY_OPENAS         "OpenAs"
#define A_URLKEY_SOICON         "SOIcon"
#define A_URLKEY_WIN_ICONFILE   "IconFile"
#define A_URLKEY_WIN_ICONINDEX  "IconIndex"
#define A_URLKEY_WORKDIR        "WorkingDirectory"
#define A_URLKEY_ARGUMENTS      "Arguments"
#define A_URLKEY_INTERN_ORIGURL "[URL]"

// Unicode version

#define U_URLSECTION_SHORTCUT   L"InternetShortcut"
#define U_URLKEY_URL            L"URL"
#define U_URLKEY_TITLE          L"Title"
#define U_URLKEY_TARGET         L"Target"
#define U_URLKEY_FRAME          L"Frame"
#define U_URLKEY_OPENAS         L"OpenAs"
#define U_URLKEY_SOICON         L"SOIcon"
#define U_URLKEY_WIN_ICONFILE   L"IconFile"
#define U_URLKEY_WIN_ICONINDEX  L"IconIndex"
#define U_URLKEY_WORKDIR        L"WorkingDirectory"
#define U_URLKEY_ARGUMENTS      L"Arguments"
#define U_URLKEY_INTERN_ORIGURL L"[URL]"

#   define URLSECTION_SHORTCUT  U_URLSECTION_SHORTCUT
#   define URLKEY_URL           U_URLKEY_URL
#   define URLKEY_TITLE         U_URLKEY_TITLE
#   define URLKEY_TARGET        U_URLKEY_TARGET
#   define URLKEY_FRAME         U_URLKEY_FRAME
#   define URLKEY_OPENAS        U_URLKEY_OPENAS
#   define URLKEY_SOICON        U_URLKEY_SOICON
#   define URLKEY_WIN_ICONFILE  U_URLKEY_WIN_ICONFILE
#   define URLKEY_WIN_ICONINDEX U_URLKEY_WIN_ICONINDEX
#   define URLKEY_WORKDIR       U_URLKEY_WORKDIR
#   define URLKEY_ARGUMENTS     U_URLKEY_ARGUMENTS
#   define URLKEY_INTERN_ORIGURL U_URLKEY_INTERN_ORIGURL

#endif // __URLKEYS_HXX

<|endoftext|>


<commit_before><commit_msg>Add files via upload<commit_after><|endoftext|>


<commit_before><commit_msg>Minor bug fix<commit_after><|endoftext|>


<commit_before>#include <windows.h>
#include <math.h>
#include <string>
#include <vector>
#include <sstream>
#include "../math/math.h"
#include <objidl.h>
#include <gdiplus.h>
#pragma comment( lib, "gdiplus.lib" )
using namespace std;
using namespace Gdiplus;

// Gdiplus
GdiplusStartupInput g_gdiplusStartupInput;
ULONG_PTR g_gdiplusToken;
Graphics *g_graphics;
Font *g_font;
Pen *g_pen; //  ü.
Brush *g_blackBrush; // 귯 ü.
Brush *g_redBrush; // 귯 ü.
Brush *g_brush; // 귯 ü.
Bitmap *g_bg;
Image *g_image;
Image *g_carImage;
HWND g_hWnd = NULL;

int g_incT = 0;
int frameT = 0;
int frame = 0;
wstring frameStr;

int g_pathIdx = 0;
vector<Vector3> g_Path;
struct sCar
{
	bool isStop;
	int curPathIdx;
	Vector3 pos;
	float speed; // ʴ ȼ ̵ӵ.
};
sCar g_car;

// ݹ ν Լ  Ÿ
LRESULT CALLBACK WndProc( HWND hWnd, UINT iMessage,
	WPARAM wParam, LPARAM lParam );
void InitGdiPlus(HWND hWnd);
void ReleaseGdiPlus();
void DrawString( Graphics *graph, int x, int y, const wstring &str);
void MainLoop(int elapseT);
void MoveCar(int elapseT);

int APIENTRY WinMain(HINSTANCE hInstance,
	HINSTANCE hPrevInstance,
	LPSTR lpCmdLine,
	int nCmdShow)
{
	wchar_t className[32] = L"Petrol Station";
	wchar_t windowName[32] = L"Petrol Station";

	// Ŭ
	// ̷  ڴ
	WNDCLASS WndClass;
	WndClass.cbClsExtra = 0;			//쿡 ϴ  ޸𸮼( ׳ 0 ̴  Ű澲 )
	WndClass.cbWndExtra = 0;			//쿡 ϴ  ޸𸮼( ׳ 0 ̴  Ű澲 )
	WndClass.hbrBackground = (HBRUSH)GetStockObject(LTGRAY_BRUSH);		//
	WndClass.hCursor = LoadCursor( NULL, IDC_ARROW );			// Ŀ
	WndClass.hIcon = LoadIcon( NULL, IDI_APPLICATION );		//ܸ
	WndClass.hInstance = hInstance;				//α׷νϽڵ
	WndClass.lpfnWndProc = (WNDPROC)WndProc;			// ν Լ
	WndClass.lpszMenuName = NULL;						//޴̸  NULL
	WndClass.lpszClassName = className;				// ۼϰ ִ  Ŭ ̸
	WndClass.style	 = CS_HREDRAW | CS_VREDRAW;	// ׸   (  ɶ ȭ鰻 CS_HREDRAW | CS_VREDRAW )

	// ۼ  Ŭ
	RegisterClass( &WndClass );

	//
	//  ڵ  g_hWnd  ޴´.
	HWND hWnd = CreateWindow(
		className,				//Ǵ  Ŭ̸
		windowName,				// ŸƲٿ µǴ ̸
		WS_OVERLAPPEDWINDOW,	// Ÿ WS_OVERLAPPEDWINDOW
		0,				//  ġ X
		0,				//  ġ Y
		800,				//  ũ ( ۾ ũⰡ ƴ )
		600,				//  ũ ( ۾ ũⰡ ƴ )
		GetDesktopWindow(),		//θ  ڵ ( α׷ ֻ  NULL Ǵ GetDesktopWindow() )
		NULL,					//޴ ID ( ڽ Ʈ ü ΰ Ʈ ID
		hInstance,				// 찡  α׷ νϽ ڵ
		NULL					//߰  NULL ( Ű )
		);

	g_hWnd = hWnd;

	//츦 Ȯ ۾ ũ
	RECT rcClient = { 0, 0, 800, 600};
	AdjustWindowRect( &rcClient, WS_OVERLAPPEDWINDOW, FALSE );	//rcClient ũ⸦ ۾    ũ⸦ rcClient  ԵǾ ´.

	// ũ  ġ ٲپش.
	SetWindowPos( hWnd, NULL, 0, 0, rcClient.right - rcClient.left, rcClient.bottom - rcClient.top,
		SWP_NOZORDER | SWP_NOMOVE );

	// 츦 ȭ鿡 .
	ShowWindow( hWnd, nCmdShow );

	InitGdiPlus(hWnd);

	//޽ ü
	MSG msg;
	ZeroMemory( &msg, sizeof(MSG) );

	int oldT = GetTickCount();
	while (msg.message != WM_QUIT)
	{
		//PeekMessage  ޽ ť ޽  α׷ ߱ ʰ  ȴ.
		//̶ ޽ť ޽  false  ϵǰ ޽  true  ̵ȴ.
		if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
		{
			TranslateMessage( &msg ); // Ű  ڸ Ͽ WM_CHAR ޽ ߻Ų.
			DispatchMessage( &msg );  //޾ƿ ޽   ν Լ Ų.
		}

		const int curT = GetTickCount();
		const int elapseT = curT - oldT;
		if (elapseT > 15)
		{
			oldT = curT;
			MainLoop(elapseT);
		}

	}

	ReleaseGdiPlus();
	return 0;
}

//
//  ν Լ ( ޽ ť ޾ƿ ޽ óѴ )
//
LRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
	PAINTSTRUCT ps;
	HDC hdc;

	switch (msg)
	{
	case WM_PAINT: // ȭ ŵ  ȣȴ.
		{
			hdc = BeginPaint(hWnd, &ps);
			Graphics *graph = Graphics::FromImage(g_bg);

			RECT cr;
			GetClientRect(hWnd, &cr);
			Rect wndSize(cr.left, cr.top, cr.right, cr.bottom);
			graph->DrawImage(g_image, wndSize);

			for (int i=0; i < (int)g_Path.size(); ++i)
			{
				graph->FillEllipse(g_redBrush, (int)g_Path[ i].x, (int)g_Path[ i].z, 5, 5);
			}

			const int W = 113;
			const int H = 58;
			Vector3 p1(-W/2, 0, -H/2);
			Vector3 p2(W/2, 0, -H/2);
			Vector3 p3(-W/2, 0, H/2);

			Matrix44 m;
			if ((g_car.curPathIdx >= 0) &&
				(g_car.curPathIdx+1 < (int)g_Path.size()))
			{
				Vector3 dir = g_Path[ g_car.curPathIdx+1]
				- g_car.pos;
				dir.Normalize();

				Quaternion q(Vector3(1,0,0),
					Vector3(dir.x, 0, -dir.z));
				m = q.GetMatrix();
			}

			Vector3 pp1 = (p1 * m) + g_car.pos;
			Vector3 pp2 = (p2 * m) + g_car.pos;
			Vector3 pp3 = (p3 * m) + g_car.pos;

			Point pp[3];
			pp[0] = Point((int)pp1.x, (int)pp1.z);
			pp[1] = Point((int)pp2.x, (int)pp2.z);
			pp[2] = Point((int)pp3.x, (int)pp3.z);

			//graph->DrawImage(g_carImage,
			//	Rect((int)g_car.pos.x-(113/2),
			//	(int)g_car.pos.y-(58/2), 113, 58) );

			graph->DrawImage(g_carImage,
				pp,
				3,
				0,0,W,H, UnitPixel);

			DrawString(graph, 50, 0, frameStr);
			g_graphics->DrawImage(g_bg, wndSize);
			EndPaint(hWnd, &ps);
		}
		break;

	case WM_LBUTTONDOWN:
		{
			Vector3 pos(LOWORD(lParam), 0, HIWORD(lParam));
			g_Path.push_back(pos);
		}
		break;

	case WM_LBUTTONUP:
		break;
	case WM_MOUSEMOVE:
		break;
	case WM_KEYDOWN:
		break;

	case WM_DESTROY: //찡 ıȴٸ..
		PostQuitMessage(0);	//α׷  û ( ޽   ȴ )
		break;
	}

	return DefWindowProc( hWnd, msg, wParam, lParam ); // ⺻ ޼ ó Ѵ.
}

// Gdiplus ʱȭ.
void InitGdiPlus(HWND hWnd)
{
	//Start Gdiplus
	Gdiplus::GdiplusStartup(&g_gdiplusToken, &g_gdiplusStartupInput, NULL);
	g_graphics = new Graphics(hWnd);
	g_pen = new Pen(Color::Red);
	g_brush = new SolidBrush(Color::White);
	g_blackBrush = new SolidBrush(0xFF000000);
	g_redBrush = new SolidBrush(0xFFFF0000);
	g_font = new Font(L"Arial", 16);
	g_bg = new Bitmap(800,600);
	g_image = Image::FromFile(L"oilbank.png");
	g_carImage = Image::FromFile(L"car.png");

	g_car.isStop = false;
	g_car.curPathIdx = -1;
	g_car.pos = Vector3(0,0,0);
	g_car.speed = 40;

}

// Gdiplus .
void ReleaseGdiPlus()
{
	delete g_image;
	delete g_font;
	delete g_pen;
	delete g_brush;
	delete g_blackBrush;
	delete g_redBrush;
	delete g_graphics;
	delete g_bg;
	delete g_carImage;
	// Shutdown Gdiplus
	Gdiplus::GdiplusShutdown(g_gdiplusToken);
}

void DrawString( Graphics *graph, int x, int y, const wstring &str)
{
	StringFormat format;
	format.SetAlignment(StringAlignmentCenter);

	graph->DrawString( str.c_str(), -1, g_font,
		PointF((REAL)x, (REAL)y),
		&format, g_blackBrush);
}

void MainLoop(int elapseT)
{
	MoveCar(elapseT);

	++frame;
	frameT += elapseT;
	if (frameT > 1000)
	{
		std::wstringstream ss;
		ss << frame;
		frameStr = ss.str();
		frame = 0;
		frameT = 0;
	}

	::InvalidateRect(g_hWnd, NULL, FALSE);
}

void MoveCar(int elapseT)
{
	//if (g_car.isStop)
	//	return;

	if (2 > (int)g_Path.size())
		return;
	if ((g_car.curPathIdx+1) >= (int)g_Path.size())
		return;

	if (g_car.curPathIdx == -1)
	{
		g_car.pos = g_Path[ 0];
		g_car.curPathIdx = 0;
	}

	Vector3 dir = g_Path[ g_car.curPathIdx+1] - g_car.pos;
	const float len = dir.Length();

	if (len < 1.9f)
	{
		//  η ̵Ѵ.
		if ((g_car.curPathIdx + 1) < (int)g_Path.size())
		{
			++g_car.curPathIdx;
		}
		else
		{
			g_car.isStop = true;
		}
	}

	dir.Normalize();
	g_car.pos += dir * g_car.speed * (elapseT * 0.001f);
}
<commit_msg>petrol<commit_after>#include <windows.h>
#include <math.h>
#include <string>
#include <vector>
#include <sstream>
#include "../math/math.h"
#include <objidl.h>
#include <gdiplus.h>
#pragma comment( lib, "gdiplus.lib" )
using namespace std;
using namespace Gdiplus;

// Gdiplus
GdiplusStartupInput g_gdiplusStartupInput;
ULONG_PTR g_gdiplusToken;
Graphics *g_graphics;
Font *g_font;
Pen *g_pen; //  ü.
Brush *g_blackBrush; // 귯 ü.
Brush *g_redBrush; // 귯 ü.
Brush *g_blueBrush; // 귯 ü.
Brush *g_brush; // 귯 ü.
Bitmap *g_bg;
Image *g_image;
Image *g_carImage;
HWND g_hWnd = NULL;

int g_incT = 0;
int frameT = 0;
int frame = 0;
wstring frameStr;

struct sPath
{
	int type; // 0:move, 1:stop
	Vector3 pos;
};

vector<sPath> g_Path;
struct sCar
{
	bool isStop;
	int waitTime;
	int curPathIdx;
	Vector3 pos;
	float speed; // ʴ ȼ ̵ӵ.
};
sCar g_car;

// ݹ ν Լ  Ÿ
LRESULT CALLBACK WndProc( HWND hWnd, UINT iMessage,
	WPARAM wParam, LPARAM lParam );
void InitGdiPlus(HWND hWnd);
void ReleaseGdiPlus();
void DrawString( Graphics *graph, int x, int y, const wstring &str);
void MainLoop(int elapseT);
void MoveCar(int elapseT);

int APIENTRY WinMain(HINSTANCE hInstance,
	HINSTANCE hPrevInstance,
	LPSTR lpCmdLine,
	int nCmdShow)
{
	wchar_t className[32] = L"Petrol Station";
	wchar_t windowName[32] = L"Petrol Station";

	// Ŭ
	// ̷  ڴ
	WNDCLASS WndClass;
	WndClass.cbClsExtra = 0;			//쿡 ϴ  ޸𸮼( ׳ 0 ̴  Ű澲 )
	WndClass.cbWndExtra = 0;			//쿡 ϴ  ޸𸮼( ׳ 0 ̴  Ű澲 )
	WndClass.hbrBackground = (HBRUSH)GetStockObject(LTGRAY_BRUSH);		//
	WndClass.hCursor = LoadCursor( NULL, IDC_ARROW );			// Ŀ
	WndClass.hIcon = LoadIcon( NULL, IDI_APPLICATION );		//ܸ
	WndClass.hInstance = hInstance;				//α׷νϽڵ
	WndClass.lpfnWndProc = (WNDPROC)WndProc;			// ν Լ
	WndClass.lpszMenuName = NULL;						//޴̸  NULL
	WndClass.lpszClassName = className;				// ۼϰ ִ  Ŭ ̸
	WndClass.style	 = CS_HREDRAW | CS_VREDRAW;	// ׸   (  ɶ ȭ鰻 CS_HREDRAW | CS_VREDRAW )

	// ۼ  Ŭ
	RegisterClass( &WndClass );

	//
	//  ڵ  g_hWnd  ޴´.
	HWND hWnd = CreateWindow(
		className,				//Ǵ  Ŭ̸
		windowName,				// ŸƲٿ µǴ ̸
		WS_OVERLAPPEDWINDOW,	// Ÿ WS_OVERLAPPEDWINDOW
		0,				//  ġ X
		0,				//  ġ Y
		800,				//  ũ ( ۾ ũⰡ ƴ )
		600,				//  ũ ( ۾ ũⰡ ƴ )
		GetDesktopWindow(),		//θ  ڵ ( α׷ ֻ  NULL Ǵ GetDesktopWindow() )
		NULL,					//޴ ID ( ڽ Ʈ ü ΰ Ʈ ID
		hInstance,				// 찡  α׷ νϽ ڵ
		NULL					//߰  NULL ( Ű )
		);

	g_hWnd = hWnd;

	//츦 Ȯ ۾ ũ
	RECT rcClient = { 0, 0, 800, 600};
	AdjustWindowRect( &rcClient, WS_OVERLAPPEDWINDOW, FALSE );	//rcClient ũ⸦ ۾    ũ⸦ rcClient  ԵǾ ´.

	// ũ  ġ ٲپش.
	SetWindowPos( hWnd, NULL, 0, 0, rcClient.right - rcClient.left, rcClient.bottom - rcClient.top,
		SWP_NOZORDER | SWP_NOMOVE );

	// 츦 ȭ鿡 .
	ShowWindow( hWnd, nCmdShow );

	InitGdiPlus(hWnd);

	//޽ ü
	MSG msg;
	ZeroMemory( &msg, sizeof(MSG) );

	int oldT = GetTickCount();
	while (msg.message != WM_QUIT)
	{
		//PeekMessage  ޽ ť ޽  α׷ ߱ ʰ  ȴ.
		//̶ ޽ť ޽  false  ϵǰ ޽  true  ̵ȴ.
		if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
		{
			TranslateMessage( &msg ); // Ű  ڸ Ͽ WM_CHAR ޽ ߻Ų.
			DispatchMessage( &msg );  //޾ƿ ޽   ν Լ Ų.
		}

		const int curT = GetTickCount();
		const int elapseT = curT - oldT;
		if (elapseT > 15)
		{
			oldT = curT;
			MainLoop(elapseT);
		}

	}

	ReleaseGdiPlus();
	return 0;
}

//
//  ν Լ ( ޽ ť ޾ƿ ޽ óѴ )
//
LRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
	PAINTSTRUCT ps;
	HDC hdc;

	switch (msg)
	{
	case WM_PAINT: // ȭ ŵ  ȣȴ.
		{
			hdc = BeginPaint(hWnd, &ps);
			Graphics *graph = Graphics::FromImage(g_bg);

			RECT cr;
			GetClientRect(hWnd, &cr);
			Rect wndSize(cr.left, cr.top, cr.right, cr.bottom);
			graph->DrawImage(g_image, wndSize);

			for (int i=0; i < (int)g_Path.size(); ++i)
			{
				graph->FillEllipse((g_Path[ i].type==0)? g_redBrush : g_blueBrush,
					(int)g_Path[ i].pos.x, (int)g_Path[ i].pos.z, 5, 5);
			}

			const int W = 113;
			const int H = 58;
			Vector3 p1(-W/2, 0, -H/2);
			Vector3 p2(W/2, 0, -H/2);
			Vector3 p3(-W/2, 0, H/2);

			Matrix44 m;
			if ((g_car.curPathIdx >= 0) &&
				(g_car.curPathIdx+1 < (int)g_Path.size()))
			{
				Vector3 dir = g_Path[ g_car.curPathIdx+1].pos
				- g_car.pos;
				dir.Normalize();

				Quaternion q(Vector3(1,0,0),
					Vector3(dir.x, 0, -dir.z));
				m = q.GetMatrix();
			}

			Vector3 pp1 = (p1 * m) + g_car.pos;
			Vector3 pp2 = (p2 * m) + g_car.pos;
			Vector3 pp3 = (p3 * m) + g_car.pos;

			Point pp[3];
			pp[0] = Point((int)pp1.x, (int)pp1.z);
			pp[1] = Point((int)pp2.x, (int)pp2.z);
			pp[2] = Point((int)pp3.x, (int)pp3.z);

			graph->DrawImage(g_carImage,
				pp,
				3,
				0,0,W,H, UnitPixel);

			DrawString(graph, 50, 0, frameStr);
			g_graphics->DrawImage(g_bg, wndSize);
			EndPaint(hWnd, &ps);
		}
		break;

	case WM_LBUTTONDOWN:
		{
			Vector3 pos(LOWORD(lParam), 0, HIWORD(lParam));
			sPath path;
			path.pos = pos;
			path.type = 0;
			g_Path.push_back(path);
		}
		break;

	case WM_RBUTTONDOWN:
		{
			Vector3 pos(LOWORD(lParam), 0, HIWORD(lParam));
			sPath path;
			path.pos = pos;
			path.type = 1;
			g_Path.push_back(path);
		}
		break;

	case WM_LBUTTONUP:
		break;
	case WM_MOUSEMOVE:
		break;
	case WM_KEYDOWN:
		break;

	case WM_DESTROY: //찡 ıȴٸ..
		PostQuitMessage(0);	//α׷  û ( ޽   ȴ )
		break;
	}

	return DefWindowProc( hWnd, msg, wParam, lParam ); // ⺻ ޼ ó Ѵ.
}

// Gdiplus ʱȭ.
void InitGdiPlus(HWND hWnd)
{
	//Start Gdiplus
	Gdiplus::GdiplusStartup(&g_gdiplusToken, &g_gdiplusStartupInput, NULL);
	g_graphics = new Graphics(hWnd);
	g_pen = new Pen(Color::Red);
	g_brush = new SolidBrush(Color::White);
	g_blackBrush = new SolidBrush(0xFF000000);
	g_redBrush = new SolidBrush(0xFFFF0000);
	g_blueBrush = new SolidBrush(0xFF0000FF);
	g_font = new Font(L"Arial", 16);
	g_bg = new Bitmap(800,600);
	g_image = Image::FromFile(L"oilbank.png");
	g_carImage = Image::FromFile(L"car.png");

	g_car.isStop = false;
	g_car.waitTime = 0;
	g_car.curPathIdx = -1;
	g_car.pos = Vector3(0,0,0);
	g_car.speed = 40;

}

// Gdiplus .
void ReleaseGdiPlus()
{
	delete g_image;
	delete g_font;
	delete g_pen;
	delete g_brush;
	delete g_blackBrush;
	delete g_redBrush;
	delete g_blueBrush;
	delete g_graphics;
	delete g_bg;
	delete g_carImage;
	// Shutdown Gdiplus
	Gdiplus::GdiplusShutdown(g_gdiplusToken);
}

void DrawString( Graphics *graph, int x, int y, const wstring &str)
{
	StringFormat format;
	format.SetAlignment(StringAlignmentCenter);

	graph->DrawString( str.c_str(), -1, g_font,
		PointF((REAL)x, (REAL)y),
		&format, g_blackBrush);
}

void MainLoop(int elapseT)
{
	MoveCar(elapseT);

	++frame;
	frameT += elapseT;
	if (frameT > 1000)
	{
		std::wstringstream ss;
		ss << frame;
		frameStr = ss.str();
		frame = 0;
		frameT = 0;
	}

	::InvalidateRect(g_hWnd, NULL, FALSE);
}

void MoveCar(int elapseT)
{
	//if (g_car.isStop)
	//	return;

	if (2 > (int)g_Path.size())
		return;
	if ((g_car.curPathIdx+1) >= (int)g_Path.size())
		return;

	if (g_car.curPathIdx == -1)
	{
		g_car.pos = g_Path[ 0].pos;
		g_car.curPathIdx = 0;
	}

	Vector3 dir = g_Path[ g_car.curPathIdx+1].pos - g_car.pos;
	const float len = dir.Length();

	if (len < 1.9f)
	{
		//  η ̵Ѵ.
		if ((g_car.curPathIdx + 1) < (int)g_Path.size())
		{
			if (g_Path[ g_car.curPathIdx+1].type == 1)
			{
				// ð  Ѵ.
				g_car.waitTime += elapseT;
				if (g_car.waitTime > 5000)
				{
					++g_car.curPathIdx;
					g_car.waitTime =0;
				}
			}
			else
			{
				++g_car.curPathIdx;
			}
		}
		else
		{
			g_car.isStop = true;
		}
	}

	dir.Normalize();
	g_car.pos += dir * g_car.speed * (elapseT * 0.001f);
}
<|endoftext|>