<commit_before>#include "registering_enum.h"
#include "game.h"

#include <cstdlib>
#include <ncurses.h>
#include <iostream>

using namespace std;

pair<int,int> start_ncurses(void);
void end_ncurses(void);

int main(int argc, char* argv[])
{
	pair<int, int> screen_size;
	screen_size = start_ncurses();

	WINDOW* menuwin = newwin(6, screen_size.second-12, screen_size.first-8, 5);
	box(menuwin, 0, 0);
	refresh();
	wrefresh(menuwin);

	// Using arrow keys
	keypad(menuwin, true);

	Game* game = NULL;
	game = new Game(menuwin);

	if (game == NULL) {
		printw("Could not start game.");
		fprintf(stderr, "[%p] game variable is null.", (void*) game);
	}
	else {
		game->loop();
		delete(game);
		game = NULL;
	}

	end_ncurses();

	return 0;
}

pair<int, int> start_ncurses(void)
{
	initscr();
	cbreak();
	noecho();

	// Get screen size
	int yMax, xMax;
	getmaxyx(stdscr, yMax, xMax);

	if (has_colors()) {
		start_color();

		if (can_change_color()) {

			//init_color(color, 0~999, 0~999, 0~999);
			init_color(COLOR_BLACK  ,   0,   0,   0);
			init_color(COLOR_RED    , 999,   0,   0);
			init_color(COLOR_GREEN  ,   0, 999,   0);
			init_color(COLOR_YELLOW , 999, 999,   0);
			init_color(COLOR_BLUE   ,   0,   0, 999);
			init_color(COLOR_MAGENTA, 999,   0, 999);
			init_color(COLOR_CYAN   , 500, 500, 500);
			init_color(COLOR_WHITE  , 999, 999, 999);
		}

		//init_pair(#color_pair, Foreground, Background);
		init_pair(Color::Foreground_White,  COLOR_WHITE  , COLOR_BLACK  );
		init_pair(Color::Foreground_Red,    COLOR_RED    , COLOR_BLACK  );
		init_pair(Color::Foreground_Green,  COLOR_GREEN  , COLOR_BLACK  );
		init_pair(Color::Foreground_Blue,   COLOR_BLUE   , COLOR_BLACK  );
		init_pair(Color::Foreground_Yellow, COLOR_YELLOW , COLOR_BLACK  );
		init_pair(Color::Foreground_Purple, COLOR_MAGENTA, COLOR_BLACK  );
		init_pair(Color::Foreground_Black,  COLOR_CYAN   , COLOR_BLACK  );
		init_pair(Color::Background_Black,  COLOR_CYAN   , COLOR_CYAN   );
		init_pair(Color::Background_White,  COLOR_WHITE  , COLOR_WHITE  );
		init_pair(Color::Background_Red,    COLOR_RED    , COLOR_RED    );
		init_pair(Color::Background_Green,  COLOR_GREEN  , COLOR_GREEN  );
		init_pair(Color::Background_Blue,   COLOR_BLUE   , COLOR_BLUE   );
		init_pair(Color::Background_Yellow, COLOR_YELLOW , COLOR_YELLOW );
		init_pair(Color::Background_Purple, COLOR_MAGENTA, COLOR_MAGENTA);
	}
	else {
		printw("Terminal does not support color");
		getch();
	}

	return make_pair(yMax, xMax);
}

void end_ncurses()
{
	endwin();

	return ;
}
<commit_msg>Parsing command line parameters<commit_after>#include "registering_enum.h"
#include "game.h"

#include <cstdlib>
#include <ncurses.h>
#include <unistd.h>

using namespace std;

pair<int,int> start_ncurses(void);
void end_ncurses(void);

int main(int argc, char* argv[])
{
	int num_discs = 5;
	int num_pawns = 3;

	// Parse parameters
	int c;
	while ((c = getopt(argc, argv, "d:p:")) != -1) {
		switch (c) {
			case 'd':
			if (optarg) num_discs = atoi(optarg);
			break;

			case 'p':
			if (optarg) num_pawns = atoi(optarg);
			break;
		}
	}

	pair<int, int> screen_size;
	screen_size = start_ncurses();

	WINDOW* menuwin = newwin(num_pawns+3, screen_size.second-12, screen_size.first-8, 5);
	box(menuwin, 0, 0);
	refresh();
	wrefresh(menuwin);

	// Using arrow keys
	keypad(menuwin, true);

	Game* game = NULL;
	game = new Game(menuwin);

	if (game == NULL) {
		printw("Could not start game.");
		fprintf(stderr, "[%p] game variable is null.", (void*) game);
	}
	else {
		game->loop();
		delete(game);
		game = NULL;
	}

	end_ncurses();

	return 0;
}

pair<int, int> start_ncurses(void)
{
	initscr();
	cbreak();
	noecho();

	// Get screen size
	int yMax, xMax;
	getmaxyx(stdscr, yMax, xMax);

	if (has_colors()) {
		start_color();

		if (can_change_color()) {

			//init_color(color, 0~999, 0~999, 0~999);
			init_color(COLOR_BLACK  ,   0,   0,   0);
			init_color(COLOR_RED    , 999,   0,   0);
			init_color(COLOR_GREEN  ,   0, 999,   0);
			init_color(COLOR_YELLOW , 999, 999,   0);
			init_color(COLOR_BLUE   ,   0,   0, 999);
			init_color(COLOR_MAGENTA, 999,   0, 999);
			init_color(COLOR_CYAN   , 500, 500, 500);
			init_color(COLOR_WHITE  , 999, 999, 999);
		}

		//init_pair(#color_pair, Foreground, Background);
		init_pair(Color::Foreground_White,  COLOR_WHITE  , COLOR_BLACK  );
		init_pair(Color::Foreground_Red,    COLOR_RED    , COLOR_BLACK  );
		init_pair(Color::Foreground_Green,  COLOR_GREEN  , COLOR_BLACK  );
		init_pair(Color::Foreground_Blue,   COLOR_BLUE   , COLOR_BLACK  );
		init_pair(Color::Foreground_Yellow, COLOR_YELLOW , COLOR_BLACK  );
		init_pair(Color::Foreground_Purple, COLOR_MAGENTA, COLOR_BLACK  );
		init_pair(Color::Foreground_Black,  COLOR_CYAN   , COLOR_BLACK  );
		init_pair(Color::Background_Black,  COLOR_CYAN   , COLOR_CYAN   );
		init_pair(Color::Background_White,  COLOR_WHITE  , COLOR_WHITE  );
		init_pair(Color::Background_Red,    COLOR_RED    , COLOR_RED    );
		init_pair(Color::Background_Green,  COLOR_GREEN  , COLOR_GREEN  );
		init_pair(Color::Background_Blue,   COLOR_BLUE   , COLOR_BLUE   );
		init_pair(Color::Background_Yellow, COLOR_YELLOW , COLOR_YELLOW );
		init_pair(Color::Background_Purple, COLOR_MAGENTA, COLOR_MAGENTA);
	}
	else {
		printw("Terminal does not support color");
		getch();
	}

	return make_pair(yMax, xMax);
}

void end_ncurses()
{
	endwin();

	return ;
}
<|endoftext|>


<commit_before>#include <irrlicht.h>
#include <iostream>

#include "irrlichtDebug.hpp"

using namespace irr;

namespace ic = irr::core;
namespace is = irr::scene;
namespace iv = irr::video;

struct MyEventReceiver : IEventReceiver
{
  bool OnEvent(const SEvent &event)
  {
    // If input is of keyboard type  (KEY_INPUT)
    // and a pressed key
    // and the key is ESCAPE
    if (event.EventType == EET_KEY_INPUT_EVENT &&
        event.KeyInput.PressedDown &&
        event.KeyInput.Key == KEY_ESCAPE)
      exit(0);

    return false;
  }
};

int main()
{
  // Event Receiver
  MyEventReceiver receiver;
  // Initialization of the rendering system and window
  IrrlichtDevice *device = createDevice(iv::EDT_OPENGL,
                                        ic::dimension2d<u32>(640, 480),
                                        16, false, false, false, &receiver);

  iv::IVideoDriver  *driver = device->getVideoDriver();
  is::ISceneManager *smgr = device->getSceneManager();

//  // Loading a mesh
//  is::IAnimatedMesh *mesh = smgr->getMesh("data/tris.md2");

//  // Creating node from mesh
//  is::IAnimatedMeshSceneNode *node = smgr->addAnimatedMeshSceneNode(mesh);

  is::ICameraSceneNode *camera = smgr->addCameraSceneNodeMaya();
//  camera->setTarget(node->getPosition());

  while(device->run())
  {
    driver->beginScene(true, true, iv::SColor(0,50,100,255));

    // Draw the scene
    smgr->drawAll();
    //
    driver->endScene();
  }
  device->drop();

  return 0;
}
<commit_msg>ENH: Draw the axis base in the scene<commit_after>#include <irrlicht.h>
#include <iostream>

#include "irrlichtDebug.hpp"

using namespace irr;

namespace ic = irr::core;
namespace is = irr::scene;
namespace iv = irr::video;

// Prototypes
void drawAxes(irr::video::IVideoDriver * driver);

// Event managing class
struct MyEventReceiver : IEventReceiver
{
  bool OnEvent(const SEvent &event)
  {
    // If input is of keyboard type  (KEY_INPUT)
    // and a pressed key
    // and the key is ESCAPE
    if (event.EventType == EET_KEY_INPUT_EVENT &&
        event.KeyInput.PressedDown &&
        event.KeyInput.Key == KEY_ESCAPE)
      exit(0);

    return false;
  }
};

int main()
{
  // Event Receiver
  MyEventReceiver receiver;
  // Initialization of the rendering system and window
  IrrlichtDevice *device = createDevice(iv::EDT_OPENGL,
                                        ic::dimension2d<u32>(640, 480),
                                        16, false, false, false, &receiver);

  iv::IVideoDriver  *driver = device->getVideoDriver();
  is::ISceneManager *smgr = device->getSceneManager();

//  // Loading a mesh
//  is::IAnimatedMesh *mesh = smgr->getMesh("data/tris.md2");

//  // Creating node from mesh
//  is::IAnimatedMeshSceneNode *node = smgr->addAnimatedMeshSceneNode(mesh);

  is::ICameraSceneNode *camera = smgr->addCameraSceneNodeMaya();
//  camera->setTarget(node->getPosition());

  while(device->run())
  {
    driver->beginScene(true, true, iv::SColor(0,250,255,255));

    // Draw Axes
    drawAxes(driver);

    // Draw the scene
    smgr->drawAll();

    driver->endScene();
  }
  device->drop();

  return 0;
}

void drawAxes(video::IVideoDriver *driver)
{
    iv::SMaterial lineMaterial;
    lineMaterial.Thickness = 2;
    lineMaterial.setFlag(irr::video::EMF_LIGHTING, false);
    driver->setMaterial(lineMaterial);
    driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
    driver->draw3DLine(ic::vector3df(0,0,0),ic::vector3df(1,0,0),iv::SColor(0,255,0,0));
    driver->draw3DLine(ic::vector3df(0,0,0),ic::vector3df(0,1,0),iv::SColor(0,0,255,0));
    driver->draw3DLine(ic::vector3df(0,0,0),ic::vector3df(0,0,1),iv::SColor(0,0,0,255));
}
<|endoftext|>


<commit_before>#ifndef ITER_ZIP_HPP_
#define ITER_ZIP_HPP_

#include "internal/iter_tuples.hpp"
#include "internal/iterbase.hpp"

#include <algorithm>
#include <iterator>
#include <tuple>
#include <utility>

namespace iter {
  namespace impl {
    template <typename TupleType, std::size_t... Is>
    class Zipped;

    template <typename TupleType, std::size_t... Is>
    Zipped<TupleType, Is...> zip_impl(TupleType&&, std::index_sequence<Is...>);
  }

  template <typename... Containers>
  auto zip(Containers&&... containers);
}

template <typename TupleType, std::size_t... Is>
class iter::impl::Zipped {
 private:
  TupleType containers_;
  friend Zipped iter::impl::zip_impl<TupleType, Is...>(
      TupleType&&, std::index_sequence<Is...>);

  using ZipIterDeref = iterator_deref_tuple<TupleType>;

  Zipped(TupleType&& containers) : containers_(std::move(containers)) {}

 public:
  Zipped(Zipped&&) = default;
  class Iterator : public std::iterator<std::input_iterator_tag, ZipIterDeref> {
   private:
    iterator_tuple_type<TupleType> iters_;

   public:
    Iterator(iterator_tuple_type<TupleType>&& iters)
        : iters_(std::move(iters)) {}

    Iterator& operator++() {
      absorb(++std::get<Is>(iters_)...);
      return *this;
    }

    Iterator operator++(int) {
      auto ret = *this;
      ++*this;
      return ret;
    }

    bool operator!=(const Iterator& other) const {
      if (sizeof...(Is) == 0) return false;

      bool results[] = {
          true, (std::get<Is>(iters_) != std::get<Is>(other.iters_))...};
      return std::all_of(
          get_begin(results), get_end(results), [](bool b) { return b; });
    }

    bool operator==(const Iterator& other) const {
      return !(*this != other);
    }

    ZipIterDeref operator*() {
      return ZipIterDeref{(*std::get<Is>(iters_))...};
    }

    auto operator-> () -> ArrowProxy<decltype(**this)> {
      return {**this};
    }
  };

  Iterator begin() {
    return {iterator_tuple_type<TupleType>{
        get_begin(std::get<Is>(containers_))...}};
  }

  Iterator end() {
    return {
        iterator_tuple_type<TupleType>{get_end(std::get<Is>(containers_))...}};
  }
};

template <typename TupleType, std::size_t... Is>
iter::impl::Zipped<TupleType, Is...> iter::impl::zip_impl(
    TupleType&& containers, std::index_sequence<Is...>) {
  return {std::move(containers)};
}

template <typename... Containers>
auto iter::zip(Containers&&... containers) {
  return impl::zip_impl(
      std::tuple<Containers...>{std::forward<Containers>(containers)...},
      std::index_sequence_for<Containers...>{});
}

#endif
<commit_msg>Adds support for const iteration to zip<commit_after>#ifndef ITER_ZIP_HPP_
#define ITER_ZIP_HPP_

#include "internal/iter_tuples.hpp"
#include "internal/iterbase.hpp"

#include <algorithm>
#include <iterator>
#include <tuple>
#include <utility>

namespace iter {
  namespace impl {
    template <typename TupleType, std::size_t... Is>
    class Zipped;

    template <typename TupleType, std::size_t... Is>
    Zipped<TupleType, Is...> zip_impl(TupleType&&, std::index_sequence<Is...>);
  }

  template <typename... Containers>
  auto zip(Containers&&... containers);
}

template <typename TupleType, std::size_t... Is>
class iter::impl::Zipped {
 private:
  TupleType containers_;
  friend Zipped iter::impl::zip_impl<TupleType, Is...>(
      TupleType&&, std::index_sequence<Is...>);

  template <typename TupleTypeT>
  using ZipIterDeref = iterator_deref_tuple<TupleTypeT>;

  Zipped(TupleType&& containers) : containers_(std::move(containers)) {}

 public:
  Zipped(Zipped&&) = default;
  template <typename TupleTypeT>
  class Iterator : public std::iterator<std::input_iterator_tag, ZipIterDeref<TupleTypeT>> {
   private:
    template <typename> friend class Iterator;
    iterator_tuple_type<TupleTypeT> iters_;

   public:
    Iterator(iterator_tuple_type<TupleTypeT>&& iters)
        : iters_(std::move(iters)) {}

    Iterator& operator++() {
      absorb(++std::get<Is>(iters_)...);
      return *this;
    }

    Iterator operator++(int) {
      auto ret = *this;
      ++*this;
      return ret;
    }

    template <typename T>
    bool operator!=(const Iterator<T>& other) const {
      if (sizeof...(Is) == 0) return false;

      bool results[] = {
          true, (std::get<Is>(iters_) != std::get<Is>(other.iters_))...};
      return std::all_of(
          get_begin(results), get_end(results), [](bool b) { return b; });
    }

    template <typename T>
    bool operator==(const Iterator<T>& other) const {
      return !(*this != other);
    }

    ZipIterDeref<TupleTypeT> operator*() {
      return ZipIterDeref<TupleTypeT>{(*std::get<Is>(iters_))...};
    }

    auto operator-> () -> ArrowProxy<decltype(**this)> {
      return {**this};
    }
  };

  Iterator<TupleType> begin() {
    return {iterator_tuple_type<TupleType>{
        get_begin(std::get<Is>(containers_))...}};
  }

  Iterator<TupleType> end() {
    return {
        iterator_tuple_type<TupleType>{get_end(std::get<Is>(containers_))...}};
  }

  Iterator<AsConst<TupleType>> begin() const {
    return {iterator_tuple_type<AsConst<TupleType>>{
        get_begin(std::get<Is>(as_const(containers_)))...}};
  }

  Iterator<AsConst<TupleType>> end() const {
    return {
        iterator_tuple_type<AsConst<TupleType>>{get_end(std::get<Is>(as_const(containers_)))...}};
  }
};

template <typename TupleType, std::size_t... Is>
iter::impl::Zipped<TupleType, Is...> iter::impl::zip_impl(
    TupleType&& containers, std::index_sequence<Is...>) {
  return {std::move(containers)};
}

template <typename... Containers>
auto iter::zip(Containers&&... containers) {
  return impl::zip_impl(
      std::tuple<Containers...>{std::forward<Containers>(containers)...},
      std::index_sequence_for<Containers...>{});
}

#endif
<|endoftext|>


<commit_before>#include <fstream>
#include <iostream>
#include <Refal2.h>
#include <Windows.h>

using namespace Refal2;

namespace Refal2 {

class CStandartFunctionTable : std::map<std::string, void*> {
public:
	bool FindByName( const std::string& name,
		void*& standartFunction ) const;
};

static void strangePrint( const CUnitList& expression )
{
	for( const CUnitNode* i = expression.GetFirst(); i != 0; i = i->Next() ) {
		switch( i->GetType() ) {
			case UT_Char:
				std::cout << i->Char();
				break;
			case UT_Label:
				std::cout << "'" << LabelTable.GetLabelText( i->Label() ) << "'";
				break;
			case UT_Number:
				std::cout << "'" << i->Number() << "'";
				break;
			case UT_LeftParen:
				std::cout << "(";
				break;
			case UT_RightParen:
				std::cout << ")";
				break;
			default:
				assert( false );
				break;
		}
	}
	std::cout << std::endl;
}

bool ExtrnPrint( CUnitList& argument, std::string& errorText )
{
	strangePrint( argument );
	return true;
}

bool ExtrnPrintm( CUnitList& argument, std::string& errorText )
{
	HandyPrintFieldOfView( argument );
	return true;
}

bool ExtrnProut( CUnitList& argument, std::string& errorText )
{
	strangePrint( argument );
	argument.Empty();
	return true;
}

bool ExtrnProutm( CUnitList& argument, std::string& errorText )
{
	HandyPrintFieldOfView( argument );
	argument.Empty();
	return true;
}

}

class CErrorHandler : public IErrorHandler {
public:
	virtual void Error( const std::string& errorText );
	virtual void Warning( const std::string& warningText );
};

void CErrorHandler::Error( const std::string& errorText )
{
	std::cerr << errorText << std::endl;
}
void CErrorHandler::Warning( const std::string& warningText )
{
	std::cerr << warningText << std::endl;
}

bool ParseFile( std::istream& fileStream )
{
	LabelTable.Empty();
	CErrorHandler errorProcessor;
	CScanner scanner( &errorProcessor );

	for( char c; fileStream.get( c ); ) {
		scanner.AddChar( c );
	}

	return ( !scanner.HasErrors() );
}

int main( int argc, const char* argv[] )
{
	if( argc < 2 ) {
		std::cerr << "Wrong arguments: source files were not set." << std::endl;
		return 1;
	}

	bool success = true;
	for( int i = 1; i < argc; i++ ) {
		std::ifstream fileStream( argv[i] );
		if( !fileStream.good() ) {
			std::cerr << "Cannot open file: `" << argv[i] << "`." << std::endl;
			std::cerr << "------------------------" << std::endl << std::endl;
			success = false;
			continue;
		}
		std::cout << "Source file: `" << argv[i] << "`." << std::endl;
		ParseFile( fileStream );
		std::cout << "------------------------" << std::endl << std::endl;
		std::cerr << "------------------------" << std::endl << std::endl;
		fileStream.close();
	}

	return ( success ? 0 : 1 );
}
<commit_msg>delete wrong include<commit_after>#include <fstream>
#include <iostream>
#include <Refal2.h>

using namespace Refal2;

namespace Refal2 {

class CStandartFunctionTable : std::map<std::string, void*> {
public:
	bool FindByName( const std::string& name,
		void*& standartFunction ) const;
};

static void strangePrint( const CUnitList& expression )
{
	for( const CUnitNode* i = expression.GetFirst(); i != 0; i = i->Next() ) {
		switch( i->GetType() ) {
			case UT_Char:
				std::cout << i->Char();
				break;
			case UT_Label:
				std::cout << "'" << LabelTable.GetLabelText( i->Label() ) << "'";
				break;
			case UT_Number:
				std::cout << "'" << i->Number() << "'";
				break;
			case UT_LeftParen:
				std::cout << "(";
				break;
			case UT_RightParen:
				std::cout << ")";
				break;
			default:
				assert( false );
				break;
		}
	}
	std::cout << std::endl;
}

bool ExtrnPrint( CUnitList& argument, std::string& errorText )
{
	strangePrint( argument );
	return true;
}

bool ExtrnPrintm( CUnitList& argument, std::string& errorText )
{
	HandyPrintFieldOfView( argument );
	return true;
}

bool ExtrnProut( CUnitList& argument, std::string& errorText )
{
	strangePrint( argument );
	argument.Empty();
	return true;
}

bool ExtrnProutm( CUnitList& argument, std::string& errorText )
{
	HandyPrintFieldOfView( argument );
	argument.Empty();
	return true;
}

}

class CErrorHandler : public IErrorHandler {
public:
	virtual void Error( const std::string& errorText );
	virtual void Warning( const std::string& warningText );
};

void CErrorHandler::Error( const std::string& errorText )
{
	std::cerr << errorText << std::endl;
}
void CErrorHandler::Warning( const std::string& warningText )
{
	std::cerr << warningText << std::endl;
}

bool ParseFile( std::istream& fileStream )
{
	LabelTable.Empty();
	CErrorHandler errorProcessor;
	CScanner scanner( &errorProcessor );

	for( char c; fileStream.get( c ); ) {
		scanner.AddChar( c );
	}

	return ( !scanner.HasErrors() );
}

int main( int argc, const char* argv[] )
{
	if( argc < 2 ) {
		std::cerr << "Wrong arguments: source files were not set." << std::endl;
		return 1;
	}

	bool success = true;
	for( int i = 1; i < argc; i++ ) {
		std::ifstream fileStream( argv[i] );
		if( !fileStream.good() ) {
			std::cerr << "Cannot open file: `" << argv[i] << "`." << std::endl;
			std::cerr << "------------------------" << std::endl << std::endl;
			success = false;
			continue;
		}
		std::cout << "Source file: `" << argv[i] << "`." << std::endl;
		ParseFile( fileStream );
		std::cout << "------------------------" << std::endl << std::endl;
		std::cerr << "------------------------" << std::endl << std::endl;
		fileStream.close();
	}

	return ( success ? 0 : 1 );
}
<|endoftext|>


<commit_before>#include <fstream>
#include <iostream>
#include <vector>
#include <stdlib.h>

#include "../include/enum.h"
#include "../include/betterEnum.h"
#include "../include/divAndC.h"
#include "../include/linear.h"
#include "../include/Helper/fileUtils.h"
#include "../include/Helper/timingRoutines.h"

#define RUN_TESTS 0

int main()
{
    std::ifstream input;
    input.open("MSS_TestProblems.txt");
    if(!input.is_open())
    {
        input.close();
        std::cout << "MSS_TestProblems.txt not found in current directory. Now exiting." << std::endl;
        exit(1);
    }

    std::ofstream out;
    out.open("MSS_TestResults.txt");

    std::vector<std::vector<int>*>* processedInts = Helper::processMSSFile(input);
    input.close();

    out << "Results of enumFunction: \n";
    for(uint i = 0; i < processedInts->size(); i++)
    {
        int start;
        int end;
        int total = enumFunction(*(processedInts->at(i)), start, end);
        Helper::WriteResultsToFile(out, *processedInts->at(i), start, end, total);
        std::cout << '\n';
    }

    out << "Results of betterEnumFunction: \n";
    for(uint i = 0; i < processedInts->size(); i++)
    {
        int start;
        int end;
        int total = betterEnumFunction(*(processedInts->at(i)), start, end);
        Helper::WriteResultsToFile(out, *processedInts->at(i), start, end, total);
        std::cout << '\n';
    }

    out << "Results of D&C function: \n";
    for(uint i = 0; i < processedInts->size(); i++)
    {
        int start;
        int end;
        int total = divAndC(*(processedInts->at(i)), start, end);
        Helper::WriteResultsToFile(out, *processedInts->at(i), start, end, total);
        std::cout << '\n';
    }

    out << "Results of linear function: \n";
    for(uint i = 0; i < processedInts->size(); i++)
    {
        int start;
        int end;
        int total = linear(*(processedInts->at(i)), start, end);
        Helper::WriteResultsToFile(out, *processedInts->at(i), start, end, total);
		std::cout << '\n';
    }
    out.close();

    //Clean up memory
    for(uint i = 0; i < processedInts->size(); i++)
        delete processedInts->at(i);
    delete processedInts;

#if RUN_TESTS == 1
    std::cout << "Running timing function for enumFunction: " << std::endl;
    int enumValsN[] = {1000, 1200, 1400, 1600, 1800, 2000, 2200, 2400, 2600, 2800};

    for(int i = 0; i < 10; i++)
    {
        std::vector<int>* randNums = Helper::GenRandNums(enumValsN[i]);
        int(*funPtr1)(std::vector<int>) = &enumFunction;
        Helper::ClockMSSFunction(funPtr1, randNums);
    }

    std::cout << "Running timing function for betterEnumFunction: " << std::endl;
    int betterEnumValsN[] = {15000, 20000, 25000, 30000, 35000, 40000, 45000, 50000, 55000, 60000};

    for(int i = 0; i < 10; i++)
    {
        std::vector<int>* randNums = Helper::GenRandNums(betterEnumValsN[i]);
        int(*funPtr1)(std::vector<int>) = &betterEnumFunction;
        Helper::ClockMSSFunction(funPtr1, randNums);
    }

    std::cout << "Running timing function for D&C function: " << std::endl;
    int DCValsN[] = {15000, 20000 , 25000, 30000, 35000, 40000, 45000, 50000, 55000, 60000};
    for(int i = 0; i < 10; i++)
    {
	std::vector<int>* randNums = Helper::GenRandNums(DCValsN[i]);
	int(*funPtr1)(std::vector<int>) = &divAndC;
	Helper::ClockMSSFunction(funPtr1, randNums);
    }

    std::cout << "Running timing function for linear: " << std::endl;
    int linearN[] = {10000000, 20000000, 30000000, 40000000, 50000000, 60000000, 70000000, 80000000, 90000000, 100000000};

    for(int i = 0; i < 10; i++)
    {
        std::vector<int>* randNums = Helper::GenRandNums(linearN[i]);
        int(*funPtr1)(std::vector<int>) = &linear;
        Helper::ClockMSSFunction(funPtr1, randNums);
    }

#endif

    return 0;
}
<commit_msg>Fix memory leaks in program<commit_after>#include <fstream>
#include <iostream>
#include <vector>
#include <stdlib.h>

#include "../include/enum.h"
#include "../include/betterEnum.h"
#include "../include/divAndC.h"
#include "../include/linear.h"
#include "../include/Helper/fileUtils.h"
#include "../include/Helper/timingRoutines.h"

#define RUN_TESTS 0

int main()
{
    std::ifstream input;
    input.open("MSS_TestProblems.txt");
    if(!input.is_open())
    {
        input.close();
        std::cout << "MSS_TestProblems.txt not found in current directory. Now exiting." << std::endl;
        exit(1);
    }

    std::ofstream out;
    out.open("MSS_TestResults.txt");

    std::vector<std::vector<int>*>* processedInts = Helper::processMSSFile(input);
    input.close();

    out << "Results of enumFunction: \n";
    for(uint i = 0; i < processedInts->size(); i++)
    {
        int start;
        int end;
        int total = enumFunction(*(processedInts->at(i)), start, end);
        Helper::WriteResultsToFile(out, *processedInts->at(i), start, end, total);
        std::cout << '\n';
    }

    out << "Results of betterEnumFunction: \n";
    for(uint i = 0; i < processedInts->size(); i++)
    {
        int start;
        int end;
        int total = betterEnumFunction(*(processedInts->at(i)), start, end);
        Helper::WriteResultsToFile(out, *processedInts->at(i), start, end, total);
        std::cout << '\n';
    }

    out << "Results of D&C function: \n";
    for(uint i = 0; i < processedInts->size(); i++)
    {
        int start;
        int end;
        int total = divAndC(*(processedInts->at(i)), start, end);
        Helper::WriteResultsToFile(out, *processedInts->at(i), start, end, total);
        std::cout << '\n';
    }

    out << "Results of linear function: \n";
    for(uint i = 0; i < processedInts->size(); i++)
    {
        int start;
        int end;
        int total = linear(*(processedInts->at(i)), start, end);
        Helper::WriteResultsToFile(out, *processedInts->at(i), start, end, total);
		std::cout << '\n';
    }
    out.close();

    //Clean up memory
    for(uint i = 0; i < processedInts->size(); i++)
        delete processedInts->at(i);
    delete processedInts;

#if RUN_TESTS == 1
    std::cout << "Running timing function for enumFunction: " << std::endl;
    int enumValsN[] = {1000, 1200, 1400, 1600, 1800, 2000, 2200, 2400, 2600, 2800};

    for(int i = 0; i < 10; i++)
    {
        std::vector<int>* randNums = Helper::GenRandNums(enumValsN[i]);
        int(*funPtr1)(std::vector<int>) = &enumFunction;
        Helper::ClockMSSFunction(funPtr1, randNums);
        delete randNums;
    }

    std::cout << "Running timing function for betterEnumFunction: " << std::endl;
    int betterEnumValsN[] = {15000, 20000, 25000, 30000, 35000, 40000, 45000, 50000, 55000, 60000};

    for(int i = 0; i < 10; i++)
    {
        std::vector<int>* randNums = Helper::GenRandNums(betterEnumValsN[i]);
        int(*funPtr1)(std::vector<int>) = &betterEnumFunction;
        Helper::ClockMSSFunction(funPtr1, randNums);
        delete randNums;
    }

    std::cout << "Running timing function for D&C function: " << std::endl;
    int DCValsN[] = {15000, 20000 , 25000, 30000, 35000, 40000, 45000, 50000, 55000, 60000};
    for(int i = 0; i < 10; i++)
    {
	std::vector<int>* randNums = Helper::GenRandNums(DCValsN[i]);
	int(*funPtr1)(std::vector<int>) = &divAndC;
	Helper::ClockMSSFunction(funPtr1, randNums);
        delete randNums;
    }

    std::cout << "Running timing function for linear: " << std::endl;
    int linearN[] = {10000000, 20000000, 30000000, 40000000, 50000000, 60000000, 70000000, 80000000, 90000000, 100000000};

    for(int i = 0; i < 10; i++)
    {
        std::vector<int>* randNums = Helper::GenRandNums(linearN[i]);
        int(*funPtr1)(std::vector<int>) = &linear;
        Helper::ClockMSSFunction(funPtr1, randNums);
        delete randNums;
    }

#endif

    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <queue>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include "Shell.h"
#include "Input.h"

using namespace std;

int main() {
    Input in;
    queue<string> tasks;

    // to exit while loop, user must type exit
    while(1) {

        in.getInput();
        tasks = in.Parse();

        // bool determines whether command was successful
        bool comp_status = true;
	    bool comp_status2 = true;
	    bool comp_status3 = true;
	    bool comp_status4 = true;
	    bool comp_status5 = true;
	    bool comp_status6 = true;
	    bool comp_status7 = true;
	    bool comp_status8 = true;
	    bool comp_status9 = true;
	    bool comp_status10 = true;
	    int hash = -1;
	    Connector con;
        char** c;
        Execute ex;

        // TEST STUFF
        Test test;

        while (tasks.size() != 0) {
            // if at any point the user has exit
	        if (tasks.front() == "exit") {
		    	cout << "You have exited shell." << endl;
			    exit(0);
	        }

            //------------------------------------------------------------------

            else if (tasks.front() == "&&") {
		        // to see if
			// there is a connector
			// before the parentheses
		        hash = 0;
			con.amp(tasks, comp_status);
            }

            //------------------------------------------------------------------

            else if (tasks.front() == "||") {
		        // to see if
			// there is a connector
			// before the paren
		    	hash = 0;
			con.orr(tasks, comp_status);
	    }

            // simply pop the semicolon and continue looping
	        else if (tasks.front() == ";") {
		        hash = 0;
			tasks.pop();

	        }

	    //------------------------------------------------------------------

	    else if (tasks.front() == "(") {
		    //checks to see if there is a
		    //connector before the parentheses
		    if (hash == -1) {
			    perror("no connector before (");
			    break;
		    }

		    bool bal;

		    //to see if there are an
		    //equal amount of
		    //beg and end parentheses
		    con.balance(tasks, bal);
		    if (bal == false) {
			    perror("parentheses not balanced");
			    break;
		    }

		    tasks.pop();
		    int num = 1;
		    while (num != 0) {
			    if (tasks.front() == "&&") {
				   // if num equals one meaning
				   // if we are inside one paren the single
				   // commands are bool stat 2
				   if (num == 1) {
					   con.amp(tasks, comp_status2);
				   }

				   // if num equals two meaning
				   // if we are inside 2 paren the single
				   // commands are bool stat 3
				   else if (num == 2) {
					   con.amp(tasks, comp_status3);
				   }

				   else if (num == 3) {
					   con.amp(tasks, comp_status4);
				   }

				   else if (num == 4) {
					   con.amp(tasks, comp_status5);
				   }

				   else if (num == 5) {
					   con.amp(tasks, comp_status6);
				   }

				   else if (num == 6) {
					   con.amp(tasks, comp_status7);
				   }

				   else if (num == 7) {
					   con.amp(tasks, comp_status8);
				   }

				   else if (num == 8) {
					   con.amp(tasks, comp_status9);
				   }

				   else if (num == 9) {
					   con.amp(tasks, comp_status10);
				   }
			    }

			    else if (tasks.front() == "||") {
				    // if num is 1 then comp 2
				    // gets sent to orr
				    // cause thats just a single
				    // parentheses
				    if (num == 1) {
					    con.orr(tasks, comp_status2);
				    }

				    // if num is 2 then comp 3
				    // gets sent to orr
				    // cause thats just a double
				    // parentheses
				    else if (num == 2) {
					    con.orr(tasks, comp_status3);
				    }

				    else if (num == 3) {
					    con.orr(tasks, comp_status4);
				    }

				    else if (num == 4) {
					    con.orr(tasks, comp_status5);
				    }

				    else if (num == 5) {
					    con.orr(tasks, comp_status6);
				    }

				    else if (num == 6) {
					    con.orr(tasks, comp_status7);
				    }

				    else if (num == 7) {
					    con.orr(tasks, comp_status8);
				    }

				    else if (num == 8) {
					    con.orr(tasks, comp_status9);
				    }

				    else if (num == 9) {
					    con.orr(tasks, comp_status10);
				    }
			    }

			    else if (tasks.front() == ";") {
				   con.semi(tasks);
			    }

			    else if (tasks.front() == "(") {
				    tasks.pop();
				    num++;
			    }

			    else if (tasks.front() == ")") {
				    tasks.pop();

				    // if num equals 9 then
				    // we know comp stat 10
				    // is used for comp stat 9
				    // meaning that 9 paren in
				    // 8 paren so comp 10's status
				    // determines comp 9's status
				    if (num == 9) {
					    if (comp_status10 == false) {
						    comp_status9 = false;
					    }
					    else {
						    comp_status9 = true;
					    }
				    }
				    else if (num == 8) {
					    if (comp_status9 == false) {
						    comp_status8 = false;
					    }
					    else {
						    comp_status8 = true;
					    }
				    }
				    else if (num == 7) {
					    if (comp_status8 == false) {
						    comp_status7 = false;
					    }
					    else {
						    comp_status7 = true;
					    }
				    }
				    else if (num == 6) {
					    if (comp_status7 == false) {
						    comp_status6 = false;
					    }
					    else {
						    comp_status6 = true;
					    }
				    }
				    else if (num == 5) {
					    if (comp_status6 == false) {
						    comp_status5 = false;
					    }
					    else {
						    comp_status5 = true;
					    }
				    }
				    else if (num == 4) {
					    if (comp_status5 == false) {
						    comp_status4 = false;
					    }
					    else {
						    comp_status4 = true;
					    }
				    }
				    else if (num == 3) {
					    if (comp_status4 == false) {
						    comp_status3 = false;
					    }
					    else {
						    comp_status3 = true;
					    }
				    }
				    else if (num == 2) {
					    if (comp_status3 == false) {
						    comp_status2 = false;
					    }
					    else {
						    comp_status2 = true;
					    }
				    }
				    num = num - 1;
			    }

			    else {
				    // checks if front is test then executes test
				    // specifically, or just plain executes
				    // according to size
				    if (num == 9) {
					    if (tasks.front() == "test" || tasks.front() == "[") {
						    bool brack = false;
						    if (tasks.front() == "[") {
							    brack = true;
						    }
						    tasks.pop();
						    test.run(tasks, comp_status10, brack);
					    }

					    else {
						    c = in.toChar(tasks.front());
						    ex.execute(c, comp_status10);
						    tasks.pop();
					    }
				    }

				    else if (num == 8) {
					    if (tasks.front() == "test" || tasks.front() == "[") {
						    bool brack = false;
						    if (tasks.front() == "[") {
							    brack = true;
						    }
						    tasks.pop();
						    test.run(tasks, comp_status9, brack);
					    }
					    else {
						    c = in.toChar(tasks.front());
						    ex.execute(c, comp_status9);
						    tasks.pop();
					    }
				    }

				    else if (num == 7) {
					    if (tasks.front() == "test" || tasks.front() == "[") {
						    bool brack = false;
						    if (tasks.front() == "[") {
							    brack = true;
						    }
						    tasks.pop();
						    test.run(tasks, comp_status8, brack);
					    }
					    else {
						    c = in.toChar(tasks.front());
						    ex.execute(c, comp_status8);
						    tasks.pop();
					    }
				    }

				    else if (num == 6) {
					    if (tasks.front() == "test" || tasks.front() == "[") {
						    bool brack = false;
						    if (tasks.front() == "[") {
							    brack = true;
						    }
						    tasks.pop();
						    test.run(tasks, comp_status7, brack);
					    }
					    else {
						    c = in.toChar(tasks.front());
					            ex.execute(c, comp_status7);
					            tasks.pop();
					    }
				    }

				    else if (num == 5) {
					    if (tasks.front() == "test" || tasks.front() == "[") {
						    bool brack = false;
						    if (tasks.front() == "[") {
							    brack = true;
						    }
						    tasks.pop();
						    test.run(tasks, comp_status6, brack);
					    }
					    else {
						    c = in.toChar(tasks.front());
					            ex.execute(c, comp_status6);
					            tasks.pop();
					    }
				    }

				    else if (num == 4) {
					    if (tasks.front() == "test" || tasks.front() == "[") {
						    bool brack = false;
						    if (tasks.front() == "[") {
							    brack = true;
						    }
						    tasks.pop();
						    test.run(tasks, comp_status5, brack);
					    }
					    else {
						    c = in.toChar(tasks.front());
					            ex.execute(c, comp_status5);
					            tasks.pop();
					    }
				    }

				    else if (num == 3) {
					    if (tasks.front() == "test" || tasks.front() == "[") {
						    bool brack = false;
						    if (tasks.front() == "[") {
							    brack = true;
						    }
						    tasks.pop();
						    test.run(tasks, comp_status4, brack);
					    }
					    else {
						    c = in.toChar(tasks.front());
					            ex.execute(c, comp_status4);
					            tasks.pop();
					    }
				    }

				    else if (num == 2) {
					    if (tasks.front() == "test" || tasks.front() == "[") {
						    bool brack = false;
						    if (tasks.front() == "[") {
							    brack = true;
						    }
						    tasks.pop();
						    test.run(tasks, comp_status3, brack);
					    }
					    else {
						    c = in.toChar(tasks.front());
					            ex.execute(c, comp_status3);
					            tasks.pop();
					    }
				    }

				    else if (num == 1) {
					    if (tasks.front() == "test" || tasks.front() == "[") {
						    bool brack = false;
						    if (tasks.front() == "[") {
							    brack = true;
						    }
						    tasks.pop();
						    test.run(tasks, comp_status2, brack);
					    }
					    else {
						    c = in.toChar(tasks.front());
						    ex.execute(c, comp_status2);
						    tasks.pop();
					    }
				    }
			    }
		    }

		    if (comp_status2 == false) {
			    comp_status = false;
		    }

		    else {
			    comp_status = true;
		    }
	    }

            //-----------------------------------------------------------------

            // the user wants to test
            else if (tasks.front() == "test" || tasks.front() == "[") {
                // pops "test"
                bool brack = false;
                if (tasks.front() == "[") {
                    brack = true;
                }
                tasks.pop();
                test.run(tasks, comp_status, brack);
            }

            else if ( tasks.front().size() > 3 && (tasks.front().substr(0, 3) == "test" ||
                    tasks.front().at(0) == '[') ) {
                bool brack = false;
                if (tasks.front().at(0) == '[') {
                    brack = true;
                }
                queue<string> a = test.parseTest(tasks.front());
                test.run(tasks, comp_status, brack);
            }

            // task was not a connector, and therefore a command
            else {
		    c = in.toChar(tasks.front());
		    ex.execute(c, comp_status);
	    	    tasks.pop();
	        }
	}
	cout << flush;
    }
    return 0;
}
<commit_msg>test works in parentheses, finally<commit_after>#include <iostream>
#include <queue>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include "Shell.h"
#include "Input.h"

using namespace std;

int main() {
    Input in;
    queue<string> tasks;

    // to exit while loop, user must type exit
    while(1) {

        in.getInput();
        tasks = in.Parse();

        // bool determines whether command was successful
        bool comp_status = true;
	    bool comp_status2 = true;
	    bool comp_status3 = true;
	    bool comp_status4 = true;
	    bool comp_status5 = true;
	    bool comp_status6 = true;
	    bool comp_status7 = true;
	    bool comp_status8 = true;
	    bool comp_status9 = true;
	    bool comp_status10 = true;
	    int hash = -1;
	    Connector con;
        char** c;
        Execute ex;

        // TEST STUFF
        Test test;

        while (tasks.size() != 0) {
            // if at any point the user has exit
	        if (tasks.front() == "exit") {
		    	cout << "You have exited shell." << endl;
			    exit(0);
	        }

            //------------------------------------------------------------------

            else if (tasks.front() == "&&") {
		        // to see if
			// there is a connector
			// before the parentheses
		        hash = 0;
			con.amp(tasks, comp_status);
            }

            //------------------------------------------------------------------

            else if (tasks.front() == "||") {
		        // to see if
			// there is a connector
			// before the paren
		    	hash = 0;
			con.orr(tasks, comp_status);
	    }

            // simply pop the semicolon and continue looping
	        else if (tasks.front() == ";") {
		        hash = 0;
			tasks.pop();

	        }

	    //------------------------------------------------------------------

	    else if (tasks.front() == "(") {
		    //checks to see if there is a
		    //connector before the parentheses
		    if (hash == -1) {
			    perror("no connector before (");
			    break;
		    }

		    bool bal;

		    //to see if there are an
		    //equal amount of
		    //beg and end parentheses
		    con.balance(tasks, bal);
		    if (bal == false) {
			    perror("parentheses not balanced");
			    break;
		    }

		    tasks.pop();
		    int num = 1;
		    while (num != 0) {
			    if (tasks.front() == "&&") {
				   // if num equals one meaning
				   // if we are inside one paren the single
				   // commands are bool stat 2
				   if (num == 1) {
					   con.amp(tasks, comp_status2);
				   }

				   // if num equals two meaning
				   // if we are inside 2 paren the single
				   // commands are bool stat 3
				   else if (num == 2) {
					   con.amp(tasks, comp_status3);
				   }

				   else if (num == 3) {
					   con.amp(tasks, comp_status4);
				   }

				   else if (num == 4) {
					   con.amp(tasks, comp_status5);
				   }

				   else if (num == 5) {
					   con.amp(tasks, comp_status6);
				   }

				   else if (num == 6) {
					   con.amp(tasks, comp_status7);
				   }

				   else if (num == 7) {
					   con.amp(tasks, comp_status8);
				   }

				   else if (num == 8) {
					   con.amp(tasks, comp_status9);
				   }

				   else if (num == 9) {
					   con.amp(tasks, comp_status10);
				   }
			    }

			    else if (tasks.front() == "||") {
				    // if num is 1 then comp 2
				    // gets sent to orr
				    // cause thats just a single
				    // parentheses
				    if (num == 1) {
					    con.orr(tasks, comp_status2);
				    }

				    // if num is 2 then comp 3
				    // gets sent to orr
				    // cause thats just a double
				    // parentheses
				    else if (num == 2) {
					    con.orr(tasks, comp_status3);
				    }

				    else if (num == 3) {
					    con.orr(tasks, comp_status4);
				    }

				    else if (num == 4) {
					    con.orr(tasks, comp_status5);
				    }

				    else if (num == 5) {
					    con.orr(tasks, comp_status6);
				    }

				    else if (num == 6) {
					    con.orr(tasks, comp_status7);
				    }

				    else if (num == 7) {
					    con.orr(tasks, comp_status8);
				    }

				    else if (num == 8) {
					    con.orr(tasks, comp_status9);
				    }

				    else if (num == 9) {
					    con.orr(tasks, comp_status10);
				    }
			    }

			    else if (tasks.front() == ";") {
				   con.semi(tasks);
			    }

			    else if (tasks.front() == "(") {
				    tasks.pop();
				    num++;
			    }

			    else if (tasks.front() == ")") {
				    tasks.pop();

				    // if num equals 9 then
				    // we know comp stat 10
				    // is used for comp stat 9
				    // meaning that 9 paren in
				    // 8 paren so comp 10's status
				    // determines comp 9's status
				    if (num == 9) {
					    if (comp_status10 == false) {
						    comp_status9 = false;
					    }
					    else {
						    comp_status9 = true;
					    }
				    }
				    else if (num == 8) {
					    if (comp_status9 == false) {
						    comp_status8 = false;
					    }
					    else {
						    comp_status8 = true;
					    }
				    }
				    else if (num == 7) {
					    if (comp_status8 == false) {
						    comp_status7 = false;
					    }
					    else {
						    comp_status7 = true;
					    }
				    }
				    else if (num == 6) {
					    if (comp_status7 == false) {
						    comp_status6 = false;
					    }
					    else {
						    comp_status6 = true;
					    }
				    }
				    else if (num == 5) {
					    if (comp_status6 == false) {
						    comp_status5 = false;
					    }
					    else {
						    comp_status5 = true;
					    }
				    }
				    else if (num == 4) {
					    if (comp_status5 == false) {
						    comp_status4 = false;
					    }
					    else {
						    comp_status4 = true;
					    }
				    }
				    else if (num == 3) {
					    if (comp_status4 == false) {
						    comp_status3 = false;
					    }
					    else {
						    comp_status3 = true;
					    }
				    }
				    else if (num == 2) {
					    if (comp_status3 == false) {
						    comp_status2 = false;
					    }
					    else {
						    comp_status2 = true;
					    }
				    }
				    num = num - 1;
			    }

			    else {
				    // checks if front is test then executes test
				    // specifically, or just plain executes
				    // according to size
				    if (num == 9) {
					    if (tasks.front() == "test" || tasks.front() == "[") {
						    bool brack = false;
						    if (tasks.front() == "[") {
							    brack = true;
						    }
						    tasks.pop();
						    test.run(tasks, comp_status10, brack);
					    }
                       else if ( tasks.front().size() > 3 &&
                                (tasks.front().substr(0, 4) ==
                                "test" || tasks.front().at(0) == '[') ) {
                            bool brack = false;
                            if (tasks.front().at(0) == '[') {
                                brack = true;
                            }
                            queue<string> a = test.parseTest(tasks.front());
                            a.pop();
                            test.run(a, comp_status10, brack);
                            tasks.pop();
                        }

					    else {
						    c = in.toChar(tasks.front());
						    ex.execute(c, comp_status10);
						    tasks.pop();
					    }
				    }

				    else if (num == 8) {
					    if (tasks.front() == "test" || tasks.front() == "[") {
						    bool brack = false;
						    if (tasks.front() == "[") {
							    brack = true;
						    }
						    tasks.pop();
						    test.run(tasks, comp_status9, brack);
					    }
                       else if ( tasks.front().size() > 3 &&
                                (tasks.front().substr(0, 4) ==
                                "test" || tasks.front().at(0) == '[') ) {
                            bool brack = false;
                            if (tasks.front().at(0) == '[') {
                                brack = true;
                            }
                            queue<string> a = test.parseTest(tasks.front());
                            a.pop();
                            test.run(a, comp_status9, brack);
                            tasks.pop();
                        }
					    else {
						    c = in.toChar(tasks.front());
						    ex.execute(c, comp_status9);
						    tasks.pop();
					    }
				    }

				    else if (num == 7) {
					    if (tasks.front() == "test" || tasks.front() == "[") {
						    bool brack = false;
						    if (tasks.front() == "[") {
							    brack = true;
						    }
						    tasks.pop();
						    test.run(tasks, comp_status8, brack);
					    }
                        else if ( tasks.front().size() > 3 &&
                                (tasks.front().substr(0, 4) ==
                                "test" || tasks.front().at(0) == '[') ) {
                            bool brack = false;
                            if (tasks.front().at(0) == '[') {
                                brack = true;
                            }
                            queue<string> a = test.parseTest(tasks.front());
                            a.pop();
                            test.run(a, comp_status8, brack);
                            tasks.pop();
                        }
					    else {
						    c = in.toChar(tasks.front());
						    ex.execute(c, comp_status8);
						    tasks.pop();
					    }
				    }

				    else if (num == 6) {
					    if (tasks.front() == "test" || tasks.front() == "[") {
						    bool brack = false;
						    if (tasks.front() == "[") {
							    brack = true;
						    }
						    tasks.pop();
						    test.run(tasks, comp_status7, brack);
					    }
                       else if ( tasks.front().size() > 3 &&
                                (tasks.front().substr(0, 4) ==
                                "test" || tasks.front().at(0) == '[') ) {
                            bool brack = false;
                            if (tasks.front().at(0) == '[') {
                                brack = true;
                            }
                            queue<string> a = test.parseTest(tasks.front());
                            a.pop();
                            test.run(a, comp_status7, brack);
                            tasks.pop();
                        }
					    else {
						    c = in.toChar(tasks.front());
					            ex.execute(c, comp_status7);
					            tasks.pop();
					    }
				    }

				    else if (num == 5) {
					    if (tasks.front() == "test" || tasks.front() == "[") {
						    bool brack = false;
						    if (tasks.front() == "[") {
							    brack = true;
						    }
						    tasks.pop();
						    test.run(tasks, comp_status6, brack);
					    }
                        else if ( tasks.front().size() > 3 &&
                                (tasks.front().substr(0, 4) ==
                                "test" || tasks.front().at(0) == '[') ) {
                            bool brack = false;
                            if (tasks.front().at(0) == '[') {
                                brack = true;
                            }
                            queue<string> a = test.parseTest(tasks.front());
                            a.pop();
                            test.run(a, comp_status6, brack);
                            tasks.pop();
                        }
					    else {
						    c = in.toChar(tasks.front());
					            ex.execute(c, comp_status6);
					            tasks.pop();
					    }
				    }

				    else if (num == 4) {
					    if (tasks.front() == "test" || tasks.front() == "[") {
						    bool brack = false;
						    if (tasks.front() == "[") {
							    brack = true;
						    }
						    tasks.pop();
						    test.run(tasks, comp_status5, brack);
					    }
                        else if ( tasks.front().size() > 3 &&
                                (tasks.front().substr(0, 4) ==
                                "test" || tasks.front().at(0) == '[') ) {
                            bool brack = false;
                            if (tasks.front().at(0) == '[') {
                                brack = true;
                            }
                            queue<string> a = test.parseTest(tasks.front());
                            a.pop();
                            test.run(a, comp_status5, brack);
                            tasks.pop();
                        }
					    else {
						    c = in.toChar(tasks.front());
					            ex.execute(c, comp_status5);
					            tasks.pop();
					    }
				    }

				    else if (num == 3) {
					    if (tasks.front() == "test" || tasks.front() == "[") {
						    bool brack = false;
						    if (tasks.front() == "[") {
							    brack = true;
						    }
						    tasks.pop();
						    test.run(tasks, comp_status4, brack);
					    }
                        else if ( tasks.front().size() > 3 &&
                                (tasks.front().substr(0, 4) ==
                                "test" || tasks.front().at(0) == '[') ) {
                            bool brack = false;
                            if (tasks.front().at(0) == '[') {
                                brack = true;
                            }
                            queue<string> a = test.parseTest(tasks.front());
                            a.pop();
                            test.run(a, comp_status4, brack);
                            tasks.pop();
                        }
					    else {
						    c = in.toChar(tasks.front());
					            ex.execute(c, comp_status4);
					            tasks.pop();
					    }
				    }

				    else if (num == 2) {
					    if (tasks.front() == "test" || tasks.front() == "[") {
						    bool brack = false;
						    if (tasks.front() == "[") {
							    brack = true;
						    }
						    tasks.pop();
						    test.run(tasks, comp_status3, brack);
					    }
                        else if ( tasks.front().size() > 3 &&
                                (tasks.front().substr(0, 4) ==
                                "test" || tasks.front().at(0) == '[') ) {
                            bool brack = false;
                            if (tasks.front().at(0) == '[') {
                                brack = true;
                            }
                            queue<string> a = test.parseTest(tasks.front());
                            a.pop();
                            test.run(a, comp_status3, brack);
                            tasks.pop();
                        }
					    else {
						    c = in.toChar(tasks.front());
					            ex.execute(c, comp_status3);
					            tasks.pop();
					    }
				    }

				    else if (num == 1) {
					    if (tasks.front() == "test" || tasks.front() == "[") {
						    bool brack = false;
						    if (tasks.front() == "[") {
							    brack = true;
						    }
						    tasks.pop();
						    test.run(tasks, comp_status2, brack);
					    }
                        else if ( tasks.front().size() > 3 &&
                                (tasks.front().substr(0, 4) ==
                                "test" || tasks.front().at(0) == '[') ) {
                            bool brack = false;
                            if (tasks.front().at(0) == '[') {
                                brack = true;
                            }
                            queue<string> a = test.parseTest(tasks.front());
                            a.pop();
                            test.run(a, comp_status2, brack);
                            tasks.pop();
                        }
					    else {
						    c = in.toChar(tasks.front());
						    ex.execute(c, comp_status2);
						    tasks.pop();
					    }
				    }
			    }
		    }

		    if (comp_status2 == false) {
			    comp_status = false;
		    }

		    else {
			    comp_status = true;
		    }
	    }

            //-----------------------------------------------------------------

            // the user wants to test
            else if (tasks.front() == "test" || tasks.front() == "[") {
                // pops "test"
                bool brack = false;
                if (tasks.front() == "[") {
                    brack = true;
                }
                tasks.pop();
                test.run(tasks, comp_status, brack);
            }

            // task was not a connector, and therefore a command
            else {
		    c = in.toChar(tasks.front());
		    ex.execute(c, comp_status);
	    	    tasks.pop();
	        }
	}
	cout << flush;
    }
    return 0;
}
<|endoftext|>


<commit_before>#include "model.h"
#include "helper.h"

#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/euler_angles.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/ext.hpp>
#include <imgui.h>
#include <imgui_impl_glfw.h>
#include <iostream>
#include <math.h>

#if defined(WIN32) || defined(_WIN32) || defined(__WIN32)
#undef near
#undef far
#endif

// int main(int argc, char const *argv[])
// {
// 		auto oct = std::make_unique<tnw::octree::Tree>();
// 		tnw::octree::BoundingBox bb = tnw::octree::BoundingBox(glm::vec3(-1,-1,1), 2);
// 		tnw::octree::Sphere s(glm::vec3(0,0,0), 0.5);
// 		tnw::octree::SquarePyramid sp(glm::vec3(0,-1,0), 2, 0.5);

// 		oct->classify(sp, bb, 3, 0);
// 	return 0;
// }

struct IsometricCamera
{
	float scale = 2.0, near = 10.0, far = -10.0;
	bool positive_hor = true, positive_ver = true;
};

void key_callback(GLFWwindow*, int, int, int, int);
void desenharEixos();
glm::mat4 isometric(float, float, float, bool, bool);

int main(void) {
	GLFWwindow* window;

	// Initialize the library
	if (!glfwInit())
		return 1;

	// Create a windowed mode window and its OpenGL context
	window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);

	if (!window) {
		glfwTerminate();
		return 1;
	}

	// Init ImGui
	ImGui_ImplGlfw_Init(window, true);
	// Disable .ini
	ImGui::GetIO().IniFilename = nullptr;
	// Make the window's context current
	glfwMakeContextCurrent(window);

	int window_width, window_height;
	glfwGetWindowSize(window, &window_width, &window_height);

	//Opções de OpenGL
	glClearColor(1.,1.,1.,1.);
	glEnable(GL_LINE_SMOOTH);
	glEnable(GL_CULL_FACE);
	glEnable(GL_DEPTH_TEST);
	glFrontFace(GL_CCW);

	//Set callbacks
	glfwSetKeyCallback(window, key_callback);
		//glfwSetMouseButtonCallback(window, mouse_button_callback);
		//glfwSetCursorPosCallback(window, mouse_callback);

	//Camera initalization
	IsometricCamera camera;

	// tnw::octree::BoundingBox bb2(glm::vec3(0,0,0), 4);
	// tnw::octree::BoundingBox bb3(glm::vec3(2,-1,1), 2);

	// auto oct = std::make_unique<tnw::octree::Tree>();
	tnw::octree::BoundingBox bb = tnw::octree::BoundingBox(glm::vec3(0,0,0), 1);
	tnw::octree::Sphere s(glm::vec3(0,0,0), 0.5);
	tnw::octree::SquarePyramid sp(glm::vec3(0,-1,0), 2, 0.5);
	tnw::octree::Box bx(glm::vec3(0.5,0.25,-0.25), 1, 0.5, 0.5);
	auto oct = classify(bx, bb, 4, 0);

	// std::cout << "Interseção bb1, bb2: " << (tnw::box_intersection(bb.getCenter(), bb.depth, bb.depth, bb.depth, bb2.getCenter(), bb2.depth, bb2.depth, bb2.depth) ? std::string("true") : std::string("false")) << std::endl;
	// std::cout << "Interseção bb1, bb3: " << (tnw::box_intersection(bb.getCenter(), bb.depth, bb.depth, bb.depth, bb3.getCenter(), bb3.depth, bb3.depth, bb3.depth) ? std::string("true") : std::string("false")) << std::endl;
	// std::cout << "Interseção bb2, bb3: " << (tnw::box_intersection(bb2.getCenter(), bb2.depth, bb2.depth, bb2.depth, bb3.getCenter(), bb3.depth, bb3.depth, bb3.depth) ? std::string("true") : std::string("false")) << std::endl;

	// Loop until the user closes the window
	while (!glfwWindowShouldClose(window)) {
		ImGui_ImplGlfw_NewFrame();

		// Render here
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		glShadeModel(GL_SMOOTH);

		glPushMatrix();

		glm::mat4 view = isometric(camera.scale, camera.near, camera.far, camera.positive_hor, camera.positive_ver);
		glLoadMatrixf(glm::value_ptr(view));

		desenharEixos();

		oct->draw(bb);
		// glColor3f(1,0,0);
		// bb.draw();
		// glColor3f(0,1,0);
		// bb2.draw();
		// glColor3f(0,0,1);
		// bb3.draw();

		glPopMatrix();

		//Interface construction
		ImGui::Begin("Menu");

		if (ImGui::Button("+ Scale")) {
			camera.scale += 1;
		}
		if (ImGui::Button("- Scale")) {
			camera.scale -= 1;
		}
		if (ImGui::Button("Flip X")) {
			camera.positive_hor = !camera.positive_hor;
		}
		if (ImGui::Button("Flip Y")) {
			camera.positive_ver = !camera.positive_ver;
		}
		ImGui::End();

		//ImGui::ShowTestWindow();

		// Swap front and back buffers
		ImGui::Render();
		glfwSwapBuffers(window);

		// Poll for and process events
		glfwPollEvents();
	}

	ImGui_ImplGlfw_Shutdown();
	glfwTerminate();
	return 0;
}

void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
    	glfwSetWindowShouldClose(window, GLFW_TRUE);
    }

}

void desenharEixos(){
	glBegin(GL_LINES);
		glColor3f(1.000000f, 0.000000f, 0.000000f);
		glVertex3d(0, 0, 0);
		glVertex3d(1, 0, 0);
		glColor3f(0.000000f, 1.000000f, 0.000000f);
		glVertex3d(0, 0, 0);
		glVertex3d(0, 1, 0);
		glColor3f(0.000000f, 0.000000f, 1.000000f);
		glVertex3d(0, 0, 0);
		glVertex3d(0, 0, 1);
		glColor3f(1.0f, 1.0f, 1.0f);
	glEnd();
}

glm::mat4 isometric(float scale, float near, float far, bool positive_hor, bool positive_ver)
{
	float rot_y = glm::radians(45.0);
	float rot_x = std::asin(std::tan(glm::radians(30.0f)));

	if (!positive_ver){
		rot_y = -rot_y;
	}
	if (!positive_hor){
		rot_x = -rot_x;
	}
	glm::mat4 a = glm::rotate(glm::mat4(), rot_y, glm::vec3(0.0,1.0,0.0));
	glm::mat4 b = glm::rotate(glm::mat4(), rot_x, glm::vec3(1.0,0.0,0.0));

	glm::mat4 o = glm::ortho(-scale, scale, -scale, scale, near, far);

	return o*b*a;
}
<commit_msg>Arrumado problema de câmera<commit_after>#include "model.h"
#include "helper.h"

#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/euler_angles.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/ext.hpp>
#include <imgui.h>
#include <imgui_impl_glfw.h>
#include <iostream>
#include <math.h>

#if defined(WIN32) || defined(_WIN32) || defined(__WIN32)
#undef near
#undef far
#endif

// int main(int argc, char const *argv[])
// {
// 		auto oct = std::make_unique<tnw::octree::Tree>();
// 		tnw::octree::BoundingBox bb = tnw::octree::BoundingBox(glm::vec3(-1,-1,1), 2);
// 		tnw::octree::Sphere s(glm::vec3(0,0,0), 0.5);
// 		tnw::octree::SquarePyramid sp(glm::vec3(0,-1,0), 2, 0.5);

// 		oct->classify(sp, bb, 3, 0);
// 	return 0;
// }

struct IsometricCamera
{
	float scale = 2.0, near = -10.0, far = 10.0;
	bool positive_hor = true, positive_ver = true;
};

void key_callback(GLFWwindow*, int, int, int, int);
void desenharEixos();
glm::mat4 isometric(float, float, float, bool, bool);

int main(void) {
	GLFWwindow* window;

	// Initialize the library
	if (!glfwInit())
		return 1;

	// Create a windowed mode window and its OpenGL context
	window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);

	if (!window) {
		glfwTerminate();
		return 1;
	}

	// Init ImGui
	ImGui_ImplGlfw_Init(window, true);
	// Disable .ini
	ImGui::GetIO().IniFilename = nullptr;
	// Make the window's context current
	glfwMakeContextCurrent(window);

	int window_width, window_height;
	glfwGetWindowSize(window, &window_width, &window_height);

	//Opções de OpenGL
	glClearColor(1.,1.,1.,1.);
	glEnable(GL_LINE_SMOOTH);
	glEnable(GL_CULL_FACE);
	glEnable(GL_DEPTH_TEST);
	glFrontFace(GL_CCW);

	//Set callbacks
	glfwSetKeyCallback(window, key_callback);
		//glfwSetMouseButtonCallback(window, mouse_button_callback);
		//glfwSetCursorPosCallback(window, mouse_callback);

	//Camera initalization
	IsometricCamera camera;

	// tnw::octree::BoundingBox bb2(glm::vec3(0,0,0), 4);
	// tnw::octree::BoundingBox bb3(glm::vec3(2,-1,1), 2);

	// auto oct = std::make_unique<tnw::octree::Tree>();
	tnw::octree::BoundingBox bb = tnw::octree::BoundingBox(glm::vec3(0,0,0), 1);
	tnw::octree::Sphere s(glm::vec3(0,0,0), 0.5);
	tnw::octree::SquarePyramid sp(glm::vec3(0,-1,0), 2, 0.5);
	tnw::octree::Box bx(glm::vec3(0.5,0.25,-0.25), 1, 0.5, 0.5);
	auto oct = classify(bx, bb, 4, 0);

	// std::cout << "Interseção bb1, bb2: " << (tnw::box_intersection(bb.getCenter(), bb.depth, bb.depth, bb.depth, bb2.getCenter(), bb2.depth, bb2.depth, bb2.depth) ? std::string("true") : std::string("false")) << std::endl;
	// std::cout << "Interseção bb1, bb3: " << (tnw::box_intersection(bb.getCenter(), bb.depth, bb.depth, bb.depth, bb3.getCenter(), bb3.depth, bb3.depth, bb3.depth) ? std::string("true") : std::string("false")) << std::endl;
	// std::cout << "Interseção bb2, bb3: " << (tnw::box_intersection(bb2.getCenter(), bb2.depth, bb2.depth, bb2.depth, bb3.getCenter(), bb3.depth, bb3.depth, bb3.depth) ? std::string("true") : std::string("false")) << std::endl;

	// Loop until the user closes the window
	while (!glfwWindowShouldClose(window)) {
		ImGui_ImplGlfw_NewFrame();

		// Render here
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		glShadeModel(GL_SMOOTH);

		glPushMatrix();

		glm::mat4 view = isometric(camera.scale, camera.near, camera.far, camera.positive_hor, camera.positive_ver);
		glLoadMatrixf(glm::value_ptr(view));

		desenharEixos();

		oct->draw(bb);
		// glColor3f(1,0,0);
		// bb.draw();
		// glColor3f(0,1,0);
		// bb2.draw();
		// glColor3f(0,0,1);
		// bb3.draw();

		glPopMatrix();

		//Interface construction
		ImGui::Begin("Menu");

		if (ImGui::Button("+ Scale")) {
			camera.scale += 1;
		}
		if (ImGui::Button("- Scale")) {
			camera.scale -= 1;
		}
		if (ImGui::Button("Flip X")) {
			camera.positive_hor = !camera.positive_hor;
		}
		if (ImGui::Button("Flip Y")) {
			camera.positive_ver = !camera.positive_ver;
		}
		ImGui::End();

		//ImGui::ShowTestWindow();

		// Swap front and back buffers
		ImGui::Render();
		glfwSwapBuffers(window);

		// Poll for and process events
		glfwPollEvents();
	}

	ImGui_ImplGlfw_Shutdown();
	glfwTerminate();
	return 0;
}

void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
    	glfwSetWindowShouldClose(window, GLFW_TRUE);
    }

}

void desenharEixos(){
	glBegin(GL_LINES);
		glColor3f(1.000000f, 0.000000f, 0.000000f);
		glVertex3d(0, 0, 0);
		glVertex3d(1, 0, 0);
		glColor3f(0.000000f, 1.000000f, 0.000000f);
		glVertex3d(0, 0, 0);
		glVertex3d(0, 1, 0);
		glColor3f(0.000000f, 0.000000f, 1.000000f);
		glVertex3d(0, 0, 0);
		glVertex3d(0, 0, 1);
		glColor3f(1.0f, 1.0f, 1.0f);
	glEnd();
}

glm::mat4 isometric(float scale, float near, float far, bool positive_hor, bool positive_ver)
{
	float rot_y = glm::radians(45.0);
	float rot_x = std::asin(std::tan(glm::radians(30.0f)));

	if (!positive_hor){
		// rot_x = -rot_x;
		rot_y = glm::radians(3*45.0);
	}
	if (!positive_ver){
		rot_y = -rot_y;
	}

	glm::mat4 a = glm::rotate(glm::mat4(), rot_y, glm::vec3(0.0,1.0,0.0));
	glm::mat4 b = glm::rotate(glm::mat4(), rot_x, glm::vec3(1.0,0.0,0.0));

	glm::mat4 o = glm::ortho(-scale, scale, -scale, scale, near, far);

	return o*b*a;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <vector>

#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>

#include "shaders/program.h"
#include "SOIL.h"

size_t const sWinWidth = 800;
size_t const sWinHeight = 800;

float sMixCoeff = 0.5f;

GLchar const* sVertexShader = R"(#version 330 core

layout(location = 0) in vec3 position;
layout(location = 1) in vec3 color;
layout(location = 2) in vec2 texCoords;

out vec3 vertColor;
out vec2 texCoord;

uniform mat4 transform;

void main()
{
    gl_Position = transform * vec4(position, 1.0f);
    vertColor = color;
    texCoord = vec2(texCoords.x, 1.0f - texCoords.y);
})";

GLchar const* sFragmentShaderOrange = R"(#version 330 core

in vec3 vertColor;
in vec2 texCoord;
out vec4 color;

uniform sampler2D texData1;
uniform sampler2D texData2;
uniform float mixCoeff;

void main()
{
    color = mix(texture(texData1, texCoord), texture(texData2, texCoord), mixCoeff);
}
)";

GLchar const* sFragmentShaderYellow = R"(#version 330 core

in vec3 vertColor;
out vec4 color;

void main()
{
    color = vec4(vertColor, 1.0f);//vec4(5.0f, 1.0f, 0.2f, 1.0f);
}
)";

void glfwErrorReporting(int errCode, char const* msg);
void keyCallback(GLFWwindow* window, int key, int scancode, int action, int modifiers);

int main(void)
{
    if (GL_FALSE == glfwInit())
        return -1;
        // Provide some hints for the GLFW
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    glfwSetErrorCallback(glfwErrorReporting);

        // Create a window
    GLFWwindow* window = glfwCreateWindow(sWinWidth, sWinHeight, "Renderize", nullptr, nullptr);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);

        // Initialize Glew

    glewExperimental = GL_TRUE;
    GLenum glewCode = glewInit();
    if (GLEW_OK != glewCode)
    {
        std::cerr << "Failed to initialize GLEW: " << glewGetErrorString(glewCode) << std::endl;
        return -1;
    }

    glViewport(0, 0, sWinWidth, sWinHeight);

        // Initialize some GLFW callback
    glfwSetKeyCallback(window, keyCallback);

    program shaderProgOr;
    program shaderProgYe;
    if (!shaderProgOr.create())
    {
        std::cerr << shaderProgOr.lastError() << std::endl;
        return -1;
    }
    if (!shaderProgYe.create())
    {
        std::cerr << shaderProgYe.lastError() << std::endl;
        return -1;
    }

    {
        // Shaders
        shader vertexShader;
        if (!vertexShader.compile(sVertexShader, GL_VERTEX_SHADER))
        {
            std::cerr << vertexShader.lastError() << std::endl;
            return -1;
        }
        shader fragmentShaderOr;
        if (!fragmentShaderOr.compile(sFragmentShaderOrange, GL_FRAGMENT_SHADER))
        {
            std::cerr << fragmentShaderOr.lastError() << std::endl;
            return -1;
        }
        shader fragmentShaderYe;
        if (!fragmentShaderYe.compile(sFragmentShaderYellow, GL_FRAGMENT_SHADER))
        {
            std::cerr << fragmentShaderYe.lastError() << std::endl;
            return -1;
        }

        // Shader program
        shaderProgOr.attach(vertexShader);
        shaderProgOr.attach(fragmentShaderOr);
        if (!shaderProgOr.link())
        {
            std::cerr << shaderProgOr.lastError() << std::endl;
            return -1;
        }
        shaderProgYe.attach(vertexShader);
        shaderProgYe.attach(fragmentShaderOr);
        if (!shaderProgYe.link())
        {
            std::cerr << shaderProgYe.lastError() << std::endl;
            return -1;
        }
    }

        // Texture loading
    GLuint textures[2];
    glGenTextures(2, textures);

    glBindTexture(GL_TEXTURE_2D, textures[0]);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

    int texWidth{ 0 }, texHeight{ 0 };
    auto image = SOIL_load_image("../../tex/crate.jpg", &texWidth, &texHeight, 0, SOIL_LOAD_RGB);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, texWidth, texHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
    glGenerateMipmap(GL_TEXTURE_2D);
    SOIL_free_image_data(image);
    glBindTexture(GL_TEXTURE_2D, 0);

    glBindTexture(GL_TEXTURE_2D, textures[1]);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

    image = SOIL_load_image("../../tex/awesomeface.png", &texWidth, &texHeight, 0, SOIL_LOAD_RGB);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, texWidth, texHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
    glGenerateMipmap(GL_TEXTURE_2D);
    SOIL_free_image_data(image);
    glBindTexture(GL_TEXTURE_2D, 0);

        // Geometry to draw
    GLfloat vertices[] = {
        // Positions        // Colors         // Texture Coords
         0.5f,  0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f,   // Top Right
         0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f,   // Bottom Right
        -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,   // Bottom Left
        -0.5f,  0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f    // Top Left
    };
    GLuint indices[] = {
        0, 1, 3,   // First Triangle
        1, 2, 3    // Second Triangle
    };

    GLuint VBO;
    glGenBuffers(1, &VBO);
    GLuint EBO;
    glGenBuffers(1, &EBO);
    GLuint VAO;
    glGenVertexArrays(1, &VAO);
    glBindVertexArray(VAO);
    {
        glBindBuffer(GL_ARRAY_BUFFER, VBO);
        glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), static_cast<GLvoid*>(0));
        glEnableVertexAttribArray(0);

        glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
        glEnableVertexAttribArray(1);

        glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat)));
        glEnableVertexAttribArray(2);
    }

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

        // Game Loop
    while (!glfwWindowShouldClose(window))
    {
        glfwPollEvents();

            // Rendering
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        shaderProgOr.use();

        GLfloat curTime = static_cast<float>(glfwGetTime());

        glm::mat4 trans;
        trans = glm::translate(trans, glm::vec3(0.5f, -0.5f, 0.0f));
        trans = glm::rotate(trans, curTime, glm::vec3(0.0f, 0.0f, 1.0f));
        trans = glm::scale(trans, glm::vec3(0.5f, 0.5f, 0.5f));

        glm::mat4 trans2;
        trans2 = glm::translate(trans2, glm::vec3(-0.5f, 0.5f, 0.0f));
        trans2 = glm::scale(trans2, glm::vec3(std::sin(curTime), std::sin(curTime), std::sin(curTime)));

        GLint transformLocation = glGetUniformLocation(shaderProgOr, "transform");
        GLint mixCoeffLocation = glGetUniformLocation(shaderProgOr, "mixCoeff");

        glUniformMatrix4fv(transformLocation, 1, GL_FALSE, glm::value_ptr(trans));
        glUniform1f(mixCoeffLocation, sMixCoeff);

        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, textures[0]);
        glUniform1i(glGetUniformLocation(shaderProgOr, "texData1"), 0);

        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, textures[1]);
        glUniform1i(glGetUniformLocation(shaderProgOr, "texData2"), 1);

        glBindVertexArray(VAO);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

        glUniformMatrix4fv(transformLocation, 1, GL_FALSE, glm::value_ptr(trans2));
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
        glBindVertexArray(0);
        glBindTexture(GL_TEXTURE_2D, 0);

        glfwSwapBuffers(window);

        /*glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);*/
    }

    glDeleteVertexArrays(1, &VAO);
    glDeleteBuffers(1, &EBO);
    glDeleteBuffers(1, &VBO);
    glfwTerminate();
    return 0;
}

void glfwErrorReporting(int errCode, char const* msg)
{
    std::cerr << "ERROR " << errCode << ": " << msg << std::endl;
}

void keyCallback(GLFWwindow* window, int key, int scancode, int action, int modifiers)
{
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
        glfwSetWindowShouldClose(window, GL_TRUE);
    else if (key == GLFW_KEY_UP && action == GLFW_PRESS)
    {
        sMixCoeff += 0.05f;
    }
    else if (key == GLFW_KEY_DOWN && action == GLFW_PRESS)
    {
        sMixCoeff -= 0.05f;
    }
}
<commit_msg>rotating cube<commit_after>#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <vector>

#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>

#include "shaders/program.h"
#include "SOIL.h"

size_t const sWinWidth = 800;
size_t const sWinHeight = 800;

float sMixCoeff = 0.5f;

GLchar const* sVertexShader = R"(#version 330 core

layout(location = 0) in vec3 position;
layout(location = 1) in vec2 texCoords;

out vec3 vertColor;
out vec2 texCoord;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

void main()
{
    gl_Position = projection * view * model * vec4(position, 1.0f);
    vertColor = vec3(0.0f, 0.0f, 0.0f);
    texCoord = vec2(texCoords.x, 1.0f - texCoords.y);
})";

GLchar const* sFragmentShaderOrange = R"(#version 330 core

in vec3 vertColor;
in vec2 texCoord;
out vec4 color;

uniform sampler2D texData1;
uniform sampler2D texData2;
uniform float mixCoeff;

void main()
{
    color = mix(texture(texData1, texCoord), texture(texData2, texCoord), mixCoeff);
}
)";

GLchar const* sFragmentShaderYellow = R"(#version 330 core

in vec3 vertColor;
out vec4 color;

void main()
{
    color = vec4(vertColor, 1.0f);//vec4(5.0f, 1.0f, 0.2f, 1.0f);
}
)";

void glfwErrorReporting(int errCode, char const* msg);
void keyCallback(GLFWwindow* window, int key, int scancode, int action, int modifiers);

int main(void)
{
    if (GL_FALSE == glfwInit())
        return -1;
        // Provide some hints for the GLFW
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    glfwSetErrorCallback(glfwErrorReporting);

        // Create a window
    GLFWwindow* window = glfwCreateWindow(sWinWidth, sWinHeight, "Renderize", nullptr, nullptr);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);

        // Initialize Glew

    glewExperimental = GL_TRUE;
    GLenum glewCode = glewInit();
    if (GLEW_OK != glewCode)
    {
        std::cerr << "Failed to initialize GLEW: " << glewGetErrorString(glewCode) << std::endl;
        return -1;
    }

    glViewport(0, 0, sWinWidth, sWinHeight);

        // Initialize some GLFW callback
    glfwSetKeyCallback(window, keyCallback);

    program shaderProgOr;
    program shaderProgYe;
    if (!shaderProgOr.create())
    {
        std::cerr << shaderProgOr.lastError() << std::endl;
        return -1;
    }
    if (!shaderProgYe.create())
    {
        std::cerr << shaderProgYe.lastError() << std::endl;
        return -1;
    }

    {
        // Shaders
        shader vertexShader;
        if (!vertexShader.compile(sVertexShader, GL_VERTEX_SHADER))
        {
            std::cerr << vertexShader.lastError() << std::endl;
            return -1;
        }
        shader fragmentShaderOr;
        if (!fragmentShaderOr.compile(sFragmentShaderOrange, GL_FRAGMENT_SHADER))
        {
            std::cerr << fragmentShaderOr.lastError() << std::endl;
            return -1;
        }
        shader fragmentShaderYe;
        if (!fragmentShaderYe.compile(sFragmentShaderYellow, GL_FRAGMENT_SHADER))
        {
            std::cerr << fragmentShaderYe.lastError() << std::endl;
            return -1;
        }

        // Shader program
        shaderProgOr.attach(vertexShader);
        shaderProgOr.attach(fragmentShaderOr);
        if (!shaderProgOr.link())
        {
            std::cerr << shaderProgOr.lastError() << std::endl;
            return -1;
        }
        shaderProgYe.attach(vertexShader);
        shaderProgYe.attach(fragmentShaderOr);
        if (!shaderProgYe.link())
        {
            std::cerr << shaderProgYe.lastError() << std::endl;
            return -1;
        }
    }

        // Texture loading
    GLuint textures[2];
    glGenTextures(2, textures);

    glBindTexture(GL_TEXTURE_2D, textures[0]);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

    int texWidth{ 0 }, texHeight{ 0 };
    auto image = SOIL_load_image("../../tex/crate.jpg", &texWidth, &texHeight, 0, SOIL_LOAD_RGB);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, texWidth, texHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
    glGenerateMipmap(GL_TEXTURE_2D);
    SOIL_free_image_data(image);
    glBindTexture(GL_TEXTURE_2D, 0);

    glBindTexture(GL_TEXTURE_2D, textures[1]);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

    image = SOIL_load_image("../../tex/awesomeface.png", &texWidth, &texHeight, 0, SOIL_LOAD_RGB);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, texWidth, texHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
    glGenerateMipmap(GL_TEXTURE_2D);
    SOIL_free_image_data(image);
    glBindTexture(GL_TEXTURE_2D, 0);

        // Geometry to draw
    GLfloat vertices[] = {
        -0.5f, -0.5f, -0.5f, 0.0f, 0.0f,
        0.5f, -0.5f, -0.5f, 1.0f, 0.0f,
        0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
        0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
        -0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
        -0.5f, -0.5f, -0.5f, 0.0f, 0.0f,

        -0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
        0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
        0.5f, 0.5f, 0.5f, 1.0f, 1.0f,
        0.5f, 0.5f, 0.5f, 1.0f, 1.0f,
        -0.5f, 0.5f, 0.5f, 0.0f, 1.0f,
        -0.5f, -0.5f, 0.5f, 0.0f, 0.0f,

        -0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
        -0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
        -0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
        -0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
        -0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
        -0.5f, 0.5f, 0.5f, 1.0f, 0.0f,

        0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
        0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
        0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
        0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
        0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
        0.5f, 0.5f, 0.5f, 1.0f, 0.0f,

        -0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
        0.5f, -0.5f, -0.5f, 1.0f, 1.0f,
        0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
        0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
        -0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
        -0.5f, -0.5f, -0.5f, 0.0f, 1.0f,

        -0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
        0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
        0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
        0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
        -0.5f, 0.5f, 0.5f, 0.0f, 0.0f,
        -0.5f, 0.5f, -0.5f, 0.0f, 1.0f
    };
    GLuint indices[] = {
        0, 1, 3,   // First Triangle
        1, 2, 3    // Second Triangle
    };

    GLuint VBO;
    glGenBuffers(1, &VBO);
    GLuint EBO;
    glGenBuffers(1, &EBO);
    GLuint VAO;
    glGenVertexArrays(1, &VAO);
    glBindVertexArray(VAO);
    {
        glBindBuffer(GL_ARRAY_BUFFER, VBO);
        glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), static_cast<GLvoid*>(0));
        glEnableVertexAttribArray(0);

        glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
        glEnableVertexAttribArray(1);
    }

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

        // Game Loop
    while (!glfwWindowShouldClose(window))
    {
        glfwPollEvents();

            // Rendering
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        shaderProgOr.use();

        GLfloat curTime = static_cast<float>(glfwGetTime());

        glm::mat4 model;
        model = glm::rotate(model, curTime * glm::radians(50.0f), glm::vec3(1.0f, 0.5f, 0.0f));
        glm::mat4 view;
        view = glm::translate(view, glm::vec3(0.0f, 0.0f, -3.0f));
        glm::mat4 projection;
        projection = glm::perspective(glm::radians(45.0f), static_cast<float>(sWinWidth) / sWinHeight, 0.1f, 100.0f);

        GLint modelLocation = glGetUniformLocation(shaderProgOr, "model");
        GLint viewLocation = glGetUniformLocation(shaderProgOr, "view");
        GLint projectionLocation = glGetUniformLocation(shaderProgOr, "projection");
        GLint mixCoeffLocation = glGetUniformLocation(shaderProgOr, "mixCoeff");

        glUniformMatrix4fv(modelLocation, 1, GL_FALSE, glm::value_ptr(model));
        glUniformMatrix4fv(viewLocation, 1, GL_FALSE, glm::value_ptr(view));
        glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, glm::value_ptr(projection));
        glUniform1f(mixCoeffLocation, sMixCoeff);

        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, textures[0]);
        glUniform1i(glGetUniformLocation(shaderProgOr, "texData1"), 0);

        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, textures[1]);
        glUniform1i(glGetUniformLocation(shaderProgOr, "texData2"), 1);

        glBindVertexArray(VAO);
        glDrawArrays(GL_TRIANGLES, 0, 36);
        //glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
        glBindVertexArray(0);
        glBindTexture(GL_TEXTURE_2D, 0);

        glfwSwapBuffers(window);

        /*glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);*/
    }

    glDeleteVertexArrays(1, &VAO);
    glDeleteBuffers(1, &EBO);
    glDeleteBuffers(1, &VBO);
    glfwTerminate();
    return 0;
}

void glfwErrorReporting(int errCode, char const* msg)
{
    std::cerr << "ERROR " << errCode << ": " << msg << std::endl;
}

void keyCallback(GLFWwindow* window, int key, int scancode, int action, int modifiers)
{
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
        glfwSetWindowShouldClose(window, GL_TRUE);
    else if (key == GLFW_KEY_UP && action == GLFW_PRESS)
    {
        sMixCoeff += 0.05f;
    }
    else if (key == GLFW_KEY_DOWN && action == GLFW_PRESS)
    {
        sMixCoeff -= 0.05f;
    }
}
<|endoftext|>


<commit_before>#include <iostream>
#include <clocale>

#include "augs/log.h"
#include "augs/log_path_getters.h"
#include "augs/filesystem/file.h"
#include "augs/window_framework/shell.h"

#include "cmd_line_params.h"
#include "build_info.h"

#if USE_GLFW
#include <mach-o/dyld.h>

augs::path_type get_current_exe_path() {
	char path[1024];
	uint32_t size = sizeof(path);

	if (_NSGetExecutablePath(path, &size) == 0) {
		return path;
	}

	return augs::path_type();
}
#elif PLATFORM_UNIX
#include <unistd.h>
augs::path_type get_current_exe_path() {
	char dest[PATH_MAX];
	memset(dest,0,sizeof(dest)); // readlink does not null terminate!
	if (readlink("/proc/self/exe", dest, PATH_MAX) == -1) {

		} else {
			return dest;
		}

	return augs::path_type();
}
#endif

#if PLATFORM_WINDOWS
#include <Windows.h>
#undef MIN
#undef MAX
#endif

#include "augs/window_framework/create_process.h"
#include "application/main/new_and_old_hypersomnia_path.h"
#include "work_result.h"

work_result work(const int argc, const char* const * const argv);

#if PLATFORM_WINDOWS
#if BUILD_IN_CONSOLE_MODE
int main(const int argc, const char* const * const argv) {
#else

HINSTANCE g_myhinst;

int __stdcall WinMain(HINSTANCE myhinst, HINSTANCE, char*, int) {
	g_myhinst = myhinst;
	const auto argc = __argc;
	const auto argv = __argv;
#endif
#elif PLATFORM_UNIX
int main(const int argc, const char* const * const argv) {
#else
#error "Unsupported platform!"
#endif

	/*
		At least on Linux,
		we need to call this in order to be able to write non-English characters.
	*/

	std::setlocale(LC_ALL, "");
	std::setlocale(LC_NUMERIC, "C");

	const auto params = cmd_line_params(argc, argv);

	if (!params.keep_cwd) {
#if !PLATFORM_WINDOWS && !BUILD_IN_CONSOLE_MODE
		if (auto exe_path = get_current_exe_path(); !exe_path.empty()) {
			exe_path.replace_filename("");
			std::cout << "CHANGING CWD TO: " << exe_path.string() << std::endl;
			std::filesystem::current_path(exe_path);
			std::cout << "CHANGED CWD TO: " << exe_path.string() << std::endl;
		}
#endif
	}

	::current_app_type = params.type;

	if (params.help_only) {
		std::cout << get_help_section() << std::endl;

		return EXIT_SUCCESS;
	}

	if (params.version_only) {
		std::cout << get_version_section() << std::endl;

		return EXIT_SUCCESS;
	}

	const auto completed_work_result = work(argc, argv);
	LOG_NVPS(completed_work_result);

	{
		auto save_success_logs = [&]() {
			const auto logs = program_log::get_current().get_complete();
			augs::save_as_text(get_exit_success_path(), logs);
		};

		auto save_failure_logs = [&]() {
			const auto logs = program_log::get_current().get_complete();
			const auto failure_log_path = get_exit_failure_path();

			augs::save_as_text(failure_log_path, logs);
			augs::open_text_editor(failure_log_path);
			mark_as_controlled_crash();
		};

		switch (completed_work_result) {
			case work_result::SUCCESS:
				save_success_logs();
				return EXIT_SUCCESS;

			case work_result::FAILURE: {
				save_failure_logs();
				return EXIT_FAILURE;
			}

			case work_result::RELAUNCH: {
				LOG("main: Application requested relaunch.");
				save_success_logs();

				return augs::restart_application(params.exe_path.string(), "");
			}

			case work_result::RELAUNCH_UPGRADED: {
				LOG("main: Application requested relaunch due to a successful upgrade.");
				save_success_logs();

				return augs::restart_application(params.exe_path.string(), "--upgraded-successfully");
			}

			default:
				break;
		}
	}

	return EXIT_FAILURE;
}

<commit_msg>Properly chdir to executable's directory<commit_after>#include <iostream>
#include <clocale>

#include "augs/log.h"
#include "augs/log_path_getters.h"
#include "augs/filesystem/file.h"
#include "augs/window_framework/shell.h"

#include "cmd_line_params.h"
#include "build_info.h"

#if defined(APPLE)
#include "CoreFoundation/CoreFoundation.h"
#include <unistd.h>
#include <libgen.h>
#elif PLATFORM_UNIX
#include <unistd.h>
augs::path_type get_current_exe_path() {
	char dest[PATH_MAX];
	memset(dest,0,sizeof(dest)); // readlink does not null terminate!
	if (readlink("/proc/self/exe", dest, PATH_MAX) == -1) {

		} else {
			return dest;
		}

	return augs::path_type();
}
#endif

#if PLATFORM_WINDOWS
#include <Windows.h>
#undef MIN
#undef MAX
#endif

#include "augs/window_framework/create_process.h"
#include "application/main/new_and_old_hypersomnia_path.h"
#include "work_result.h"

work_result work(const int argc, const char* const * const argv);

#if PLATFORM_WINDOWS
#if BUILD_IN_CONSOLE_MODE
int main(const int argc, const char* const * const argv) {
#else

HINSTANCE g_myhinst;

int __stdcall WinMain(HINSTANCE myhinst, HINSTANCE, char*, int) {
	g_myhinst = myhinst;
	const auto argc = __argc;
	const auto argv = __argv;
#endif
#elif PLATFORM_UNIX
int main(const int argc, const char* const * const argv) {
#else
#error "Unsupported platform!"
#endif

	/*
		At least on Linux,
		we need to call this in order to be able to write non-English characters.
	*/

	std::setlocale(LC_ALL, "");
	std::setlocale(LC_NUMERIC, "C");

	const auto params = cmd_line_params(argc, argv);

	if (!params.keep_cwd) {
#ifdef __APPLE__
		CFBundleRef mainBundle = CFBundleGetMainBundle();
		CFURLRef exeURL = CFBundleCopyExecutableURL(mainBundle);
		char path[PATH_MAX];
		if (!CFURLGetFileSystemRepresentation(exeURL, TRUE, (UInt8 *)path, PATH_MAX))
		{
			// error!
		}

		CFRelease(exeURL);

		auto p = augs::path_type(p);
		p.replace_filename("");

		auto s = p.string();

		std::cout << "CHANGING CWD TO: " << s << std::endl;

		chdir(s.c_str());

		std::cout << "CHANGED CWD TO: " << std::filesystem::current_path().string() << std::endl;

#elif PLATFORM_UNIX && !BUILD_IN_CONSOLE_MODE
		if (auto exe_path = get_current_exe_path(); !exe_path.empty()) {
			exe_path.replace_filename("");
			std::cout << "CHANGING CWD TO: " << exe_path.string() << std::endl;
			std::filesystem::current_path(exe_path);
			std::cout << "CHANGED CWD TO: " << exe_path.string() << std::endl;
		}
#endif
	}

	::current_app_type = params.type;

	if (params.help_only) {
		std::cout << get_help_section() << std::endl;

		return EXIT_SUCCESS;
	}

	if (params.version_only) {
		std::cout << get_version_section() << std::endl;

		return EXIT_SUCCESS;
	}

	const auto completed_work_result = work(argc, argv);
	LOG_NVPS(completed_work_result);

	{
		auto save_success_logs = [&]() {
			const auto logs = program_log::get_current().get_complete();
			augs::save_as_text(get_exit_success_path(), logs);
		};

		auto save_failure_logs = [&]() {
			const auto logs = program_log::get_current().get_complete();
			const auto failure_log_path = get_exit_failure_path();

			augs::save_as_text(failure_log_path, logs);
			augs::open_text_editor(failure_log_path);
			mark_as_controlled_crash();
		};

		switch (completed_work_result) {
			case work_result::SUCCESS:
				save_success_logs();
				return EXIT_SUCCESS;

			case work_result::FAILURE: {
				save_failure_logs();
				return EXIT_FAILURE;
			}

			case work_result::RELAUNCH: {
				LOG("main: Application requested relaunch.");
				save_success_logs();

				return augs::restart_application(params.exe_path.string(), "");
			}

			case work_result::RELAUNCH_UPGRADED: {
				LOG("main: Application requested relaunch due to a successful upgrade.");
				save_success_logs();

				return augs::restart_application(params.exe_path.string(), "--upgraded-successfully");
			}

			default:
				break;
		}
	}

	return EXIT_FAILURE;
}

<|endoftext|>