<commit_before>// main.cpp
// Main function for testing Maggie code
//
// Oliver W. Laslett 2015
// O.Laslett@soton.ac.uk
//
#include<iostream>
using std::cout;
using std::endl;

#include<cmath>
using std::cos;
using std::sin;

#include<maggie.hpp>
#include<gtest/gtest.h>
#include<gmock/gmock.h>
#include<boost/multi_array.hpp>
typedef boost::multi_array<float,1> array_f;
typedef boost::multi_array<float,2> matrix_f;
typedef boost::multi_array<float,3> cube_f;

#include<vector>

// Test construction of StocLLG
TEST(StochasticLLG, ContructAndDim)
{
  StocLLG llg( 1, 2, 3, 4, 5 );
  EXPECT_EQ( 3, llg.getDim() );
}

// Test deterministic part of StocLLG
TEST(StochasticLLG, Drift)
{
  // declare in and out arrays
  array_f out( boost::extents[3] );
  array_f in( boost::extents[3] );
  in[0] = 2;
  in[1] = 3;
  in[2] = 4;

  // Set up StocLLG and compute drift
  StocLLG llg( 2, 3, 1, 2, 3 );
  llg.computeDrift( out, in );

  // Are the solutions correct?
  EXPECT_EQ( -34, out[0] );
  EXPECT_EQ( -4, out[1] );
  EXPECT_EQ( 20, out[2] );
}

// Test the stochastic part of the StocLLG
TEST(StochasticLLG, Diffusion)
{
  // declare in and out arrays
  array_f in( boost::extents[3] );
  matrix_f out( boost::extents[3][3] );
  in[0] = 2;
  in[1] = 3;
  in[2] = 4;

  // set up the StocLLG and compute diffusion
  StocLLG llg( 2, 3, 1, 2, 3 );
  llg.computeDiffusion( out, in );

  // are the solutions correct?
  EXPECT_EQ( 150, out[0][0] );
  EXPECT_EQ( -28, out[0][1] );
  EXPECT_EQ( -54, out[0][2] );
  EXPECT_EQ( -44, out[1][0] );
  EXPECT_EQ( 120, out[1][1] );
  EXPECT_EQ( -68, out[1][2] );
  EXPECT_EQ( -42, out[2][0] );
  EXPECT_EQ( -76, out[2][1] );
  EXPECT_EQ( 78, out[2][2] );
}

// Test the RK4 algorithm
TEST(RK4, BasicCircle)
{
  // declare array for initial state
  array_f state( boost::extents[2] );

  float t=0; // initial time

  // fill the array state
  state[0] = 1;
  state[1] = 0;

  // Basic differential equation
  class ode : public LangevinEquation
  {
  public:
    ode() : LangevinEquation( 2 ) {}; // constructor

    // Differential equation
    virtual void computeDrift( array_f& out, array_f& in)
    {
      out[0] = in[1];
      out[1] = -in[0];
    }
  } testOde;

  // Create an instance of the RK4 integrator
  RK4 inte( testOde, state, t, 0.000001 );

  // Run the integrator for 2000 steps
  for( int i=0; i<500; i++ )
    inte.step();

  // Get the state and time
  state = inte.getState();
  t = inte.getTime();

  // Check the solution
  ASSERT_FLOAT_EQ( cos( t ), state[0] );
  ASSERT_FLOAT_EQ( -sin( t ), state[1] );
}

// Test for the Particles
TEST(Particle, SetSize)
{
  array_f uea( boost::extents[3] );
  uea[0] = 1;
  uea[1] = 0;
  uea[2] = 0;
  Particle p( 1, 2, 3, 4, 5, uea );
  ASSERT_FLOAT_EQ( 33.51032, p.getV() );
}

// Check that uea is a unit vector
TEST(Particle, UnitVector)
{
  array_f uea( boost::extents[3] );
  // Not a unit vector
  uea[0] = 0.3;
  uea[1] = 0.5;
  uea[2] = 0.7;
  ASSERT_THROW( Particle p( 1, 2, 3, 4, 5, uea ),
		std::invalid_argument );
  // is a unit vector
  uea[0] = 0.5773503;
  uea[1] = 0.5773503;
  uea[2] = 0.5773503;
  ASSERT_NO_THROW( Particle p( 1, 2, 3, 4, 5, uea ) );
}

// Test the particle cluster, are the distances correct?
TEST(ParticleCluster, Distances)
{
  // create list of 3 identical particles
  array_f uea( boost::extents[3] );
  uea[0] = 1.0;
  uea[1] = 0.0;
  uea[2] = 0.0;
  Particle p1( 1,2,3,4,5,uea );
  std::vector<Particle> plist = {p1, p1, p1};

  // Set the particle locations
  matrix_f locs( boost::extents[3][3] );

  // particle 1 at location (0,0,0)
  for( int i=0; i<3; i++ )
    locs[0][i] = 0;
  // particle 2 at location (1,0,0)
  locs[1][0] = 1;
  locs[1][1] = 0;
  locs[1][2] = 0;
  // particle 3 at location (0,1,1)
  locs[2][0] = 0;
  locs[2][1] = 1;
  locs[2][2] = 1;

  // Create the cluster and get the distances
  ParticleCluster const pclust( plist, locs );
  cube_f dists( boost::extents[3][3][3] );
  dists = pclust.getDistances();

  // assert the distances are correct
  // p1 - p1
  EXPECT_EQ( 0, dists[0][0][0] );
  EXPECT_EQ( 0, dists[0][0][1] );
  EXPECT_EQ( 0, dists[0][0][2] );
  // p1 - p2
  EXPECT_EQ( 1, dists[1][0][0] );
  EXPECT_EQ( 0, dists[1][0][1] );
  EXPECT_EQ( 0, dists[1][0][2] );
  // p1 - p3
  EXPECT_EQ( 0, dists[2][0][0] );
  EXPECT_EQ( 1, dists[2][0][1] );
  EXPECT_EQ( 1, dists[2][0][2] );
  // p2 - p1
  EXPECT_EQ( 1, dists[0][1][0] );
  EXPECT_EQ( 0, dists[0][1][1] );
  EXPECT_EQ( 0, dists[0][1][2] );
  // p2 - p2
  EXPECT_EQ( 0, dists[1][1][0] );
  EXPECT_EQ( 0, dists[1][1][1] );
  EXPECT_EQ( 0, dists[1][1][2] );
  // p2 - p3
  EXPECT_EQ( 1, dists[2][1][0] );
  EXPECT_EQ( 1, dists[2][1][1] );
  EXPECT_EQ( 1, dists[2][1][2] );
  // p3 - p1
  EXPECT_EQ( 0, dists[0][2][0] );
  EXPECT_EQ( 1, dists[0][2][1] );
  EXPECT_EQ( 1, dists[0][2][2] );
  // p3 - p2
  EXPECT_EQ( 1, dists[1][2][0] );
  EXPECT_EQ( 1, dists[1][2][1] );
  EXPECT_EQ( 1, dists[1][2][2] );
  // p3 - p3
  EXPECT_EQ( 0, dists[2][2][0] );
  EXPECT_EQ( 0, dists[2][2][1] );
  EXPECT_EQ( 0, dists[2][2][2] );
}

int main( int argc, char **argv )
{
  ::testing::InitGoogleTest( &argc, argv );
  return RUN_ALL_TESTS();
}
<commit_msg>Wrote test for particle energy barriers. Added outline functions for tests for particle and heun<commit_after>// main.cpp
// Main function for testing Maggie code
//
// Oliver W. Laslett 2015
// O.Laslett@soton.ac.uk
//
#include<iostream>
using std::cout;
using std::endl;

#include<cmath>
using std::cos;
using std::sin;

#include<maggie.hpp>
#include<gtest/gtest.h>
#include<gmock/gmock.h>
#include<boost/multi_array.hpp>
typedef boost::multi_array<float,1> array_f;
typedef boost::multi_array<float,2> matrix_f;
typedef boost::multi_array<float,3> cube_f;

#include<vector>

// Test construction of StocLLG
TEST(StochasticLLG, ContructAndDim)
{
  StocLLG llg( 1, 2, 3, 4, 5 );
  EXPECT_EQ( 3, llg.getDim() );
}

// Test deterministic part of StocLLG
TEST(StochasticLLG, Drift)
{
  // declare in and out arrays
  array_f out( boost::extents[3] );
  array_f in( boost::extents[3] );
  in[0] = 2;
  in[1] = 3;
  in[2] = 4;

  // Set up StocLLG and compute drift
  StocLLG llg( 2, 3, 1, 2, 3 );
  llg.computeDrift( out, in );

  // Are the solutions correct?
  EXPECT_EQ( -34, out[0] );
  EXPECT_EQ( -4, out[1] );
  EXPECT_EQ( 20, out[2] );
}

// Test the stochastic part of the StocLLG
TEST(StochasticLLG, Diffusion)
{
  // declare in and out arrays
  array_f in( boost::extents[3] );
  matrix_f out( boost::extents[3][3] );
  in[0] = 2;
  in[1] = 3;
  in[2] = 4;

  // set up the StocLLG and compute diffusion
  StocLLG llg( 2, 3, 1, 2, 3 );
  llg.computeDiffusion( out, in );

  // are the solutions correct?
  EXPECT_EQ( 150, out[0][0] );
  EXPECT_EQ( -28, out[0][1] );
  EXPECT_EQ( -54, out[0][2] );
  EXPECT_EQ( -44, out[1][0] );
  EXPECT_EQ( 120, out[1][1] );
  EXPECT_EQ( -68, out[1][2] );
  EXPECT_EQ( -42, out[2][0] );
  EXPECT_EQ( -76, out[2][1] );
  EXPECT_EQ( 78, out[2][2] );
}

// Test the RK4 algorithm
TEST(RK4, BasicCircle)
{
  // declare array for initial state
  array_f state( boost::extents[2] );

  float t=0; // initial time

  // fill the array state
  state[0] = 1;
  state[1] = 0;

  // Basic differential equation
  class ode : public LangevinEquation
  {
  public:
    ode() : LangevinEquation( 2 ) {}; // constructor

    // Differential equation
    virtual void computeDrift( array_f& out, array_f& in)
    {
      out[0] = in[1];
      out[1] = -in[0];
    }
  } testOde;

  // Create an instance of the RK4 integrator
  RK4 inte( testOde, state, t, 0.000001 );

  // Run the integrator for 2000 steps
  for( int i=0; i<500; i++ )
    inte.step();

  // Get the state and time
  state = inte.getState();
  t = inte.getTime();

  // Check the solution
  ASSERT_FLOAT_EQ( cos( t ), state[0] );
  ASSERT_FLOAT_EQ( -sin( t ), state[1] );
}

// Test for the Particles
TEST(Particle, SetSize)
{
  array_f uea( boost::extents[3] );
  uea[0] = 1;
  uea[1] = 0;
  uea[2] = 0;
  Particle p( 1, 2, 3, 4, 5, uea );
  ASSERT_FLOAT_EQ( 33.51032, p.getV() );
}

// Check that uea is a unit vector
TEST(Particle, UnitVector)
{
  array_f uea( boost::extents[3] );
  // Not a unit vector
  uea[0] = 0.3;
  uea[1] = 0.5;
  uea[2] = 0.7;
  ASSERT_THROW( Particle p( 1, 2, 3, 4, 5, uea ),
		std::invalid_argument );
  // is a unit vector
  uea[0] = 0.5773503;
  uea[1] = 0.5773503;
  uea[2] = 0.5773503;
  ASSERT_NO_THROW( Particle p( 1, 2, 3, 4, 5, uea ) );
}

// Check computation of the energy barriers
TEST(Particle, EnergyBarriers)
{
  array_f uea( boost::extents[3] );
  uea[0] = 0;
  uea[0] = 0;
  uea[0] = 1;
  Particle p( Constants::GYROMAG, 0.1, 3.5e5, 4e-9, 1e4, uea );

  // Cannot have reduced fields > 1 (i.e. H>H_k)
  ASSERT_THROW( p.alignedEnergyBarriers( 1.5 ),
                std::invalid_argument );

  // Check computation
  array_f ans( boost::extents[2] );
  ans = p.alignedEnergyBarriers( 0.2 );

  ASSERT_FLOAT_EQ( 2.14466058e-22, ans[0] );
  ASSERT_FLOAT_EQ( 4.82548631e-22, ans[1] );
}

// Check the computaiton of the transition rates
TEST(Particle, TransitionRates)
{
  // test here
}

// Test the particle cluster, are the distances correct?
TEST(ParticleCluster, Distances)
{
  // create list of 3 identical particles
  array_f uea( boost::extents[3] );
  uea[0] = 1.0;
  uea[1] = 0.0;
  uea[2] = 0.0;
  Particle p1( 1,2,3,4,5,uea );
  std::vector<Particle> plist = {p1, p1, p1};

  // Set the particle locations
  matrix_f locs( boost::extents[3][3] );

  // particle 1 at location (0,0,0)
  for( int i=0; i<3; i++ )
    locs[0][i] = 0;
  // particle 2 at location (1,0,0)
  locs[1][0] = 1;
  locs[1][1] = 0;
  locs[1][2] = 0;
  // particle 3 at location (0,1,1)
  locs[2][0] = 0;
  locs[2][1] = 1;
  locs[2][2] = 1;

  // Create the cluster and get the distances
  ParticleCluster const pclust( plist, locs );
  cube_f dists( boost::extents[3][3][3] );
  dists = pclust.getDistances();

  // assert the distances are correct
  // p1 - p1
  EXPECT_EQ( 0, dists[0][0][0] );
  EXPECT_EQ( 0, dists[0][0][1] );
  EXPECT_EQ( 0, dists[0][0][2] );
  // p1 - p2
  EXPECT_EQ( 1, dists[1][0][0] );
  EXPECT_EQ( 0, dists[1][0][1] );
  EXPECT_EQ( 0, dists[1][0][2] );
  // p1 - p3
  EXPECT_EQ( 0, dists[2][0][0] );
  EXPECT_EQ( 1, dists[2][0][1] );
  EXPECT_EQ( 1, dists[2][0][2] );
  // p2 - p1
  EXPECT_EQ( 1, dists[0][1][0] );
  EXPECT_EQ( 0, dists[0][1][1] );
  EXPECT_EQ( 0, dists[0][1][2] );
  // p2 - p2
  EXPECT_EQ( 0, dists[1][1][0] );
  EXPECT_EQ( 0, dists[1][1][1] );
  EXPECT_EQ( 0, dists[1][1][2] );
  // p2 - p3
  EXPECT_EQ( 1, dists[2][1][0] );
  EXPECT_EQ( 1, dists[2][1][1] );
  EXPECT_EQ( 1, dists[2][1][2] );
  // p3 - p1
  EXPECT_EQ( 0, dists[0][2][0] );
  EXPECT_EQ( 1, dists[0][2][1] );
  EXPECT_EQ( 1, dists[0][2][2] );
  // p3 - p2
  EXPECT_EQ( 1, dists[1][2][0] );
  EXPECT_EQ( 1, dists[1][2][1] );
  EXPECT_EQ( 1, dists[1][2][2] );
  // p3 - p3
  EXPECT_EQ( 0, dists[2][2][0] );
  EXPECT_EQ( 0, dists[2][2][1] );
  EXPECT_EQ( 0, dists[2][2][2] );
}

// Test run of the Heun and LLG algorithms
TEST( StocLLG, HeunIntegrationSolution )
{
  // write test for heun integration here.
}

int main( int argc, char **argv )
{
  ::testing::InitGoogleTest( &argc, argv );
  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>#include <string>
#include <memory>
#include <glog/logging.h>
#include "RelevanceCollectionManager.h"
#include "stopwords/StopwordFilter.h"
#include "tokenizer/Tokenizer.h"
#include "stemmer/StemmerIf.h"
#include "stemmer/PorterStemmer.h"
#include "DocumentProcessor.h"
#include "RelevanceServer.h"
#include "persistence/PersistenceService.h"
#include "persistence/SqlDb.h"
#include "persistence/RockHandle.h"
#include "persistence/CollectionDB.h"
#include "persistence/CollectionDBHandle.h"
#include "persistence/DocumentDB.h"
#include "persistence/DocumentDBHandle.h"
#include "persistence/CentroidDB.h"
#include "persistence/CentroidDBHandle.h"
#include "util.h"
#include <wangle/concurrent/CPUThreadPoolExecutor.h>
#include <wangle/concurrent/FutureExecutor.h>
#include <folly/futures/Future.h>
#include <thrift/lib/cpp2/server/ThriftServer.h>
#include <thrift/lib/cpp2/async/AsyncProcessor.h>

using namespace std;
using namespace folly;
using namespace persistence;
using stemmer::StemmerIf;
using stemmer::PorterStemmer;
using stopwords::StopwordFilter;
using stopwords::StopwordFilterIf;
using tokenizer::TokenizerIf;
using tokenizer::Tokenizer;
using wangle::CPUThreadPoolExecutor;
using wangle::FutureExecutor;
using util::UniquePointer;

shared_ptr<PersistenceServiceIf> getPersistence() {

  auto threadPool = std::make_shared<FutureExecutor<CPUThreadPoolExecutor>>(4);

  UniquePointer<RockHandleIf> centroidRock(
    (RockHandleIf*) new RockHandle("data/centroids")
  );
  UniquePointer<CentroidDBHandleIf> centroidDbHandle(
    (CentroidDBHandleIf*) new CentroidDBHandle(std::move(centroidRock))
  );
  shared_ptr<CentroidDBIf> centroidDb(
    (CentroidDBIf*) new CentroidDB(
      std::move(centroidDbHandle),
      make_shared<FutureExecutor<CPUThreadPoolExecutor>>(1)
    )
  );

  UniquePointer<RockHandleIf> docRock(
    (RockHandleIf*) new RockHandle("data/documents")
  );
  UniquePointer<DocumentDBHandleIf> docDbHandle(
    (DocumentDBHandleIf*) new DocumentDBHandle(std::move(docRock))
  );
  shared_ptr<DocumentDBIf> docDb(
    (DocumentDBIf*) new DocumentDB(
      std::move(docDbHandle),
      make_shared<FutureExecutor<CPUThreadPoolExecutor>>(1)
    )
  );

  UniquePointer<SqlDb> sqlDb(
    new SqlDb("data/collections.sqlite")
  );
  UniquePointer<CollectionDBHandleIf> collDbHandle(
    (CollectionDBHandleIf*) new CollectionDBHandle(std::move(sqlDb))
  );
  shared_ptr<CollectionDBIf> collDb(
    (CollectionDBIf*) new CollectionDB(
      std::move(collDbHandle),
      make_shared<FutureExecutor<CPUThreadPoolExecutor>>(1)
    )
  );

  shared_ptr<PersistenceServiceIf> persistence(
    (PersistenceServiceIf*) new PersistenceService(
      centroidDb, docDb, collDb
    )
  );
  return std::move(persistence);
}

shared_ptr<CentroidManager> getCentroidManager(shared_ptr<PersistenceServiceIf> persistence) {
  auto threadPool = make_shared<FutureExecutor<CPUThreadPoolExecutor>>(2);
  UniquePointer<CentroidUpdater> updater(
    new CentroidUpdater(
      persistence,
      threadPool
    )
  );
  return make_shared<CentroidManager>(
    std::move(updater), persistence
  );
}

int main() {
  LOG(INFO) << "start";
  thread t1([](){
    shared_ptr<TokenizerIf> tokenizer(
      (TokenizerIf*) new Tokenizer
    );
    shared_ptr<StemmerIf> stemmer(
      (StemmerIf*) new PorterStemmer
    );
    shared_ptr<StopwordFilterIf> stopwordFilter(
      (StopwordFilterIf*) new StopwordFilter
    );
    auto documentProcessor = make_shared<DocumentProcessor>(
      stemmer,
      tokenizer,
      stopwordFilter
    );
    auto persistence = getPersistence();
    auto centroidManager = getCentroidManager(persistence);

    auto manager = new RelevanceCollectionManager(
      persistence,
      centroidManager,
      documentProcessor
    );

    auto worker = new RelevanceWorker(
      persistence,
      centroidManager,
      manager
    );

    auto service = make_shared<RelevanceServer>(
      manager, worker
    );

    bool allowInsecureLoopback = true;
    string saslPolicy = "";
    auto server = new apache::thrift::ThriftServer(
      saslPolicy, allowInsecureLoopback
    );
    server->setInterface(service);
    auto port = 8097;
    server->setPort(port);
    LOG(INFO) << "listening on: " << port;
    server->serve();
  });
  t1.join();
  LOG(INFO) << "end";
}<commit_msg>make sure tables exist<commit_after>#include <string>
#include <memory>
#include <glog/logging.h>
#include "RelevanceCollectionManager.h"
#include "stopwords/StopwordFilter.h"
#include "tokenizer/Tokenizer.h"
#include "stemmer/StemmerIf.h"
#include "stemmer/PorterStemmer.h"
#include "DocumentProcessor.h"
#include "RelevanceServer.h"
#include "persistence/PersistenceService.h"
#include "persistence/SqlDb.h"
#include "persistence/RockHandle.h"
#include "persistence/CollectionDB.h"
#include "persistence/CollectionDBHandle.h"
#include "persistence/DocumentDB.h"
#include "persistence/DocumentDBHandle.h"
#include "persistence/CentroidDB.h"
#include "persistence/CentroidDBHandle.h"
#include "util.h"
#include <wangle/concurrent/CPUThreadPoolExecutor.h>
#include <wangle/concurrent/FutureExecutor.h>
#include <folly/futures/Future.h>
#include <thrift/lib/cpp2/server/ThriftServer.h>
#include <thrift/lib/cpp2/async/AsyncProcessor.h>

using namespace std;
using namespace folly;
using namespace persistence;
using stemmer::StemmerIf;
using stemmer::PorterStemmer;
using stopwords::StopwordFilter;
using stopwords::StopwordFilterIf;
using tokenizer::TokenizerIf;
using tokenizer::Tokenizer;
using wangle::CPUThreadPoolExecutor;
using wangle::FutureExecutor;
using util::UniquePointer;

shared_ptr<PersistenceServiceIf> getPersistence() {

  auto threadPool = std::make_shared<FutureExecutor<CPUThreadPoolExecutor>>(4);

  UniquePointer<RockHandleIf> centroidRock(
    (RockHandleIf*) new RockHandle("data/centroids")
  );
  UniquePointer<CentroidDBHandleIf> centroidDbHandle(
    (CentroidDBHandleIf*) new CentroidDBHandle(std::move(centroidRock))
  );
  shared_ptr<CentroidDBIf> centroidDb(
    (CentroidDBIf*) new CentroidDB(
      std::move(centroidDbHandle),
      make_shared<FutureExecutor<CPUThreadPoolExecutor>>(1)
    )
  );

  UniquePointer<RockHandleIf> docRock(
    (RockHandleIf*) new RockHandle("data/documents")
  );
  UniquePointer<DocumentDBHandleIf> docDbHandle(
    (DocumentDBHandleIf*) new DocumentDBHandle(std::move(docRock))
  );
  shared_ptr<DocumentDBIf> docDb(
    (DocumentDBIf*) new DocumentDB(
      std::move(docDbHandle),
      make_shared<FutureExecutor<CPUThreadPoolExecutor>>(1)
    )
  );

  UniquePointer<SqlDb> sqlDb(
    new SqlDb("data/collections.sqlite")
  );
  UniquePointer<CollectionDBHandleIf> collDbHandle(
    (CollectionDBHandleIf*) new CollectionDBHandle(std::move(sqlDb))
  );
  collDbHandle->ensureTables();
  shared_ptr<CollectionDBIf> collDb(
    (CollectionDBIf*) new CollectionDB(
      std::move(collDbHandle),
      make_shared<FutureExecutor<CPUThreadPoolExecutor>>(1)
    )
  );

  shared_ptr<PersistenceServiceIf> persistence(
    (PersistenceServiceIf*) new PersistenceService(
      centroidDb, docDb, collDb
    )
  );
  return std::move(persistence);
}

shared_ptr<CentroidManager> getCentroidManager(shared_ptr<PersistenceServiceIf> persistence) {
  auto threadPool = make_shared<FutureExecutor<CPUThreadPoolExecutor>>(2);
  UniquePointer<CentroidUpdater> updater(
    new CentroidUpdater(
      persistence,
      threadPool
    )
  );
  return make_shared<CentroidManager>(
    std::move(updater), persistence
  );
}

int main() {
  LOG(INFO) << "start";
  thread t1([](){
    shared_ptr<TokenizerIf> tokenizer(
      (TokenizerIf*) new Tokenizer
    );
    shared_ptr<StemmerIf> stemmer(
      (StemmerIf*) new PorterStemmer
    );
    shared_ptr<StopwordFilterIf> stopwordFilter(
      (StopwordFilterIf*) new StopwordFilter
    );
    auto documentProcessor = make_shared<DocumentProcessor>(
      stemmer,
      tokenizer,
      stopwordFilter
    );
    auto persistence = getPersistence();
    auto centroidManager = getCentroidManager(persistence);

    auto manager = new RelevanceCollectionManager(
      persistence,
      centroidManager,
      documentProcessor
    );

    auto worker = new RelevanceWorker(
      persistence,
      centroidManager,
      manager
    );

    auto service = make_shared<RelevanceServer>(
      manager, worker
    );

    bool allowInsecureLoopback = true;
    string saslPolicy = "";
    auto server = new apache::thrift::ThriftServer(
      saslPolicy, allowInsecureLoopback
    );
    server->setInterface(service);
    auto port = 8097;
    server->setPort(port);
    LOG(INFO) << "listening on: " << port;
    server->serve();
  });
  t1.join();
  LOG(INFO) << "end";
}<|endoftext|>


<commit_before>#include "slog/slog.h"
#include "sdl.h"
#include "utils.h"
#include "image.h"
#include "effects.h"
#include "inputhandler.h"
#include <SDL/SDL.h>

// bool handle_user_input(Image* image)
// {
// 	SDL_Event ev;
//     while (SDL_WaitEvent(&ev))
//     {
//         SLOG("Event occurs");
//         switch (ev.type)
//         {
//         case SDL_KEYDOWN:
//         {
//             switch (ev.key.keysym.sym) {
//                 case SDLK_1:
//                     BlackAndWhite(image);
//                     break;
//                 case SDLK_2:
//                     BrightnessBoost(image);
//                     break;
//                 case SDLK_ESCAPE:
//                     return false;
//                 default:
//                     break;
//             }
//         }
//         case SDL_QUIT:
//             break;
//         default:
//             break;
//         }
//
//         display_vfb(image->buffer, image->width, image->height);
//     }
//
//     return false;
// }

UserInput* user_input;

int main(int argc, char *argv[])
{
//     if (argc < 2)
//     {
//         SLOG("Usage: phi <image_path>");
//         return (1);
//     }
//
    std::string filename = "images/android.png";
//     std::string filename = argv[1];
    std::unique_ptr<Image>image(open_image(filename, IMAGE_TYPE::PNG));
    if (!image)
    {
        SLOG("Fail to open: %s", filename.c_str());
        return (1);
    }

    SLOG("Open image %s (width: %d) (height: %d)",
         filename.c_str(), image->width, image->height);

    if (!init_graphics(image->width, image->height))
    {
        SLOG("Fail to init sdl");
        return (2);
    }

    display_vfb(image->buffer, image->width, image->height);
    InputHandler handler(std::move(image));
    handler.Bind(SDLK_1, BlackAndWhite);
    handler.Bind(SDLK_2, BrightnessChange);

    user_input = new UserInput();
    user_input->AddHandler(&handler);
    user_input->Start();

    close_graphics();
    return 0;
}
<commit_msg>* Revert commandline image file<commit_after>#include "slog/slog.h"
#include "sdl.h"
#include "utils.h"
#include "image.h"
#include "effects.h"
#include "inputhandler.h"
#include <SDL/SDL.h>

// bool handle_user_input(Image* image)
// {
// 	SDL_Event ev;
//     while (SDL_WaitEvent(&ev))
//     {
//         SLOG("Event occurs");
//         switch (ev.type)
//         {
//         case SDL_KEYDOWN:
//         {
//             switch (ev.key.keysym.sym) {
//                 case SDLK_1:
//                     BlackAndWhite(image);
//                     break;
//                 case SDLK_2:
//                     BrightnessBoost(image);
//                     break;
//                 case SDLK_ESCAPE:
//                     return false;
//                 default:
//                     break;
//             }
//         }
//         case SDL_QUIT:
//             break;
//         default:
//             break;
//         }
//
//         display_vfb(image->buffer, image->width, image->height);
//     }
//
//     return false;
// }

UserInput* user_input;

int main(int argc, char *argv[])
{
    if (argc < 2)
    {
        SLOG("Usage: phi <image_path>");
        return (1);
    }

    std::string filename = argv[1];

    // DEBUG
    //std::string filename = "images/android.png";

    std::unique_ptr<Image>image(open_image(filename, IMAGE_TYPE::PNG));
    if (!image)
    {
        SLOG("Fail to open: %s", filename.c_str());
        return (1);
    }

    SLOG("Open image %s (width: %d) (height: %d)",
         filename.c_str(), image->width, image->height);

    if (!init_graphics(image->width, image->height))
    {
        SLOG("Fail to init sdl");
        return (2);
    }

    display_vfb(image->buffer, image->width, image->height);
    InputHandler handler(std::move(image));
    handler.Bind(SDLK_1, BlackAndWhite);
    handler.Bind(SDLK_2, BrightnessChange);

    user_input = new UserInput();
    user_input->AddHandler(&handler);
    user_input->Start();

    close_graphics();
    return 0;
}
<|endoftext|>


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

// TODO MEDIUM PRIORITY Under KDE (at least on Mageia) the way I have set
// up the widths of wxComboBox and wxTextCtrl and wxButton (in various
// controls in which these feature), where they are
// supposed to be the same height, they actually turn out to be slightly
// different heights. However even if I manually set them all to the same
// hard-coded height number, they still seem to come out different heights
// on KDE. It doesn't make a lot of sense.

// TODO MEDIUM PRIORITY Tooltips aren't showing on Windows.

/// TODO MEDIUM PRIORITY The database file should perhaps have a checksum to
// guard against its contents changing other than via the application.

// TODO HIGH PRIORITY Facilitate automatic checking for updates from user's
// machine, or else provide an easy way for users to sign up to a mailing
// list that keeps them informed about updates. Also note we had to manually
// add "SetOverwrite on" to the CMake NSIS template file, to ensure the
// generated installer will overwrite existing files when doing updates. This
// is not ideal.

// TODO HIGH PRIORITY Create a decent icon for the application. We want this
// in both .ico form (for Windows executable icon) and .xpm
// form (for icon for Frame). Note, when I exported my
// "token icon" using GIMP to .ico format, and later used this
// to create a double-clickable icon in Windows, only the text
// on the icon appeared, and the background image became
// transparent for some reason. Furthermore, when set as the
// large in-windows icon in the CPack/NSIS installer, the icon
// wasn't showing at all. Once decent icon is created, also make sure it is
// pulled into the wxBitmap in SetupWizard.

// TODO HIGH PRIORITY Make the GUI display acceptably on smaller screen
// i.e. laptop.

// TODO MEDIUM PRIORITY Startup time under Windows is really slow, even when
// compiled in Release mode.

// TODO MEDIUM PRIORITY Give user the option to export to CSV.

// TODO LOW PRIORITY Allow export/import to/from .qif (?) format.

// TODO MEDIUM PRIORITY Allow window borders to be dragged around, especially
// for DraftJournalListCtrl. This make it easier for users on laptops.

// TODO HIGH PRIORITY User guide. Write it using Sphinx.

// TODO HIGH PRIORITY Incorporate "make user_guide" into CMakeLists.txt with
// target that runs Sphinx to make user guide and then compile into application.
// The "make install" and "make package" targets also need to be adjusted
// so that help files will be installed to appropriate locations on the target
// system.

// TODO MEDIUM PRIORITY When the user creates a new file, ask if they want to
// create a shortcut to the file on their Desktop (assuming they didn't
// actually create the file in their desktop).

#include "app.hpp"
#include <wx/app.h>

wxIMPLEMENT_APP(dcm::App);
<commit_msg>Dummy commit - verifying that the fix referred to in the previous commit did indeed working (to fix tab traversal issue in TransactionCtrl re. buttons).<commit_after>/*
 * Copyright 2013 Matthew Harvey
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// TODO MEDIUM PRIORITY Under KDE (at least on Mageia) the way I have set
// up the widths of wxComboBox and wxTextCtrl and wxButton (in various
// controls in which these feature), where they are
// supposed to be the same height, they actually turn out to be slightly
// different heights. However even if I manually set them all to the same
// hard-coded height number, they still seem to come out different heights
// on KDE. It doesn't make a lot of sense.

// TODO MEDIUM PRIORITY Tooltips aren't showing on Windows.

/// TODO MEDIUM PRIORITY The database file should perhaps have a checksum to
// guard against its contents changing other than via the application.

// TODO HIGH PRIORITY Facilitate automatic checking for updates from user's
// machine, or else provide an easy way for users to sign up to a mailing
// list that keeps them informed about updates. Also note we had to manually
// add "SetOverwrite on" to the CMake NSIS template file, to ensure the
// generated installer will overwrite existing files when doing updates. This
// is not ideal.

// TODO HIGH PRIORITY Create a decent icon for the application. We want this
// in both .ico form (for Windows executable icon) and .xpm
// form (for icon for Frame). Note, when I exported my
// "token icon" using GIMP to .ico format, and later used this
// to create a double-clickable icon in Windows, only the text
// on the icon appeared, and the background image became
// transparent for some reason. Furthermore, when set as the
// large in-windows icon in the CPack/NSIS installer, the icon
// wasn't showing at all. Once decent icon is created, also make sure it is
// pulled into the wxBitmap in SetupWizard.

// TODO HIGH PRIORITY Make the GUI display acceptably on smaller screen
// i.e. laptop.

// TODO MEDIUM PRIORITY Startup time under Windows is really slow, even when
// compiled in Release mode.

// TODO MEDIUM PRIORITY Give user the option to export to CSV.

// TODO LOW PRIORITY Allow export/import to/from .qif (?) format.

// TODO MEDIUM PRIORITY Allow window borders to be dragged around, especially
// for DraftJournalListCtrl. This make it easier for users on laptops.

// TODO HIGH PRIORITY User guide. Write it using Sphinx.

// TODO HIGH PRIORITY Incorporate "make user_guide" into CMakeLists.txt with
// target that runs Sphinx to make user guide and then compile into application.
// The "make install" and "make package" targets also need to be adjusted
// so that help files will be installed to appropriate locations on the target
// system.

// TODO MEDIUM PRIORITY When the user creates a new file, ask if they want to
// create a shortcut to the file on their Desktop (assuming they didn't
// actually create the file in their desktop).

#include "app.hpp"
#include <wx/app.h>

wxIMPLEMENT_APP(dcm::App);
<|endoftext|>


<commit_before>#include "utils.hpp"
#include "node.hpp"

#include <iostream>
#include <cstdlib>

using namespace std;

int main(){

    srand(time(NULL));

    Node *root;

    for(int i=0; i<10; i++){
        root = new Node();

        cout << "A eq. gerada do node é (torça para ser pequena): ";
        root->print_node_d();
        cout << endl;

        vector<double> x = {double (random()%10) };

        cout << "Para x = " << x[0] << ", O valor da eq. do node é: " << root->eval(x) << endl << endl;
    }

    Node *copy = root->get_copy();

    cout << "cópia do ultimo:";
    copy->print_node_d();
    cout << endl;

    return 0;
}
<commit_msg>1.3 Atualizado para testar novas implementações<commit_after>//main.cpp
#include <iostream>
#include <cstdlib>
#include <vector>

#include "utils.hpp"
#include "individual.hpp"

using namespace std;

int main(){

    srand(time(NULL));

    vector< vector<double> > points;
    vector<double> x;
    vector<double> y;

    double temp;
    Individual *sujeito1 = new Individual();

    for (int i=0; i<2; i++){
        cin >> temp;
        x.push_back(temp);
        cin >> temp;
        y.push_back(temp);
    }

    points.push_back(x);
    points.push_back(y);

    cout << sujeito1->fitness(points) << endl;
    sujeito1->print_expression_d();
    cout << endl;

    return 0;
}
<|endoftext|>


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

#include "game.h"
#include "music.h"
#include "pilecode.h"
#include "data.h"
#include "levels.h"

#include <functional>
#include <fstream>

using namespace arctic;  // NOLINT
using namespace arctic::easy;  // NOLINT
using namespace pilecode; // NOLINT

class PlayerProfile {
public:
	World* GetSavedWorld(int level)
	{
		if (IsLevelAvailable(level)) {
			return level_[level]->Clone();
		}
		else {
			return nullptr;
		}
	}

	void UpdateLevel(int level, World* world)
	{
		if (level < level_.size()) {
			level_[level] = std::shared_ptr<World>(world);
		}
		SaveToDisk();
	}

	void AddLevel(int level, World* world)
	{
		if (level == level_.size()) {
			level_.emplace_back(world);
		}
		SaveToDisk();
	}

	void SaveTo(std::ostream& s) const
	{
		Save<size_t>(s, level_.size());
		for (const auto& l : level_) {
			l->SaveTo(s);
		}
	}

	void LoadFrom(std::istream& s)
	{
		size_t levels;
		Load<size_t>(s, levels);
		level_.resize(levels);
		for (auto& l : level_) {
			l.reset(new World());
			l->LoadFrom(s);
		}
	}

	void SaveToDisk() const
	{
		std::ofstream ofs("profile.sav");
		SaveTo(ofs);
	}

	void LoadFromDisk()
	{
		std::ifstream ifs("profile.sav");
		if (ifs.good()) {
			LoadFrom(ifs);
		}
	}

	bool IsLevelAvailable(int level) const
	{
		return (size_t)level < level_.size();
	}

	int LastAvailableLevel() const
	{
		return int(level_.empty() ? 0 : level_.size() - 1);
	}
private:
	std::vector<std::shared_ptr<World>> level_;
};

PlayerProfile g_profile;

class IScene {
public:
	virtual ~IScene() {}
	virtual IScene* Run() = 0;
};

class GameScene : public IScene {
public:
	GameScene(int _level, int _prevLevel)
		: level_(_level)
		, prevLevel_(_prevLevel)
	{}

	IScene* Run() override;

private:
	bool exiting = false;
	int level_ = 0;
	int prevLevel_ = 0;
};

class EditorScene : public IScene {
public:
	explicit EditorScene(int _level)
		: level_(_level)
	{}

	IScene* Run() override;

private:
	bool exiting = false;
	int level_ = 0;
	int prevLevel_ = 0;
};

IScene* GameScene::Run()
{
	Game game;
	if (level_ >= 0) {
		game.Start(level_, prevLevel_, g_profile.LastAvailableLevel(), g_profile.GetSavedWorld(level_));
		if (!g_profile.IsLevelAvailable(level_)) {
			g_profile.AddLevel(level_, game.GetInitWorld());
		}
	}
	else {
		game.Start(level_, prevLevel_, level_, nullptr);
	}
	prevLevel_ = level_;

	while (true) {
		if (!game.Control()) {
			exiting = true;
			break;
		}

		game.Update();
		game.Render();
		if (game.IsComplete()) {
			sfx::g_positive.Play(0.3f);
			level_++;
			break;
		}

		int nextLevel = level_;
		if (game.GetNextLevel() < level_) {
			nextLevel = (level_ > 0 ? level_ - 1 : level_);
		}
		if (game.GetNextLevel() > level_) {
			nextLevel = (level_ + 1) % LevelsCount();
		}
		if (nextLevel != level_) {
			if (g_profile.IsLevelAvailable(nextLevel)) {
				level_ = nextLevel;
				break;
			}
			else {
				sfx::g_negative2.Play();
			}
		}

		if (IsKeyOnce(kKeyF4)) {
			return new EditorScene(level_);
		}

#ifdef DEV_MODE
		if (IsKeyOnce(kKeyF8)) {
			level = -1;
			break;
		}
		if (IsKeyOnce(kKeyF9)) {
			level++;
			break;
		}
		if (IsKeyOnce(kKeyF10)) {
			level--;
			break;
		}
#endif

		UpdateMusic();
	}

	g_profile.UpdateLevel(prevLevel_, game.GetInitWorld());
	game.Finish(level_, prevLevel_);

	if (exiting) {
		return nullptr;
	}
	else {
		return new GameScene(level_, prevLevel_);
	}
}

IScene* EditorScene::Run()
{
	Game game;
	if (level_ >= 0) {
		game.StartWithEditor(level_, level_, g_profile.LastAvailableLevel(), g_profile.GetSavedWorld(level_));
	}
	else {
		game.StartWithEditor(level_, level_, level_, nullptr);
	}

	while (true) {
		if (!game.Control()) {
			exiting = true;
			break;
		}

		game.Update();
		game.Render();

		int nextLevel = level_;
		if (game.GetNextLevel() < level_) {
			nextLevel = (level_ > 0 ? level_ - 1 : level_);
		}
		if (game.GetNextLevel() > level_) {
			nextLevel = (level_ + 1) % LevelsCount();
		}
		if (nextLevel != level_) {
			level_ = nextLevel;
			break;
		}

		UpdateMusic();
	}

	g_profile.UpdateLevel(prevLevel_, game.GetInitWorld());
	game.Finish(level_, prevLevel_);

	if (exiting) {
		return new GameScene(level_, level_);
	}
	else {
		return new EditorScene(level_);
	}
}

void DrawIntro()
{
	DrawWithFixedAlphaBlend(image::g_background[2], 0, 0, Ui8(255));
	AlphaDraw(image::g_pilecode, 0, 0);
}

void Intro()
{
	double transitionSec = 1.2f;

	// Show Intro
	double startTime = ae::Time();
	while (true) {
		if (ui::StopAnimationKey()) {
			break;
		}
		DrawIntro();
		Ui8 brightness = Ui8(ae::Clamp(float((ae::Time() - startTime) * 255 / transitionSec), 0.0f, 255.0f));
		FilterBrightness(ae::GetEngine()->GetBackbuffer(), brightness);
		ae::ShowFrame();
		Sleep(0.010);
	}

	// Hide intro
	double showedTime = ae::Time() - startTime;
	double finishTime = ae::Time() + std::min(transitionSec, showedTime);
	while (ae::Time() < finishTime) {
		DrawIntro();
		Ui8 brightness = Ui8(ae::Clamp(float((finishTime - ae::Time()) * 255 / transitionSec), 0.0f, 255.0f));
		FilterBrightness(ae::GetEngine()->GetBackbuffer(), brightness);
		ae::ShowFrame();
		Sleep(0.010);
	}
	Sleep(0.100);
}

void EasyMain()
{
	// Init system stuff
	srand((int)time(nullptr));
	ResizeScreen(screen::w, screen::h);

	// Init game
	PreInitData();
	InitData();
	g_profile.LoadFromDisk();

	Intro();

	// Run game
	UpdateMusic();
	IScene* scene = new GameScene(g_profile.LastAvailableLevel(), 0);
	while (scene) {
		IScene* nextScene = scene->Run();
		delete scene;
		scene = nextScene;
	}
}
<commit_msg>fix DEV_MODE macro<commit_after>// The MIT License(MIT)
//
// Copyright 2017 bladez-fate
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.

#include "game.h"
#include "music.h"
#include "pilecode.h"
#include "data.h"
#include "levels.h"

#include <functional>
#include <fstream>

using namespace arctic;  // NOLINT
using namespace arctic::easy;  // NOLINT
using namespace pilecode; // NOLINT

class PlayerProfile {
public:
	World* GetSavedWorld(int level)
	{
		if (IsLevelAvailable(level)) {
			return level_[level]->Clone();
		}
		else {
			return nullptr;
		}
	}

	void UpdateLevel(int level, World* world)
	{
		if (level < level_.size()) {
			level_[level] = std::shared_ptr<World>(world);
		}
		SaveToDisk();
	}

	void AddLevel(int level, World* world)
	{
		if (level == level_.size()) {
			level_.emplace_back(world);
		}
		SaveToDisk();
	}

	void SaveTo(std::ostream& s) const
	{
		Save<size_t>(s, level_.size());
		for (const auto& l : level_) {
			l->SaveTo(s);
		}
	}

	void LoadFrom(std::istream& s)
	{
		size_t levels;
		Load<size_t>(s, levels);
		level_.resize(levels);
		for (auto& l : level_) {
			l.reset(new World());
			l->LoadFrom(s);
		}
	}

	void SaveToDisk() const
	{
		std::ofstream ofs("profile.sav");
		SaveTo(ofs);
	}

	void LoadFromDisk()
	{
		std::ifstream ifs("profile.sav");
		if (ifs.good()) {
			LoadFrom(ifs);
		}
	}

	bool IsLevelAvailable(int level) const
	{
		return (size_t)level < level_.size();
	}

	int LastAvailableLevel() const
	{
		return int(level_.empty() ? 0 : level_.size() - 1);
	}
private:
	std::vector<std::shared_ptr<World>> level_;
};

PlayerProfile g_profile;

class IScene {
public:
	virtual ~IScene() {}
	virtual IScene* Run() = 0;
};

class GameScene : public IScene {
public:
	GameScene(int _level, int _prevLevel)
		: level_(_level)
		, prevLevel_(_prevLevel)
	{}

	IScene* Run() override;

private:
	bool exiting = false;
	int level_ = 0;
	int prevLevel_ = 0;
};

class EditorScene : public IScene {
public:
	explicit EditorScene(int _level)
		: level_(_level)
	{}

	IScene* Run() override;

private:
	bool exiting = false;
	int level_ = 0;
	int prevLevel_ = 0;
};

IScene* GameScene::Run()
{
	Game game;
	if (level_ >= 0) {
		game.Start(level_, prevLevel_, g_profile.LastAvailableLevel(), g_profile.GetSavedWorld(level_));
		if (!g_profile.IsLevelAvailable(level_)) {
			g_profile.AddLevel(level_, game.GetInitWorld());
		}
	}
	else {
		game.Start(level_, prevLevel_, level_, nullptr);
	}
	prevLevel_ = level_;

	while (true) {
		if (!game.Control()) {
			exiting = true;
			break;
		}

		game.Update();
		game.Render();
		if (game.IsComplete()) {
			sfx::g_positive.Play(0.3f);
			level_++;
			break;
		}

		int nextLevel = level_;
		if (game.GetNextLevel() < level_) {
			nextLevel = (level_ > 0 ? level_ - 1 : level_);
		}
		if (game.GetNextLevel() > level_) {
			nextLevel = (level_ + 1) % LevelsCount();
		}
		if (nextLevel != level_) {
			if (g_profile.IsLevelAvailable(nextLevel)) {
				level_ = nextLevel;
				break;
			}
			else {
				sfx::g_negative2.Play();
			}
		}

		if (IsKeyOnce(kKeyF4)) {
			return new EditorScene(level_);
		}

#ifdef DEV_MODE
		if (IsKeyOnce(kKeyF8)) {
			level_ = -1;
			break;
		}
		if (IsKeyOnce(kKeyF9)) {
			level_++;
			break;
		}
		if (IsKeyOnce(kKeyF10)) {
			level_--;
			break;
		}
#endif

		UpdateMusic();
	}

	g_profile.UpdateLevel(prevLevel_, game.GetInitWorld());
	game.Finish(level_, prevLevel_);

	if (exiting) {
		return nullptr;
	}
	else {
		return new GameScene(level_, prevLevel_);
	}
}

IScene* EditorScene::Run()
{
	Game game;
	if (level_ >= 0) {
		game.StartWithEditor(level_, level_, g_profile.LastAvailableLevel(), g_profile.GetSavedWorld(level_));
	}
	else {
		game.StartWithEditor(level_, level_, level_, nullptr);
	}

	while (true) {
		if (!game.Control()) {
			exiting = true;
			break;
		}

		game.Update();
		game.Render();

		int nextLevel = level_;
		if (game.GetNextLevel() < level_) {
			nextLevel = (level_ > 0 ? level_ - 1 : level_);
		}
		if (game.GetNextLevel() > level_) {
			nextLevel = (level_ + 1) % LevelsCount();
		}
		if (nextLevel != level_) {
			level_ = nextLevel;
			break;
		}

		UpdateMusic();
	}

	g_profile.UpdateLevel(prevLevel_, game.GetInitWorld());
	game.Finish(level_, prevLevel_);

	if (exiting) {
		return new GameScene(level_, level_);
	}
	else {
		return new EditorScene(level_);
	}
}

void DrawIntro()
{
	DrawWithFixedAlphaBlend(image::g_background[2], 0, 0, Ui8(255));
	AlphaDraw(image::g_pilecode, 0, 0);
}

void Intro()
{
	double transitionSec = 1.2f;

	// Show Intro
	double startTime = ae::Time();
	while (true) {
		if (ui::StopAnimationKey()) {
			break;
		}
		DrawIntro();
		Ui8 brightness = Ui8(ae::Clamp(float((ae::Time() - startTime) * 255 / transitionSec), 0.0f, 255.0f));
		FilterBrightness(ae::GetEngine()->GetBackbuffer(), brightness);
		ae::ShowFrame();
		Sleep(0.010);
	}

	// Hide intro
	double showedTime = ae::Time() - startTime;
	double finishTime = ae::Time() + std::min(transitionSec, showedTime);
	while (ae::Time() < finishTime) {
		DrawIntro();
		Ui8 brightness = Ui8(ae::Clamp(float((finishTime - ae::Time()) * 255 / transitionSec), 0.0f, 255.0f));
		FilterBrightness(ae::GetEngine()->GetBackbuffer(), brightness);
		ae::ShowFrame();
		Sleep(0.010);
	}
	Sleep(0.100);
}

void EasyMain()
{
	// Init system stuff
	srand((int)time(nullptr));
	ResizeScreen(screen::w, screen::h);

	// Init game
	PreInitData();
	InitData();
	g_profile.LoadFromDisk();

	Intro();

	// Run game
	UpdateMusic();
	IScene* scene = new GameScene(g_profile.LastAvailableLevel(), 0);
	while (scene) {
		IScene* nextScene = scene->Run();
		delete scene;
		scene = nextScene;
	}
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include<queue>
#include <math.h>
//#include <algoritm.h>

using namespace std;

//TO DO:
//* make queueing functions
//* make seach function
//* figure out how to que all things

struct Matrix{
    vector < vector <int> > problem;
    vector < vector <int> > goal;
    int fn;
    int gn;
    int hn;
};

class Compare_Values    {
    public:
        bool operator()(Matrix& M1, Matrix& M2){
            if(M1.fn != 0){
                if(M1.fn < M2.fn) return true;
            }
            else{
                if(M1.gn < M2.gn) return true;
            }
            return false;
        }
};

//OPERATORS: i and j are row and column values you want to move blank to
Matrix UP(Matrix& M, int i, int j){
    swap(M.problem[i][j], M.problem[i+1][j]);
    M.gn= M.gn =1;
    return M;
}

Matrix DN(Matrix& M, int i, int j){
    swap(M.problem[i][j],M.problem[i-1][j]);
    M.gn = M.gn+1;
    return M;
}

Matrix RT(Matrix& M, int i, int j){
    swap(M.problem[i][j], M.problem[i][j-1]);
    M.gn = M.gn+1;
    return M;
}

Matrix LF(Matrix& M, int i, int j){
    swap(M.problem[i][j], M.problem[i][j+1]);
    M.gn = M.gn+1;
    return M;
}

//function to expand nodes with operators (current node, operators)
//returns queue of matricies (all possible ways to move the blank)
vector< Matrix >  expand(Matrix M/*, Matrix& M1, Matrix& M2, Matrix& M3, Matrix& M4*/){
    vector< Matrix > vec;

    Matrix M1;
    M1.problem.push_back(std::vector<int>(3, 1));
    M1.problem.push_back(std::vector<int>(3, 2));
    M1.problem.push_back(std::vector<int>(3, 3));

    Matrix M2;
    M2.problem.push_back(std::vector<int>(3, 1));
    M2.problem.push_back(std::vector<int>(3, 2));
    M2.problem.push_back(std::vector<int>(3, 3));

    Matrix M3;
    M3.problem.push_back(std::vector<int>(3, 1));
    M3.problem.push_back(std::vector<int>(3, 2));
    M3.problem.push_back(std::vector<int>(3, 3));

    Matrix M4;
    M4.problem.push_back(std::vector<int>(3, 1));
    M4.problem.push_back(std::vector<int>(3, 2));
    M4.problem.push_back(std::vector<int>(3, 3));

    //make 4 copies of matrix M that we can store in the que
    M1 = M;

    M2 = M;

    M3 = M;

    M4 = M;

    //find which indicies the blank is at
    int row,column;
    for(int i = 0; i < 3; i++){
        for(int j = 0; j < 3; j++){
            if(M.problem[i][j] == 0){
                row = i;
                column = j;
                break;
            }
        }
    }

    //for each indicie that the blank is at, swap with the values it can swap with
    if(column == 2 && row == 0){
        vec.push_back(LF(M1,row, column-1));
        vec.push_back(DN(M2,row+1,column));
    }
    else if(column == 2 && row == 1){
        vec.push_back(UP(M1,row-1,column));
        vec.push_back(LF(M2, row, column-1));
        vec.push_back(DN(M3, row+1, column));
    }
    else if(column ==2 && row ==2){
        vec.push_back(UP(M1, row-1, column));
        vec.push_back(LF(M2, row, column -1));
    }
    else if(column == 0 && row == 0){
        vec.push_back(RT(M1,row, column+1));
        vec.push_back(DN(M2,row+1,column));
    }
    else if(column == 0 && row == 1){
        vec.push_back(UP(M1,row-1,column));
        vec.push_back(RT(M2, row, column+1));
        vec.push_back(DN(M3, row+1, column));
    }
    else if(column ==0 && row ==2){
        vec.push_back(UP(M1, row-1, column));
        vec.push_back(RT(M2, row, column+1));
    }
    else if(column == 1 && row == 0){
        vec.push_back(LF(M1,row, column-1));
        vec.push_back(DN(M2,row+1,column));
        vec.push_back(RT(M3, row, column+1));
    }
    else if(column == 1 && row == 1){
        vec.push_back(UP(M1,row-1,column));
        vec.push_back(LF(M2, row, column-1));
        vec.push_back(DN(M3, row+1, column));
        vec.push_back(RT(M4, row, column+1));
    }
    else if(column ==1 && row ==2){
        vec.push_back(UP(M1, row-1, column));
        vec.push_back(LF(M2, row, column -1));
        vec.push_back(RT(M3, row, column + 1));
    }

    //return the vector queue
    return vec;
}

//Uniform Cost Search function (nodes(queue), expand)
//returns a node in order of g(n)
priority_queue<Matrix, vector<Matrix>, Compare_Values> UC(priority_queue <Matrix, vector<Matrix>, Compare_Values>  &pq, vector<Matrix> expand){
    for(int i = 0; i < expand.size(); i++)
        pq.push(expand[i]);

    return pq;
}

//A* Mattahatan Search Function
//returns a queue in order of f(n) = g(n) + f(n)

//A* Misplaced Tile function
//returns a queue in order of f(n) = g(n) + f(n)

//general search function to use with search algorithms
Matrix generalSearch(Matrix M, priority_queue<Matrix, vector<Matrix>, Compare_Values> queueing(priority_queue <Matrix, vector<Matrix>, Compare_Values>),
                         vector<Matrix> expand( Matrix ));

//function to check if the matrix matches the goal state
bool checkIfGoal(vector < vector<int> >  M);

int main(){

    Matrix M;
    //make goal matrix to visualize
    M.goal.push_back(std::vector<int>(3, 1));
    M.goal.push_back(std::vector<int>(3, 2));
    M.goal.push_back(std::vector<int>(3, 3));

    //These are the copy matrices used in expand function
    /*Matrix M1;
    M1.problem.push_back(std::vector<int>(3, 1));
    M1.problem.push_back(std::vector<int>(3, 2));
    M1.problem.push_back(std::vector<int>(3, 3));

    Matrix M2;
    M2.problem.push_back(std::vector<int>(3, 1));
    M2.problem.push_back(std::vector<int>(3, 2));
    M2.problem.push_back(std::vector<int>(3, 3));

    Matrix M3;
    M3.problem.push_back(std::vector<int>(3, 1));
    M3.problem.push_back(std::vector<int>(3, 2));
    M3.problem.push_back(std::vector<int>(3, 3));

    Matrix M4;
    M4.problem.push_back(std::vector<int>(3, 1));
    M4.problem.push_back(std::vector<int>(3, 2));
    M4.problem.push_back(std::vector<int>(3, 3));
    */

    //create M's goal state
    M.goal[0][0]=1;
    M.goal[0][1]=2;
    M.goal[0][2]=3;
    M.goal[1][0]=4;
    M.goal[1][1]=5;
    M.goal[1][2]=6;
    M.goal[2][0]=7;
    M.goal[2][1]=8;
    M.goal[2][2]=0;

    cout << "Outputting goal matrix: " << endl;
    int a,b;
    for(b = 0; b < 3; ++b)
    {
        for(a = 0; a < 3; ++a)
            cout << M.goal[b][a] << "\t" ;
        cout<<endl;
    }

    //make matrix for 8puzzle
    M.problem.push_back(std::vector<int>(3, 1));
    M.problem.push_back(std::vector<int>(3, 2));
    M.problem.push_back(std::vector<int>(3, 3));

    M.problem[0][0]=1;
    M.problem[0][1]=3;
    M.problem[0][2]=2;
    M.problem[1][0]=4;
    M.problem[1][1]=0;
    M.problem[1][2]=6;
    M.problem[2][0]=7;
    M.problem[2][1]=5;
    M.problem[2][2]=8;

    cout << "Outputting regular matrix: " << endl;
    int c,d;
    for(d = 0; d < 3; ++d)
    {
        for(c = 0; c < 3; ++c)
            cout << M.problem[d][c] << "\t" ;
        cout<<endl;
    }

    //queue of all the possible expansions of M
    vector<Matrix> vec = expand(M/*, M1, M2, M3, M4*/);

    //cout << "Outputting gn values: " << M1.gn << ", " << M2.gn << ", " << M3.gn << ", " << M4.gn << endl;

    cout << "Outputting the queue: " << endl;
    int i,e,f;
    for(i = 0; i < vec.size(); i++)
    {
        for(f = 0; f < 3; ++f)
        {
            for(e = 0; e < 3; ++e)
                cout << vec.at(i).problem[f][e] << "\t" ;
            cout<<endl;
        }
        cout << endl;
    }
    //checking if goal matches matrix with function
    cout << "8 Tile matches goal state? " << checkIfGoal(M.problem) << endl;

    Matrix UCS;

    UCS.problem.push_back(std::vector<int>(3, 1));
    UCS.problem.push_back(std::vector<int>(3, 2));
    UCS.problem.push_back(std::vector<int>(3, 3));

    UCS.goal.push_back(std::vector<int>(3, 1));
    UCS.goal.push_back(std::vector<int>(3, 2));
    UCS.goal.push_back(std::vector<int>(3, 3));

    priority_queue<Matrix, vector<Matrix>, Compare_Values> pq;

    UCS = generalSearch(M, UC, expand);
    //search.problem  = generalSearch(M).problem;
    //search.goal = M.goal;
    //search.fn = generalSearch(M).fn;

    return 0;
}

bool checkIfGoal(vector <vector<int> > M)
{
    if(M[0][0] ==1 && M[0][1] ==2 && M[0][2] ==3 && M[1][0] ==4 && M[1][1] == 5 && M[1][2] == 6 && M[2][0] == 7 && M[2][1] == 8 && M[2][2] == 0)
        return true;
    return false;
}

Matrix generalSearch(Matrix M, priority_queue<Matrix, vector<Matrix>, Compare_Values> queueing(priority_queue <Matrix, vector<Matrix>, Compare_Values>),
                         vector<Matrix> expand( Matrix )){
    priority_queue <Matrix, vector<Matrix>, Compare_Values> nodes;
    nodes.push(M);
    do{
        if(nodes.empty()){
            cout <<  "Failure. There is no solution to this problem." << endl;
            break;
        }
        Matrix node;
        node.problem.push_back(std::vector<int>(3, 1));
        node.problem.push_back(std::vector<int>(3, 2));
        node.problem.push_back(std::vector<int>(3, 3));

        node.goal.push_back(std::vector<int>(3, 1));
        node.goal.push_back(std::vector<int>(3, 2));
        node.goal.push_back(std::vector<int>(3, 3));

        node = nodes.top();

        cout << "Nodes is now: " << endl;
        int e,f;
        for(f = 0; f < 3; ++f){
            for(e = 0; e < 3; ++e)
                cout << nodes.top().problem[f][e] << "\t" ;
            cout<<endl;
        }
        if(checkIfGoal(node.problem))
            return nodes.top();
        nodes = queueing(nodes, expand(node));
    }while(!nodes.empty());

}

<commit_msg>changed to void funtions bc cannot put function in function<commit_after>#include <iostream>
#include <vector>
#include<queue>
#include <math.h>
//#include <algoritm.h>

using namespace std;

//TO DO:
//* make queueing functions
//* make seach function
//* figure out how to que all things

struct Matrix{
    vector < vector <int> > problem;
    vector < vector <int> > goal;
    int gn;
    int hn;
};

class Compare_Values    {
    public:
        bool operator()(Matrix& M1, Matrix& M2){
            if(M1.hn != 0){
                if(M1.hn < M2.hn) return true;
            }
            else if(M1.hn == 0){
                if(M1.gn < M2.gn) return true;
            }
            return false;
        }
};

//A* Mattahatan Search Function
//calculates the hn value
void mat(Matrix& M){
    for(int i = 0; i < 3; i++){
        for(int j=0; j<3; j++){
            int val = M.problem[i][j];
            if(val != 0){
                int goal_row = (val - 1) / 3;
                int goal_column = (val - 1) % 3;
                M.hn = M.hn + abs(i - goal_row) + abs(j - goal_column);
            }
        }
    }
}

//A* Misplaced Tile function
//calculates the misplaced tile hn value
void misplaced_tile(Matrix& M){
    if(M.problem[0][0] != 1) M.hn++;
    if(M.problem[0][1] != 2) M.hn++;
    if(M.problem[0][2] != 3) M.hn++;
    if(M.problem[1][0] != 4) M.hn++;
    if(M.problem[1][1] != 5) M.hn++;
    if(M.problem[1][2] != 6) M.hn++;
    if(M.problem[2][0] != 7) M.hn++;
    if(M.problem[2][1] != 8) M.hn++;
    if(M.problem[2][2] != 0) M.hn++;
}

//OPERATORS: i and j are row and column values you want to move blank to
Matrix UP(Matrix& M, int i, int j, int choice){
    swap(M.problem[i][j], M.problem[i+1][j]);
    M.gn= M.gn =1;
    if(choice == 1)
        M.hn = 0;
    if(choice == 2)
        misplaced_tile(M);
    if(choice == 3)
        mat(M);
    return M;
}

Matrix DN(Matrix& M, int i, int j, int choice){
    swap(M.problem[i][j],M.problem[i-1][j]);
    M.gn = M.gn+1;
    return M;
}

Matrix RT(Matrix& M, int i, int j, int choice){
    swap(M.problem[i][j], M.problem[i][j-1]);
    M.gn = M.gn+1;
    return M;
}

Matrix LF(Matrix& M, int i, int j, int choice){
    swap(M.problem[i][j], M.problem[i][j+1]);
    M.gn = M.gn+1;
    return M;
}

//function to expand nodes with operators (current node, operators)
//returns queue of matricies (all possible ways to move the blank)
void expand(Matrix M, priority_queue<Matrix, vector<Matrix>, Compare_Values> &nodes, int                choice){

    Matrix M1;
    M1.problem.push_back(std::vector<int>(3, 1));
    M1.problem.push_back(std::vector<int>(3, 2));
    M1.problem.push_back(std::vector<int>(3, 3));

    Matrix M2;
    M2.problem.push_back(std::vector<int>(3, 1));
    M2.problem.push_back(std::vector<int>(3, 2));
    M2.problem.push_back(std::vector<int>(3, 3));

    Matrix M3;
    M3.problem.push_back(std::vector<int>(3, 1));
    M3.problem.push_back(std::vector<int>(3, 2));
    M3.problem.push_back(std::vector<int>(3, 3));

    Matrix M4;
    M4.problem.push_back(std::vector<int>(3, 1));
    M4.problem.push_back(std::vector<int>(3, 2));
    M4.problem.push_back(std::vector<int>(3, 3));

    //make 4 copies of matrix M that we can store in the que
    M1 = M;

    M2 = M;

    M3 = M;

    M4 = M;

    //find which indicies the blank is at
    int row,column;
    for(int i = 0; i < 3; i++){
        for(int j = 0; j < 3; j++){
            if(M.problem[i][j] == 0){
                row = i;
                column = j;
                break;
            }
        }
    }

    //for each indicie that the blank is at, swap with the values it can swap with
    if(column == 2 && row == 0){
        nodes.push(LF(M1,row, column-1, choice));
        nodes.push(DN(M2,row+1,column, choice));
    }
    else if(column == 2 && row == 1){
        nodes.push(UP(M1,row-1,column, choice));
        nodes.push(LF(M2, row, column-1, choice));
        nodes.push(DN(M3, row+1, column, choice));
    }
    else if(column ==2 && row ==2){
        nodes.push(UP(M1, row-1, column, choice));
        nodes.push(LF(M2, row, column -1,choice));
    }
    else if(column == 0 && row == 0){
        nodes.push(RT(M1,row, column+1,choice));
        nodes.push(DN(M2,row+1,column, choice));
    }
    else if(column == 0 && row == 1){
        nodes.push(UP(M1,row-1,column,choice));
        nodes.push(RT(M2, row, column+1, choice));
        nodes.push(DN(M3, row+1, column, choice));
    }
    else if(column ==0 && row ==2){
        nodes.push(UP(M1, row-1, column, choice));
        nodes.push(RT(M2, row, column+1, choice));
    }
    else if(column == 1 && row == 0){
        nodes.push(LF(M1,row, column-1, choice));
        nodes.push(DN(M2,row+1,column, choice));
        nodes.push(RT(M3, row, column+1, choice));
    }
    else if(column == 1 && row == 1){
        nodes.push(UP(M1,row-1,column, choice));
        nodes.push(LF(M2, row, column-1, choice));
        nodes.push(DN(M3, row+1, column, choice));
        nodes.push(RT(M4, row, column+1, choice));
    }
    else if(column ==1 && row ==2){
        nodes.push(UP(M1, row-1, column, choice));
        nodes.push(LF(M2, row, column -1, choice));
        nodes.push(RT(M3, row, column + 1, choice));
    }

    //return the vector queue
}

//Uniform Cost Search function (nodes(queue), expand)
//returns a node in order of g(n)
priority_queue<Matrix, vector<Matrix>, Compare_Values> UC(priority_queue <Matrix, vector<Matrix>, Compare_Values>  &pq, vector<Matrix> expand){
    for(int i = 0; i < expand.size(); i++)
        pq.push(expand[i]);

    return pq;
}

//general search function to use with search algorithms
void generalSearch(Matrix M, int choice)
    if(choice == 1)
        M.hn = 0;
    else if(choice == 2)
        misplaced_tile(M);
    else if(choice == 3)
        M.hn = mat(M);
    priority_queue <Matrix, vector<Matrix>, Compare_Values> nodes;
    nodes.push(M);
    do{
        if(nodes.empty()){
            cout <<  "Failure. There is no solution to this problem." << endl;
            break;
        }
        Matrix node;
        node.problem.push_back(std::vector<int>(3, 1));
        node.problem.push_back(std::vector<int>(3, 2));
        node.problem.push_back(std::vector<int>(3, 3));

        node.goal.push_back(std::vector<int>(3, 1));
        node.goal.push_back(std::vector<int>(3, 2));
        node.goal.push_back(std::vector<int>(3, 3));

        node = nodes.top();

        cout << "Nodes is now: " << endl;
        int e,f;
        for(f = 0; f < 3; ++f){
            for(e = 0; e < 3; ++e)
                cout << nodes.top().problem[f][e] << "\t" ;
            cout<<endl;
        }
        if(checkIfGoal(node.problem)){
            for(int f = 0; f < 3; ++f)
            {
                for(int e = 0; e < 3; ++e)
                    cout << node.problem[f][e] << "\t" ;
                cout<<endl;
            }
            cout << endl;
        }

        nodes = expand(M,nodes,choice);
    }while(!nodes.empty());
    return;

}

//function to check if the matrix matches the goal state
bool checkIfGoal(vector < vector<int> >  M);

int main(){

    Matrix M;
    //make goal matrix to visualize
    M.goal.push_back(std::vector<int>(3, 1));
    M.goal.push_back(std::vector<int>(3, 2));
    M.goal.push_back(std::vector<int>(3, 3));

    //create M's goal state
    M.goal[0][0]=1;
    M.goal[0][1]=2;
    M.goal[0][2]=3;
    M.goal[1][0]=4;
    M.goal[1][1]=5;
    M.goal[1][2]=6;
    M.goal[2][0]=7;
    M.goal[2][1]=8;
    M.goal[2][2]=0;

    cout << "Outputting goal matrix: " << endl;
    int a,b;
    for(b = 0; b < 3; ++b)
    {
        for(a = 0; a < 3; ++a)
            cout << M.goal[b][a] << "\t" ;
        cout<<endl;
    }

    //make matrix for 8puzzle
    M.problem.push_back(std::vector<int>(3, 1));
    M.problem.push_back(std::vector<int>(3, 2));
    M.problem.push_back(std::vector<int>(3, 3));

    M.problem[0][0]=1;
    M.problem[0][1]=3;
    M.problem[0][2]=2;
    M.problem[1][0]=4;
    M.problem[1][1]=0;
    M.problem[1][2]=6;
    M.problem[2][0]=7;
    M.problem[2][1]=5;
    M.problem[2][2]=8;

    cout << "Outputting regular matrix: " << endl;
    int c,d;
    for(d = 0; d < 3; ++d)
    {
        for(c = 0; c < 3; ++c)
            cout << M.problem[d][c] << "\t" ;
        cout<<endl;
    }

    //queue of all the possible expansions of M
    vector<Matrix> vec = expand(M/*, M1, M2, M3, M4*/);

    //cout << "Outputting gn values: " << M1.gn << ", " << M2.gn << ", " << M3.gn << ", " << M4.gn << endl;

    cout << "Outputting the queue: " << endl;
    int i,e,f;
    for(i = 0; i < vec.size(); i++)
    {
        for(f = 0; f < 3; ++f)
        {
            for(e = 0; e < 3; ++e)
                cout << vec.at(i).problem[f][e] << "\t" ;
            cout<<endl;
        }
        cout << endl;
    }
    //checking if goal matches matrix with function
    //cout << "8 Tile matches goal state? " << checkIfGoal(M.problem) << endl;

    Matrix UCS;

    UCS.problem.push_back(std::vector<int>(3, 1));
    UCS.problem.push_back(std::vector<int>(3, 2));
    UCS.problem.push_back(std::vector<int>(3, 3));

    UCS.goal.push_back(std::vector<int>(3, 1));
    UCS.goal.push_back(std::vector<int>(3, 2));
    UCS.goal.push_back(std::vector<int>(3, 3));

    priority_queue<Matrix, vector<Matrix>, Compare_Values> pq;

    UCS = generalSearch(M, UC, expand);
    //search.problem  = generalSearch(M).problem;
    //search.goal = M.goal;
    //search.fn = generalSearch(M).fn;

    return 0;
}

bool checkIfGoal(vector <vector<int> > M)
{
    if(M[0][0] ==1 && M[0][1] ==2 && M[0][2] ==3 && M[1][0] ==4 && M[1][1] == 5 && M[1][2] == 6 && M[2][0] == 7 && M[2][1] == 8 && M[2][2] == 0)
        return true;
    return false;
}

<|endoftext|>


<commit_before>#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ArduinoJson.h>

#include "helpers.hpp"
#include "defaults.hpp"
#include "radio.hpp"
#include "Config.hpp"
#include "TrackingData.hpp"
#include "ConfigServer.hpp"

Config* conf = new Config();
Radio rf(conf);
TrackingData data(conf, 10);
ConfigServer cfgSrv(80);

// Test functions for remote debugging
// int vasprintf(char** strp, const char* fmt, va_list ap) {
//     va_list ap2;
//     va_copy(ap2, ap);
//     char tmp[1];
//     int size = vsnprintf(tmp, 1, fmt, ap2);
//     if (size <= 0) return size;
//     va_end(ap2);
//     size += 1;
//     *strp = (char*)malloc(size * sizeof(char));
//     return vsnprintf(*strp, size, fmt, ap);
// }
//
// void pline(char* str, ...) {
// 	char* buf;
// 	va_list args;
//
// 	va_start(args, str);
// 	vasprintf(&buf, str, args);
// 	va_end(args);
//
// 	Terminal::println(buf);
// }
// End of test functions

void setup () {
    // Set up the EEPROM w/ a maximum size of 4096 bytes
    EEPROM.begin(4096);

    /// Set up the built-in LED and turn it on to let the user know the ESP is working
    pinMode(LED_PIN, OUTPUT);
    digitalWrite(LED_PIN, HIGH);

    /// Open up the serial and TCP monitor
    Terminal::begin(115200);

    // If the pin is not pulled to ground read config or write the default one if its not
    if (digitalRead(RESET_CONF_PIN)) {
        conf->read(0);
    } else {
        Terminal::println("Restoring factory settings...");
        conf->write(0);
    }

    // Setup the radios according to the configuration
    rf.setup();

    // Setup the OTA server
    OTA();
}

void runServerHandlers() {
    ArduinoOTA.handle();
    cfgSrv.handle();
    Terminal::handle();
}

int sleepTimeMS;
void loop() {
    // Check for a WiFi connection and attempt to reestablish it if it died
    if (!rf.connected()) {
        digitalWrite(LED_PIN, LOW);
        if (!rf.connect()) {
            // Enter deep sleep in case the connection failed
            sleepTimeMS = conf->get<int>("wifiReconnectionInterval");
            blink(); blink(); blink();
            Terminal::printf("Connection failed. Entering deep sleep mode for %dms ...\n", sleepTimeMS);
            ESP.deepSleep(sleepTimeMS * 1000, WAKE_NO_RFCAL);
        }
        digitalWrite(LED_PIN, HIGH);
    }

    // TODO: The data.send() step takes way too long
    if (conf->get<bool>("active")) {
        /// Update the environment data (scan for networks)
        if (data.update()) {
            // Send the data to the FIND Server
            bool successful = data.send();

            /// Blink to indicate that we have sent our location
            if (successful) blink();
        }
    }

    // Run all kinds of server handlers
    runServerHandlers();

    // Enter a very basic sleep mode and limit the amount of cycles to preserve power
    // (Turn off the radio and wake it up periodically to answer beacon signals from router)
    WiFi.setSleepMode(WIFI_MODEM_SLEEP);
    delay(1000);
}
<commit_msg>Removed old (deprecated) functions<commit_after>#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ArduinoJson.h>

#include "helpers.hpp"
#include "defaults.hpp"
#include "radio.hpp"
#include "Config.hpp"
#include "TrackingData.hpp"
#include "ConfigServer.hpp"

Config* conf = new Config();
Radio rf(conf);
TrackingData data(conf, 10);
ConfigServer cfgSrv(80);

void setup () {
    // Set up the EEPROM w/ a maximum size of 4096 bytes
    EEPROM.begin(4096);

    /// Set up the built-in LED and turn it on to let the user know the ESP is working
    pinMode(LED_PIN, OUTPUT);
    digitalWrite(LED_PIN, HIGH);

    /// Open up the serial and TCP monitor
    Terminal::begin(115200);

    // If the pin is not pulled to ground read config or write the default one if its not
    if (digitalRead(RESET_CONF_PIN)) {
        conf->read(0);
    } else {
        Terminal::println("Restoring factory settings...");
        conf->write(0);
    }

    // Setup the radios according to the configuration
    rf.setup();

    // Setup the OTA server
    OTA();
}

void runServerHandlers() {
    ArduinoOTA.handle();
    cfgSrv.handle();
    Terminal::handle();
}

int sleepTimeMS;
void loop() {
    // Check for a WiFi connection and attempt to reestablish it if it died
    if (!rf.connected()) {
        digitalWrite(LED_PIN, LOW);
        if (!rf.connect()) {
            // Enter deep sleep in case the connection failed
            sleepTimeMS = conf->get<int>("wifiReconnectionInterval");
            blink(); blink(); blink();
            Terminal::printf("Connection failed. Entering deep sleep mode for %dms ...\n", sleepTimeMS);
            ESP.deepSleep(sleepTimeMS * 1000, WAKE_NO_RFCAL);
        }
        digitalWrite(LED_PIN, HIGH);
    }

    // TODO: The data.send() step takes way too long
    if (conf->get<bool>("active")) {
        /// Update the environment data (scan for networks)
        if (data.update()) {
            // Send the data to the FIND Server
            bool successful = data.send();

            /// Blink to indicate that we have sent our location
            if (successful) blink();
        }
    }

    // Run all kinds of server handlers
    runServerHandlers();

    // Enter a very basic sleep mode and limit the amount of cycles to preserve power
    // (Turn off the radio and wake it up periodically to answer beacon signals from router)
    WiFi.setSleepMode(WIFI_MODEM_SLEEP);
    delay(1000);
}
<|endoftext|>


<commit_before>#include <fstream>
#include <iostream>

#include <mach-o/dyld.h>

#include "Ast.h"
#include "Compiler.h"
#include "Fiber.h"
#include "MagpieString.h"
#include "Object.h"
#include "Parser.h"
#include "VM.h"

using namespace magpie;
using namespace std;

// Finds the path to the core lib.
void getCoreLibPath(char* path)
{
  char relativePath[PATH_MAX];

  // TODO(bob): Move platform-specific stuff out to another file.
  uint32_t size = PATH_MAX;
  int result = _NSGetExecutablePath(relativePath, &size);
  ASSERT(result == 0, "Executable path too long.");

  // Find the core lib relative to the executable.
  // TODO(bob): Hack. Try to work from the build directory too.
  if (strstr(relativePath, "build/Debug/magpie") != 0 ||
      strstr(relativePath, "build/Release/magpie") != 0)
  {
    strncat(relativePath, "/../../../core/core.mag", PATH_MAX);
  }
  else
  {
    strncat(relativePath, "/../core/core.mag", PATH_MAX);
  }

  // Canonicalize the path.
  realpath(relativePath, path);
}

// Reads a file from the given path into a String.
gc<String> readFile(const char* path)
{
  ifstream stream(path);

  if (stream.fail())
  {
    cout << "Could not open file '" << path << "'." << endl;
    return gc<String>();
  }

  // From: http://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring.
  string str;

  // Allocate a std::string big enough for the file.
  stream.seekg(0, ios::end);
  str.reserve(stream.tellg());
  stream.seekg(0, ios::beg);

  // Read it in.
  str.assign((istreambuf_iterator<char>(stream)),
             istreambuf_iterator<char>());

  return String::create(str.c_str());
}

gc<String> readLine(bool isContinued)
{
  std::string line;
  while (line.size() == 0)
  {
    std::cout << (isContinued ? "| " : "> ");
    std::getline(std::cin, line);
  }

  return String::create(line.c_str());
}

int repl(VM& vm)
{
  while (true)
  {
    gc<String> source;
    gc<Expr> expr;

    while (true)
    {
      gc<String> line = readLine(!source.isNull());
      if (source.isNull())
      {
        source = line;
      }
      else
      {
        source = String::format("%s\n%s", source->cString(), line->cString());
      }

      ErrorReporter reporter(true);
      Parser parser("<repl>", source, reporter);
      expr = parser.parseExpression();

      if (reporter.needMoreLines()) continue;
      if (reporter.numErrors() == 0) break;
      return 3;
    }

    // Evaluate the expression.
    gc<Object> result = vm.evaluateReplExpression(expr);

    std::cout << "= " << result << std::endl;
  }
}

int runFile(VM& vm, const char* fileName)
{
  gc<String> source = readFile(fileName);
  bool success = vm.loadModule(fileName, source);
  return success ? 0 : 1;
}

int main(int argc, const char* argv[])
{
  if (argc > 2)
  {
    // TODO(bob): Show usage, etc.
    std::cout << "magpie [script]" << std::endl;
    return 0;
  }

  char path[PATH_MAX];
  getCoreLibPath(path);

  VM vm;

  gc<String> coreSource = readFile(path);

  vm.init(coreSource);

  if (argc == 1) return repl(vm);

  return runFile(vm, argv[1]);
}
<commit_msg>Don't show expression results for definitions in the REPL.<commit_after>#include <fstream>
#include <iostream>

#include <mach-o/dyld.h>

#include "Ast.h"
#include "Compiler.h"
#include "Fiber.h"
#include "MagpieString.h"
#include "Object.h"
#include "Parser.h"
#include "VM.h"

using namespace magpie;
using namespace std;

// Finds the path to the core lib.
void getCoreLibPath(char* path)
{
  char relativePath[PATH_MAX];

  // TODO(bob): Move platform-specific stuff out to another file.
  uint32_t size = PATH_MAX;
  int result = _NSGetExecutablePath(relativePath, &size);
  ASSERT(result == 0, "Executable path too long.");

  // Find the core lib relative to the executable.
  // TODO(bob): Hack. Try to work from the build directory too.
  if (strstr(relativePath, "build/Debug/magpie") != 0 ||
      strstr(relativePath, "build/Release/magpie") != 0)
  {
    strncat(relativePath, "/../../../core/core.mag", PATH_MAX);
  }
  else
  {
    strncat(relativePath, "/../core/core.mag", PATH_MAX);
  }

  // Canonicalize the path.
  realpath(relativePath, path);
}

// Reads a file from the given path into a String.
gc<String> readFile(const char* path)
{
  ifstream stream(path);

  if (stream.fail())
  {
    cout << "Could not open file '" << path << "'." << endl;
    return gc<String>();
  }

  // From: http://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring.
  string str;

  // Allocate a std::string big enough for the file.
  stream.seekg(0, ios::end);
  str.reserve(stream.tellg());
  stream.seekg(0, ios::beg);

  // Read it in.
  str.assign((istreambuf_iterator<char>(stream)),
             istreambuf_iterator<char>());

  return String::create(str.c_str());
}

gc<String> readLine(bool isContinued)
{
  std::string line;
  while (line.size() == 0)
  {
    std::cout << (isContinued ? "| " : "> ");
    std::getline(std::cin, line);
  }

  return String::create(line.c_str());
}

int repl(VM& vm)
{
  while (true)
  {
    gc<String> source;
    gc<Expr> expr;

    while (true)
    {
      gc<String> line = readLine(!source.isNull());
      if (source.isNull())
      {
        source = line;
      }
      else
      {
        source = String::format("%s\n%s", source->cString(), line->cString());
      }

      ErrorReporter reporter(true);
      Parser parser("<repl>", source, reporter);
      expr = parser.parseExpression();

      if (reporter.needMoreLines()) continue;
      if (reporter.numErrors() == 0) break;
      return 3;
    }

    // Evaluate the expression.
    gc<Object> result = vm.evaluateReplExpression(expr);

    // Don't show the result if it's a definition.
    if (expr->asDefExpr() != NULL) continue;
    if (expr->asDefClassExpr() != NULL) continue;

    std::cout << "= " << result << std::endl;
  }
}

int runFile(VM& vm, const char* fileName)
{
  gc<String> source = readFile(fileName);
  bool success = vm.loadModule(fileName, source);
  return success ? 0 : 1;
}

int main(int argc, const char* argv[])
{
  if (argc > 2)
  {
    // TODO(bob): Show usage, etc.
    std::cout << "magpie [script]" << std::endl;
    return 0;
  }

  char path[PATH_MAX];
  getCoreLibPath(path);

  VM vm;

  gc<String> coreSource = readFile(path);

  vm.init(coreSource);

  if (argc == 1) return repl(vm);

  return runFile(vm, argv[1]);
}
<|endoftext|>


<commit_before>#include <chrono>
#include <thread>
#include <cstring>
#include <fstream>
#include <stdio.h>

#include "AudioSubsystem.h"
#include "AudioSubsystem_OpenAL.h"
#include "Decoders/iWaveDataProvider.h"
#include "Decoders/WAV/WAVDataProvider.h"
#include "Encoders/iWaveDataEncoder.h"
#include "Encoders/WAV/WAVDataEncoder.h"
#include "Utils.h"
#include "Playlist.h"

#define ENABLE_TEST	0

const char* PORTAMP_VERSION = "1.2.0";

sConfig g_Config;
clPlaylist g_Playlist;

sConfig ReadConfigFromCommandLine( int argc, char* argv[] )
{
	sConfig Cfg;

	int i = 1;

	while ( i < argc )
	{
		if ( strstr( argv[i], "--loop" ) == argv[i] ) Cfg.m_Loop = true;
		else if ( strstr( argv[i], "--wav-modplug" ) == argv[i] ) Cfg.m_UseModPlugToDecodeWAV = true;
		else if ( strstr( argv[i], "--verbose" ) == argv[i] ) Cfg.m_Verbose = true;
		else if ( strstr (argv[i], "--output-file" ) == argv[i] )
		{
			if ( i+1 < argc )
			{
				Cfg.m_OutputFile = argv[++i];
			}
			else
			{
				printf( "Expected output file name for --output-file\n" );
				exit(0);
			}
		}
		else g_Playlist.EnqueueTrack( argv[i] );
		i++;
	}

	return Cfg;
}

void PrintBanner()
{
	printf( "PortAMP version %s (%s)\n", PORTAMP_VERSION, __DATE__ " " __TIME__ " via " __COMPILER_VER__ " for " BUILD_OS );
	printf( "Copyright (C) 2015-2019 Sergey Kosarevsky\n" );
	printf( "portamp@linderdaum.com\n" );
	printf( "https://github.com/corporateshark/PortAMP\n" );
	printf( "\n" );
	printf( "portamp <filename1> [<filename2> ...] [--loop] [--wav-modplug] [--verbose] [--output-file <filename.wav>]\n" );
	printf( "\n" );
}

int main( int argc, char* argv[] )
{
#if !ENABLE_TEST
	if ( argc <= 1 )
	{
		PrintBanner();
		return 0;
	}
#endif

	g_Config = ReadConfigFromCommandLine( argc, argv );

#if ENABLE_TEST
	if ( g_Playlist.IsEmpty() ) g_Playlist.EnqueueTrack( "test.ogg" );
	g_Config.m_Verbose = true;
#endif

	auto AudioSubsystem = CreateAudioSubsystem_OpenAL();

	AudioSubsystem->Start();

	auto Source = AudioSubsystem->CreateAudioSource();
	// allow seamless looping if there is only one track
	if ( g_Playlist.GetNumTracks() == 1 ) Source->SetLooping( g_Config.m_Loop );

	bool RequestingExit = false;

	std::shared_ptr<iWaveDataEncoder> Encoder = g_Config.m_OutputFile.empty() ? nullptr : std::make_shared<clWAVDataEncoder>();

	while ( !g_Playlist.IsEmpty() && !RequestingExit )
	{
		auto FileName = g_Playlist.GetAndPopNextTrack( g_Config.m_Loop );
		auto DataBlob = ReadFileAsBlob( FileName.c_str() );
		if (!DataBlob || !DataBlob->GetDataSize()) continue;

		auto Provider = CreateWaveDataProvider( FileName.c_str(), DataBlob );
		if (!Provider) continue;

		if (Encoder)
		{
			const auto Format = Provider->GetWaveDataFormat();
			Encoder->ResetEncoder(Format.m_NumChannels, Format.m_SamplesPerSecond, Format.m_BitsPerSample, 1.0f);
			printf("Converting %s to %s...\n", FileName.c_str(), g_Config.m_OutputFile.c_str());
			if (Provider->IsStreaming())
			{
				while (Provider->StreamWaveData(65535))
				{
					Encoder->EncodePCMData(Provider->GetWaveData(), Provider->GetWaveDataSize());
				}
			}
			else
			{
				Encoder->EncodePCMData(Provider->GetWaveData(), Provider->GetWaveDataSize());
			}
			const auto Result = Encoder->FinalizeAndGetResult();
			std::ofstream OutFile(g_Config.m_OutputFile, std::ios::out | std::ofstream::binary);
			std::copy(Result.begin(), Result.end(), std::ostreambuf_iterator<char>(OutFile));
			break;
		}

		Source->BindDataProvider( Provider );
		Source->Play();

		while ( Source->IsPlaying() && !RequestingExit )
		{
			std::this_thread::sleep_for( std::chrono::milliseconds(10) );

			if ( IsKeyPressed() ) RequestingExit = true;
		};

		Source->Stop();
	}

	Source = nullptr;

	AudioSubsystem->Stop();

	return 0;
};
<commit_msg>Print error messages when cannot read/parse an audio file<commit_after>#include <chrono>
#include <thread>
#include <cstring>
#include <fstream>
#include <stdio.h>

#include "AudioSubsystem.h"
#include "AudioSubsystem_OpenAL.h"
#include "Decoders/iWaveDataProvider.h"
#include "Decoders/WAV/WAVDataProvider.h"
#include "Encoders/iWaveDataEncoder.h"
#include "Encoders/WAV/WAVDataEncoder.h"
#include "Utils.h"
#include "Playlist.h"

#define ENABLE_TEST	0

const char* PORTAMP_VERSION = "1.2.0";

sConfig g_Config;
clPlaylist g_Playlist;

sConfig ReadConfigFromCommandLine( int argc, char* argv[] )
{
	sConfig Cfg;

	int i = 1;

	while ( i < argc )
	{
		if ( strstr( argv[i], "--loop" ) == argv[i] ) Cfg.m_Loop = true;
		else if ( strstr( argv[i], "--wav-modplug" ) == argv[i] ) Cfg.m_UseModPlugToDecodeWAV = true;
		else if ( strstr( argv[i], "--verbose" ) == argv[i] ) Cfg.m_Verbose = true;
		else if ( strstr (argv[i], "--output-file" ) == argv[i] )
		{
			if ( i+1 < argc )
			{
				Cfg.m_OutputFile = argv[++i];
			}
			else
			{
				printf( "Expected output file name for --output-file\n" );
				exit(0);
			}
		}
		else g_Playlist.EnqueueTrack( argv[i] );
		i++;
	}

	return Cfg;
}

void PrintBanner()
{
	printf( "PortAMP version %s (%s)\n", PORTAMP_VERSION, __DATE__ " " __TIME__ " via " __COMPILER_VER__ " for " BUILD_OS );
	printf( "Copyright (C) 2015-2019 Sergey Kosarevsky\n" );
	printf( "portamp@linderdaum.com\n" );
	printf( "https://github.com/corporateshark/PortAMP\n" );
	printf( "\n" );
	printf( "portamp <filename1> [<filename2> ...] [--loop] [--wav-modplug] [--verbose] [--output-file <filename.wav>]\n" );
	printf( "\n" );
}

int main( int argc, char* argv[] )
{
#if !ENABLE_TEST
	if ( argc <= 1 )
	{
		PrintBanner();
		return 0;
	}
#endif

	g_Config = ReadConfigFromCommandLine( argc, argv );

#if ENABLE_TEST
	if ( g_Playlist.IsEmpty() ) g_Playlist.EnqueueTrack( "test.ogg" );
	g_Config.m_Verbose = true;
#endif

	auto AudioSubsystem = CreateAudioSubsystem_OpenAL();

	AudioSubsystem->Start();

	auto Source = AudioSubsystem->CreateAudioSource();
	// allow seamless looping if there is only one track
	if ( g_Playlist.GetNumTracks() == 1 ) Source->SetLooping( g_Config.m_Loop );

	bool RequestingExit = false;

	std::shared_ptr<iWaveDataEncoder> Encoder = g_Config.m_OutputFile.empty() ? nullptr : std::make_shared<clWAVDataEncoder>();

	while ( !g_Playlist.IsEmpty() && !RequestingExit )
	{
		auto FileName = g_Playlist.GetAndPopNextTrack( g_Config.m_Loop );
		auto DataBlob = ReadFileAsBlob( FileName.c_str() );
		if (!DataBlob || !DataBlob->GetDataSize())
		{
			printf("Cannot read file %s\n", FileName.c_str());
			continue;
		}

		auto Provider = CreateWaveDataProvider( FileName.c_str(), DataBlob );
		if (!Provider)
		{
			printf("Cannot parse file %s\n", FileName.c_str());
			continue;
		}

		if (Encoder)
		{
			const auto Format = Provider->GetWaveDataFormat();
			Encoder->ResetEncoder(Format.m_NumChannels, Format.m_SamplesPerSecond, Format.m_BitsPerSample, 1.0f);
			printf("Converting %s to %s...\n", FileName.c_str(), g_Config.m_OutputFile.c_str());
			if (Provider->IsStreaming())
			{
				while (Provider->StreamWaveData(65535))
				{
					Encoder->EncodePCMData(Provider->GetWaveData(), Provider->GetWaveDataSize());
				}
			}
			else
			{
				Encoder->EncodePCMData(Provider->GetWaveData(), Provider->GetWaveDataSize());
			}
			const auto Result = Encoder->FinalizeAndGetResult();
			std::ofstream OutFile(g_Config.m_OutputFile, std::ios::out | std::ofstream::binary);
			std::copy(Result.begin(), Result.end(), std::ostreambuf_iterator<char>(OutFile));
			break;
		}

		Source->BindDataProvider( Provider );
		Source->Play();

		while ( Source->IsPlaying() && !RequestingExit )
		{
			std::this_thread::sleep_for( std::chrono::milliseconds(10) );

			if ( IsKeyPressed() ) RequestingExit = true;
		};

		Source->Stop();
	}

	Source = nullptr;

	AudioSubsystem->Stop();

	return 0;
};
<|endoftext|>


<commit_before>// custom build and feature flags
#ifdef DEBUG
	#define OPENGL_DEBUG        1
	#define FULLSCREEN          0
	#define DESPERATE           0
	#define BREAK_COMPATIBILITY 0
#else
	#define OPENGL_DEBUG        0
	#define FULLSCREEN          1
	#define DESPERATE           0
	#define BREAK_COMPATIBILITY 0
#endif

#define TWO_PASS    1
#define USE_MIPMAPS 1
#define USE_AUDIO   1
#define NO_UNIFORMS 0

#include "definitions.h"
#if OPENGL_DEBUG
	#include "debug.h"
#endif

#include "glext.h"
#include "shaders/fragment.inl"
#if TWO_PASS
	#include "shaders/post.inl"
#endif

#ifndef EDITOR_CONTROLS
void entrypoint(void)
#else
#include "song.h"
int CALLBACK WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
#endif
{
	// initialize window
	#if FULLSCREEN
		ChangeDisplaySettings(&screenSettings, CDS_FULLSCREEN);
		ShowCursor(0);
		const HDC hDC = GetDC(CreateWindow((LPCSTR)0xC018, 0, WS_POPUP | WS_VISIBLE, 0, 0, XRES, YRES, 0, 0, 0, 0));
	#else
		#ifdef EDITOR_CONTROLS
			HWND window = CreateWindow("static", 0, WS_POPUP | WS_VISIBLE, 0, 0, XRES, YRES, 0, 0, 0, 0);
			HDC hDC = GetDC(window);
		#else
			HDC hDC = GetDC(CreateWindow("static", 0, WS_POPUP | WS_VISIBLE, 0, 0, XRES, YRES, 0, 0, 0, 0));
		#endif
	#endif

	// initalize opengl
	SetPixelFormat(hDC, ChoosePixelFormat(hDC, &pfd), &pfd);
	wglMakeCurrent(hDC, wglCreateContext(hDC));
	#ifdef EDITOR_CONTROLS
		int pid = ((PFNGLCREATESHADERPROGRAMVPROC)wglGetProcAddress("glCreateShaderProgramv"))(GL_FRAGMENT_SHADER, 1, &fragment);
	#else
		const int pid = ((PFNGLCREATESHADERPROGRAMVPROC)wglGetProcAddress("glCreateShaderProgramv"))(GL_FRAGMENT_SHADER, 1, &fragment);
	#endif
	#if TWO_PASS
		#ifdef EDITOR_CONTROLS
			int pi2 = ((PFNGLCREATESHADERPROGRAMVPROC)wglGetProcAddress("glCreateShaderProgramv"))(GL_FRAGMENT_SHADER, 1, &post);
		#else
			const int pi2 = ((PFNGLCREATESHADERPROGRAMVPROC)wglGetProcAddress("glCreateShaderProgramv"))(GL_FRAGMENT_SHADER, 1, &post);
		#endif
	#endif

	#if OPENGL_DEBUG
		shaderDebug(fragment
			#ifdef EDITOR_CONTROLS
				,false
			#endif
		);
		#if TWO_PASS
			shaderDebug(post
				#ifdef EDITOR_CONTROLS
					,false
				#endif
			);
		#endif
	#endif

	// initialize sound
	#ifndef EDITOR_CONTROLS
		#if USE_AUDIO
			CreateThread(0, 0, (LPTHREAD_START_ROUTINE)_4klang_render, lpSoundBuffer, 0, 0);
			waveOutOpen(&hWaveOut, WAVE_MAPPER, &WaveFMT, NULL, 0, CALLBACK_NULL);
			waveOutPrepareHeader(hWaveOut, &WaveHDR, sizeof(WaveHDR));
			waveOutWrite(hWaveOut, &WaveHDR, sizeof(WaveHDR));
		#endif
	#else
		long double position = 0.0;
		song track(L"audio.wav");
		track.play();
		start = timeGetTime();
	#endif

	// main loop
	do
	{
		#if !(DESPERATE)
			// do minimal message handling so windows doesn't kill your application
			// not always strictly necessary but increases compatibility a lot
			MSG msg;
			PeekMessage(&msg, 0, 0, 0, PM_REMOVE);
		#endif

		// render with the primary shader
		((PFNGLUSEPROGRAMPROC)wglGetProcAddress("glUseProgram"))(pid);
		#ifndef EDITOR_CONTROLS
			// if you don't have an audio system figure some other way to pass time to your shader
			#if USE_AUDIO
				waveOutGetPosition(hWaveOut, &MMTime, sizeof(MMTIME));
				// it is possible to upload your vars as vertex color attribute (gl_Color) to save one function import
				#if NO_UNIFORMS
					glColor3ui(MMTime.u.sample, 0, 0);
				#else
					// remember to divide your shader time variable with the SAMPLE_RATE (44100 with 4klang)
					((PFNGLUNIFORM1IPROC)wglGetProcAddress("glUniform1i"))(0, MMTime.u.sample);
				#endif
			#endif
		#else
			refreshShaders(pid, pi2);
			position = track.getTime();
			((PFNGLUNIFORM1IPROC)wglGetProcAddress("glUniform1i"))(0, ((int)(position*44100.0)));
		#endif
		glRects(-1, -1, 1, 1);

		// render "post process" using the opengl backbuffer
		#if TWO_PASS
			glBindTexture(GL_TEXTURE_2D, 1);
			#if USE_MIPMAPS
				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
				glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 0, 0, XRES, YRES, 0);
				((PFNGLGENERATEMIPMAPPROC)wglGetProcAddress("glGenerateMipmap"))(GL_TEXTURE_2D);
			#else
				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
				glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 0, 0, XRES, YRES, 0);
			#endif
			((PFNGLACTIVETEXTUREPROC)wglGetProcAddress("glActiveTexture"))(GL_TEXTURE0);
			((PFNGLUSEPROGRAMPROC)wglGetProcAddress("glUseProgram"))(pi2);
			((PFNGLUNIFORM1IPROC)wglGetProcAddress("glUniform1i"))(0, 0);
			glRects(-1, -1, 1, 1);
		#endif

		SwapBuffers(hDC);

		// pausing and seeking enabled in debug mode
		#ifdef EDITOR_CONTROLS
			if(GetAsyncKeyState(VK_MENU))
			{
				double seek = 0.0;
				if(GetAsyncKeyState(VK_DOWN)) track.pause();
				if(GetAsyncKeyState(VK_UP))   track.play();
				if(GetAsyncKeyState(VK_RIGHT) && !GetAsyncKeyState(VK_SHIFT)) seek += 1.0;
				if(GetAsyncKeyState(VK_LEFT)  && !GetAsyncKeyState(VK_SHIFT)) seek -= 1.0;
				if(GetAsyncKeyState(VK_RIGHT) && GetAsyncKeyState(VK_SHIFT))  seek += 0.1;
				if(GetAsyncKeyState(VK_LEFT)  && GetAsyncKeyState(VK_SHIFT))  seek -= 0.1;
				if(position+seek != position)
				{
					position += seek;
					track.seek(position);
				}
			}
		#endif
	} while(!GetAsyncKeyState(VK_ESCAPE)
		#if USE_AUDIO
			&& MMTime.u.sample < MAX_SAMPLES
		#endif
	);

	ExitProcess(0);
}
<commit_msg>Probably a bit cleaner (still not really happy though...)<commit_after>// custom build and feature flags
#ifdef DEBUG
	#define OPENGL_DEBUG        1
	#define FULLSCREEN          0
	#define DESPERATE           0
	#define BREAK_COMPATIBILITY 0
#else
	#define OPENGL_DEBUG        0
	#define FULLSCREEN          1
	#define DESPERATE           0
	#define BREAK_COMPATIBILITY 0
#endif

#define TWO_PASS    1
#define USE_MIPMAPS 1
#define USE_AUDIO   1
#define NO_UNIFORMS 0

#include "definitions.h"
#if OPENGL_DEBUG
	#include "debug.h"
#endif

#include "glext.h"
#include "shaders/fragment.inl"
#if TWO_PASS
	#include "shaders/post.inl"
#endif

#ifndef EDITOR_CONTROLS
void entrypoint(void)
#else
#include "song.h"
int CALLBACK WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
#endif
{
	// initialize window
	#if FULLSCREEN
		ChangeDisplaySettings(&screenSettings, CDS_FULLSCREEN);
		ShowCursor(0);
		const HDC hDC = GetDC(CreateWindow((LPCSTR)0xC018, 0, WS_POPUP | WS_VISIBLE, 0, 0, XRES, YRES, 0, 0, 0, 0));
	#else
		#ifdef EDITOR_CONTROLS
			HWND window = CreateWindow("static", 0, WS_POPUP | WS_VISIBLE, 0, 0, XRES, YRES, 0, 0, 0, 0);
			HDC hDC = GetDC(window);
		#else
			HDC hDC = GetDC(CreateWindow("static", 0, WS_POPUP | WS_VISIBLE, 0, 0, XRES, YRES, 0, 0, 0, 0));
		#endif
	#endif

	// initalize opengl
	SetPixelFormat(hDC, ChoosePixelFormat(hDC, &pfd), &pfd);
	wglMakeCurrent(hDC, wglCreateContext(hDC));
	#ifdef EDITOR_CONTROLS
		int pid = ((PFNGLCREATESHADERPROGRAMVPROC)wglGetProcAddress("glCreateShaderProgramv"))(GL_FRAGMENT_SHADER, 1, &fragment);
	#else
		const int pid = ((PFNGLCREATESHADERPROGRAMVPROC)wglGetProcAddress("glCreateShaderProgramv"))(GL_FRAGMENT_SHADER, 1, &fragment);
	#endif
	#if TWO_PASS
		#ifdef EDITOR_CONTROLS
			int pi2 = ((PFNGLCREATESHADERPROGRAMVPROC)wglGetProcAddress("glCreateShaderProgramv"))(GL_FRAGMENT_SHADER, 1, &post);
		#else
			const int pi2 = ((PFNGLCREATESHADERPROGRAMVPROC)wglGetProcAddress("glCreateShaderProgramv"))(GL_FRAGMENT_SHADER, 1, &post);
		#endif
	#endif

	#if OPENGL_DEBUG
		#ifdef EDITOR_CONTROLS
			shaderDebug(fragment, false);
		#else
			shaderDebug(fragment, true);
		#endif
		#if TWO_PASS
			#ifdef EDITOR_CONTROLS
				shaderDebug(post, false);
			#else
				shaderDebug(post, true);
			#endif
		#endif
	#endif

	// initialize sound
	#ifndef EDITOR_CONTROLS
		#if USE_AUDIO
			CreateThread(0, 0, (LPTHREAD_START_ROUTINE)_4klang_render, lpSoundBuffer, 0, 0);
			waveOutOpen(&hWaveOut, WAVE_MAPPER, &WaveFMT, NULL, 0, CALLBACK_NULL);
			waveOutPrepareHeader(hWaveOut, &WaveHDR, sizeof(WaveHDR));
			waveOutWrite(hWaveOut, &WaveHDR, sizeof(WaveHDR));
		#endif
	#else
		long double position = 0.0;
		song track(L"audio.wav");
		track.play();
		start = timeGetTime();
	#endif

	// main loop
	do
	{
		#if !(DESPERATE)
			// do minimal message handling so windows doesn't kill your application
			// not always strictly necessary but increases compatibility a lot
			MSG msg;
			PeekMessage(&msg, 0, 0, 0, PM_REMOVE);
		#endif

		// render with the primary shader
		((PFNGLUSEPROGRAMPROC)wglGetProcAddress("glUseProgram"))(pid);
		#ifndef EDITOR_CONTROLS
			// if you don't have an audio system figure some other way to pass time to your shader
			#if USE_AUDIO
				waveOutGetPosition(hWaveOut, &MMTime, sizeof(MMTIME));
				// it is possible to upload your vars as vertex color attribute (gl_Color) to save one function import
				#if NO_UNIFORMS
					glColor3ui(MMTime.u.sample, 0, 0);
				#else
					// remember to divide your shader time variable with the SAMPLE_RATE (44100 with 4klang)
					((PFNGLUNIFORM1IPROC)wglGetProcAddress("glUniform1i"))(0, MMTime.u.sample);
				#endif
			#endif
		#else
			refreshShaders(pid, pi2);
			position = track.getTime();
			((PFNGLUNIFORM1IPROC)wglGetProcAddress("glUniform1i"))(0, ((int)(position*44100.0)));
		#endif
		glRects(-1, -1, 1, 1);

		// render "post process" using the opengl backbuffer
		#if TWO_PASS
			glBindTexture(GL_TEXTURE_2D, 1);
			#if USE_MIPMAPS
				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
				glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 0, 0, XRES, YRES, 0);
				((PFNGLGENERATEMIPMAPPROC)wglGetProcAddress("glGenerateMipmap"))(GL_TEXTURE_2D);
			#else
				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
				glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 0, 0, XRES, YRES, 0);
			#endif
			((PFNGLACTIVETEXTUREPROC)wglGetProcAddress("glActiveTexture"))(GL_TEXTURE0);
			((PFNGLUSEPROGRAMPROC)wglGetProcAddress("glUseProgram"))(pi2);
			((PFNGLUNIFORM1IPROC)wglGetProcAddress("glUniform1i"))(0, 0);
			glRects(-1, -1, 1, 1);
		#endif

		SwapBuffers(hDC);

		// pausing and seeking enabled in debug mode
		#ifdef EDITOR_CONTROLS
			if(GetAsyncKeyState(VK_MENU))
			{
				double seek = 0.0;
				if(GetAsyncKeyState(VK_DOWN)) track.pause();
				if(GetAsyncKeyState(VK_UP))   track.play();
				if(GetAsyncKeyState(VK_RIGHT) && !GetAsyncKeyState(VK_SHIFT)) seek += 1.0;
				if(GetAsyncKeyState(VK_LEFT)  && !GetAsyncKeyState(VK_SHIFT)) seek -= 1.0;
				if(GetAsyncKeyState(VK_RIGHT) && GetAsyncKeyState(VK_SHIFT))  seek += 0.1;
				if(GetAsyncKeyState(VK_LEFT)  && GetAsyncKeyState(VK_SHIFT))  seek -= 0.1;
				if(position+seek != position)
				{
					position += seek;
					track.seek(position);
				}
			}
		#endif
	} while(!GetAsyncKeyState(VK_ESCAPE)
		#if USE_AUDIO
			&& MMTime.u.sample < MAX_SAMPLES
		#endif
	);

	ExitProcess(0);
}
<|endoftext|>