<commit_before>//! \file
//! Entry point

#include <map>
#include <string>
#include <vector>
#include <sstream>
#include <iomanip>
#include "MainState.h"
#include "Renderer.h"
#include "InputHandler.h"
#include "NetworkManager.h"
#include "Data.h"
#include "local_update.h"
#include "process_packets.h"

static void update(MainState &state);
static void render(const MainState &state);
static void change(MainState &state, MainState nextState);

int main()
{
	Data::MainMenuData.Menu_EN.push_back("Host game");
	Data::MainMenuData.Menu_EN.push_back("Join game");
	Data::MainMenuData.Menu_EN.push_back("Quit");

	Data::Font = Renderer::LoadFont("../prstartk.ttf");

	MenuItem item1, item2, item3;
	item1.Text = 0;
	item1.Function = Host;
	Data::MainMenuData.MenuItems.push_back(item1);
	item2.Text = 1;
	item2.Function = Join;
	Data::MainMenuData.MenuItems.push_back(item2);
	item3.Text = 2;
	item3.Function = Exiting;
	Data::MainMenuData.MenuItems.push_back(item3);

	Renderer::TileScale = 6.0f;
	Renderer::SpriteScale = 3.0f;
	Renderer::CreateWindow(768, 768, "My window");

	Data::GameplayData.PacmanSprite.Index =
		Renderer::CreateSprite("../pacman.png");
	Data::GameplayData.GhostSprite.Index =
		Renderer::CreateSprite("../pacman.png");

	Data::JoinData.IP[0] = 127;
	Data::JoinData.IP[1] = 0;
	Data::JoinData.IP[2] = 0;
	Data::JoinData.IP[3] = 1;
	Data::JoinData.Port = 0;

	Animation pac_move(4);
	//pac_move.AddFrame(34, 170, 32, 32);
	//pac_move.AddFrame(1, 170, 32, 32);
	//pac_move.AddFrame(34, 170, 32, 32);
	//pac_move.AddFrame(67, 170, 32, 32);
	pac_move.AddFrame(18, 1, 16, 16);
	pac_move.AddFrame(35, 1, 16, 16);
	pac_move.AddFrame(18, 1, 16, 16);
	pac_move.AddFrame(1, 1, 16, 16);
	Data::GameplayData.PacmanSprite.Animations.push_back(pac_move);
	Data::GameplayData.AnimFrame = 0;

	//Animation gho_move(4);
	//gho_move.AddFrame(196, 105, 32, 32);
	//gho_move.AddFrame(196, 105, 32, 32);
	//gho_move.AddFrame(229, 105, 32, 32);
	//gho_move.AddFrame(229, 105, 32, 32);
	Animation gho_hori(4);
	gho_hori.AddFrame(1, 18, 16, 16);
	gho_hori.AddFrame(1, 18, 16, 16);
	gho_hori.AddFrame(18, 18, 16, 16);
	gho_hori.AddFrame(18, 18, 16, 16);
	Data::GameplayData.GhostSprite.Animations.push_back(gho_hori);
	Animation gho_up(4);
	gho_up.AddFrame(35, 18, 16, 16);
	gho_up.AddFrame(35, 18, 16, 16);
	gho_up.AddFrame(52, 18, 16, 16);
	gho_up.AddFrame(52, 18, 16, 16);
	Data::GameplayData.GhostSprite.Animations.push_back(gho_up);
	Animation gho_down(4);
	gho_down.AddFrame(69, 18, 16, 16);
	gho_down.AddFrame(69, 18, 16, 16);
	gho_down.AddFrame(86, 18, 16, 16);
	gho_down.AddFrame(86, 18, 16, 16);
	Data::GameplayData.GhostSprite.Animations.push_back(gho_down);
	//Data::GameplayData.GhostSprite.Animations.push_back(gho_move);

	MainState state = MainMenu;

	NetworkManager::Init();

    while (Renderer::WindowOpen())
    {
		InputHandler::PollEvents();
		if (InputHandler::WindowClosed)
		{
			break;
		}

		update(state);
		render(state);
		if (state == Exiting)
		{
			break;
		}
    }

	Renderer::Deinit();
    return 0;
}

static void update(MainState &state)
{
	MainState s = process_data(state);
	if (s != state)
	{
		change(state, s);
		return;
	}

	s = local_update(state);
	if (s != state)
	{
		change(state, s);
		return;
	}
}

static void render(const MainState &state)
{
	Renderer::Clear();

	if (state == MainMenu)
	{
		std::vector<std::string> &Menu_EN = Data::MainMenuData.Menu_EN;
		Menu &menu = Data::MainMenuData.MenuItems;
		unsigned int index = Data::MainMenuData.Index;

		for (unsigned int i = 0; i < menu.size(); i++)
		{
			Renderer::DrawText(
					Data::Font, Menu_EN[menu[i].Text], 24, 60, 100 + 40 * i);
			if (i == index)
			{
				Renderer::DrawText(Data::Font, ">", 24, 20, 100 + 40 * i);
			}
		}
	}
	else if (state == Host)
	{
		int lobby_count = Data::HostData.PlayerCount;
		int clients_text = Data::ClientsText;

		std::string address = NetworkManager::GetAddress();
		unsigned short port = NetworkManager::GetPort();
		std::ostringstream ss;
		ss << address << ":" << port;
		std::string str = ss.str();
		Renderer::DrawText(Data::Font, str, 24, 60, 100);

		ss.str("");
		ss << "Clients connected: " << lobby_count;
		str = ss.str();
		Renderer::DrawText(Data::Font, str, 24, 60, 140);
	}
	else if (state == Join)
	{
		unsigned char *ip = Data::JoinData.IP;
		unsigned short &port = Data::JoinData.Port;
		unsigned int index = Data::JoinData.Index;

		std::ostringstream ss;
		ss.fill('0');
		ss << std::setw(3) << (unsigned short)ip[0] << "."
			<< std::setw(3) << (unsigned short)ip[1] << "."
			<< std::setw(3) << (unsigned short)ip[2] << "."
			<< std::setw(3) << (unsigned short)ip[3] << ":"
			<< std::setw(5) << port;
		std::string disp = ss.str();
		Renderer::DrawText(Data::Font, disp, 24, 60, 100);
		int iPos = index;
		if (index > 2) iPos++;
		if (index > 5) iPos++;
		if (index > 8) iPos++;
		if (index > 11) iPos++;
		Renderer::DrawText(Data::Font, "^", 24, 60 + 24 * iPos, 136);
	}
	else if (state == ClientWaiting)
	{
		Renderer::DrawText(Data::Font, "Connecting...", 24, 60, 100);
	}
	else if (state == ClientConnected)
	{
		std::ostringstream ss;
		ss << "You are Player ";
		ss << Data::ClientConnectedData.PlayerNumber + 1;
		std::string str = ss.str();
		Renderer::DrawText(Data::Font, str, 24, 60, 100);
		Character c = Data::ClientConnectedData.SelectedCharacter;
		bool ready = Data::ClientConnectedData.Ready;
		unsigned int index = Data::ClientConnectedData.Index;
		if (c == Pacman_c)
		{
			Renderer::DrawText(Data::Font, "< Pac-Man >", 20, 60, 140);
		}
		else
		{
			Renderer::DrawText(Data::Font, "<  Ghost  >", 20, 60, 140);
		}
		if (ready)
		{
			Renderer::DrawText(Data::Font, "< Ready!", 20, 60, 180);
		}
		else
		{
			Renderer::DrawText(Data::Font, "  Ready? >", 20, 60, 180);
		}
		Renderer::DrawText(Data::Font, ">", 20, 20, 140 + 40 * index);
	}
	else if (state == Gameplay)
	{
		Game *game = Data::GameplayData.Local;
		unsigned int &frame = Data::GameplayData.AnimFrame;

		for (unsigned int i = 0; i < game->Players.size(); i++)
		{
			game->Players[i]->Draw();
		}
	}
	else if (state == Exiting) { }
	Renderer::Display();
}

static void change(MainState &state, MainState nextState)
{
	state = nextState;
	if (nextState == MainMenu)
	{
		NetworkManager::ResetConnections();
	}
	else if (nextState == Host)
	{
		Data::HostData.PlayerCount = 0;
	}
	else if (nextState == Join) { }
	else if (nextState == ClientWaiting) { }
	else if (nextState == ClientConnected) { }
	else if (nextState == Gameplay)
	{
		Field f;
		for (int i = 0; i < FIELD_WIDTH; i++)
		{
			for (int j = 0; j < FIELD_HEIGHT; j++)
			{
				if (i == 0 || i == FIELD_WIDTH - 1 || j == 0 || j == FIELD_HEIGHT - 1)
				{
					f.Tiles[i][j] = Field::Wall;
				}
				else
				{
					f.Tiles[i][j] = Field::Empty;
				}
			}
		}

		unsigned int count = Data::GameplayData.PlayerCount;
		Data::GameplayData.PlayerNumber =
			Data::ClientConnectedData.PlayerNumber;
		Data::GameplayData.PlayerInputs =
			std::vector<std::vector<Player::Direction> >(
				count,
				std::vector<Player::Direction>(
					InputData_size, Player::Right));
		Data::GameplayData.ReceivedFrames = std::vector<unsigned short>(count);
		std::vector<Player *> pl, ps;
		for (unsigned int i = 0; i < count; i++)
		{
			if (Data::GameplayData.Characters[i] == Pacman_c)
			{
				pl.push_back(new Pacman());
				ps.push_back(new Pacman());
			}
			else if (Data::GameplayData.Characters[i] == Ghost_c)
			{
				pl.push_back(new Ghost());
				ps.push_back(new Ghost());
			}
		}
		Data::GameplayData.Local = new Game(f, pl);
		Data::GameplayData.Synced = new Game(f, ps);
		// TODO: delete these
	}
	else if (nextState == Exiting) { }
}
<commit_msg>Text size adjustment<commit_after>//! \file
//! Entry point

#include <map>
#include <string>
#include <vector>
#include <sstream>
#include <iomanip>
#include "MainState.h"
#include "Renderer.h"
#include "InputHandler.h"
#include "NetworkManager.h"
#include "Data.h"
#include "local_update.h"
#include "process_packets.h"

static void update(MainState &state);
static void render(const MainState &state);
static void change(MainState &state, MainState nextState);

int main()
{
	Data::MainMenuData.Menu_EN.push_back("Host game");
	Data::MainMenuData.Menu_EN.push_back("Join game");
	Data::MainMenuData.Menu_EN.push_back("Quit");

	Data::Font = Renderer::LoadFont("../prstartk.ttf");

	MenuItem item1, item2, item3;
	item1.Text = 0;
	item1.Function = Host;
	Data::MainMenuData.MenuItems.push_back(item1);
	item2.Text = 1;
	item2.Function = Join;
	Data::MainMenuData.MenuItems.push_back(item2);
	item3.Text = 2;
	item3.Function = Exiting;
	Data::MainMenuData.MenuItems.push_back(item3);

	Renderer::TileScale = 6.0f;
	Renderer::SpriteScale = 3.0f;
	Renderer::CreateWindow(768, 768, "My window");

	Data::GameplayData.PacmanSprite.Index =
		Renderer::CreateSprite("../pacman.png");
	Data::GameplayData.GhostSprite.Index =
		Renderer::CreateSprite("../pacman.png");

	Data::JoinData.IP[0] = 127;
	Data::JoinData.IP[1] = 0;
	Data::JoinData.IP[2] = 0;
	Data::JoinData.IP[3] = 1;
	Data::JoinData.Port = 0;

	Animation pac_move(4);
	//pac_move.AddFrame(34, 170, 32, 32);
	//pac_move.AddFrame(1, 170, 32, 32);
	//pac_move.AddFrame(34, 170, 32, 32);
	//pac_move.AddFrame(67, 170, 32, 32);
	pac_move.AddFrame(18, 1, 16, 16);
	pac_move.AddFrame(35, 1, 16, 16);
	pac_move.AddFrame(18, 1, 16, 16);
	pac_move.AddFrame(1, 1, 16, 16);
	Data::GameplayData.PacmanSprite.Animations.push_back(pac_move);
	Data::GameplayData.AnimFrame = 0;

	//Animation gho_move(4);
	//gho_move.AddFrame(196, 105, 32, 32);
	//gho_move.AddFrame(196, 105, 32, 32);
	//gho_move.AddFrame(229, 105, 32, 32);
	//gho_move.AddFrame(229, 105, 32, 32);
	Animation gho_hori(4);
	gho_hori.AddFrame(1, 18, 16, 16);
	gho_hori.AddFrame(1, 18, 16, 16);
	gho_hori.AddFrame(18, 18, 16, 16);
	gho_hori.AddFrame(18, 18, 16, 16);
	Data::GameplayData.GhostSprite.Animations.push_back(gho_hori);
	Animation gho_up(4);
	gho_up.AddFrame(35, 18, 16, 16);
	gho_up.AddFrame(35, 18, 16, 16);
	gho_up.AddFrame(52, 18, 16, 16);
	gho_up.AddFrame(52, 18, 16, 16);
	Data::GameplayData.GhostSprite.Animations.push_back(gho_up);
	Animation gho_down(4);
	gho_down.AddFrame(69, 18, 16, 16);
	gho_down.AddFrame(69, 18, 16, 16);
	gho_down.AddFrame(86, 18, 16, 16);
	gho_down.AddFrame(86, 18, 16, 16);
	Data::GameplayData.GhostSprite.Animations.push_back(gho_down);
	//Data::GameplayData.GhostSprite.Animations.push_back(gho_move);

	MainState state = MainMenu;

	NetworkManager::Init();

    while (Renderer::WindowOpen())
    {
		InputHandler::PollEvents();
		if (InputHandler::WindowClosed)
		{
			break;
		}

		update(state);
		render(state);
		if (state == Exiting)
		{
			break;
		}
    }

	Renderer::Deinit();
    return 0;
}

static void update(MainState &state)
{
	MainState s = process_data(state);
	if (s != state)
	{
		change(state, s);
		return;
	}

	s = local_update(state);
	if (s != state)
	{
		change(state, s);
		return;
	}
}

static void render(const MainState &state)
{
	Renderer::Clear();

	if (state == MainMenu)
	{
		std::vector<std::string> &Menu_EN = Data::MainMenuData.Menu_EN;
		Menu &menu = Data::MainMenuData.MenuItems;
		unsigned int index = Data::MainMenuData.Index;

		for (unsigned int i = 0; i < menu.size(); i++)
		{
			Renderer::DrawText(
					Data::Font, Menu_EN[menu[i].Text], 24, 60, 100 + 40 * i);
			if (i == index)
			{
				Renderer::DrawText(Data::Font, ">", 24, 20, 100 + 40 * i);
			}
		}
	}
	else if (state == Host)
	{
		int lobby_count = Data::HostData.PlayerCount;
		int clients_text = Data::ClientsText;

		std::string address = NetworkManager::GetAddress();
		unsigned short port = NetworkManager::GetPort();
		std::ostringstream ss;
		ss << address << ":" << port;
		std::string str = ss.str();
		Renderer::DrawText(Data::Font, str, 24, 60, 100);

		ss.str("");
		ss << "Clients connected: " << lobby_count;
		str = ss.str();
		Renderer::DrawText(Data::Font, str, 24, 60, 140);
	}
	else if (state == Join)
	{
		unsigned char *ip = Data::JoinData.IP;
		unsigned short &port = Data::JoinData.Port;
		unsigned int index = Data::JoinData.Index;

		std::ostringstream ss;
		ss.fill('0');
		ss << std::setw(3) << (unsigned short)ip[0] << "."
			<< std::setw(3) << (unsigned short)ip[1] << "."
			<< std::setw(3) << (unsigned short)ip[2] << "."
			<< std::setw(3) << (unsigned short)ip[3] << ":"
			<< std::setw(5) << port;
		std::string disp = ss.str();
		Renderer::DrawText(Data::Font, disp, 24, 60, 100);
		int iPos = index;
		if (index > 2) iPos++;
		if (index > 5) iPos++;
		if (index > 8) iPos++;
		if (index > 11) iPos++;
		Renderer::DrawText(Data::Font, "^", 24, 60 + 24 * iPos, 136);
	}
	else if (state == ClientWaiting)
	{
		Renderer::DrawText(Data::Font, "Connecting...", 24, 60, 100);
	}
	else if (state == ClientConnected)
	{
		std::ostringstream ss;
		ss << "You are Player ";
		ss << Data::ClientConnectedData.PlayerNumber + 1;
		std::string str = ss.str();
		Renderer::DrawText(Data::Font, str, 24, 60, 100);
		Character c = Data::ClientConnectedData.SelectedCharacter;
		bool ready = Data::ClientConnectedData.Ready;
		unsigned int index = Data::ClientConnectedData.Index;
		if (c == Pacman_c)
		{
			Renderer::DrawText(Data::Font, "< Pac-Man >", 18, 60, 140);
		}
		else
		{
			Renderer::DrawText(Data::Font, "<  Ghost  >", 18, 60, 140);
		}
		if (ready)
		{
			Renderer::DrawText(Data::Font, "< Ready!", 18, 60, 180);
		}
		else
		{
			Renderer::DrawText(Data::Font, "  Ready? >", 18, 60, 180);
		}
		Renderer::DrawText(Data::Font, ">", 18, 20, 140 + 40 * index);
	}
	else if (state == Gameplay)
	{
		Game *game = Data::GameplayData.Local;
		unsigned int &frame = Data::GameplayData.AnimFrame;

		for (unsigned int i = 0; i < game->Players.size(); i++)
		{
			game->Players[i]->Draw();
		}
	}
	else if (state == Exiting) { }
	Renderer::Display();
}

static void change(MainState &state, MainState nextState)
{
	state = nextState;
	if (nextState == MainMenu)
	{
		NetworkManager::ResetConnections();
	}
	else if (nextState == Host)
	{
		Data::HostData.PlayerCount = 0;
	}
	else if (nextState == Join) { }
	else if (nextState == ClientWaiting) { }
	else if (nextState == ClientConnected) { }
	else if (nextState == Gameplay)
	{
		Field f;
		for (int i = 0; i < FIELD_WIDTH; i++)
		{
			for (int j = 0; j < FIELD_HEIGHT; j++)
			{
				if (i == 0 || i == FIELD_WIDTH - 1 || j == 0 || j == FIELD_HEIGHT - 1)
				{
					f.Tiles[i][j] = Field::Wall;
				}
				else
				{
					f.Tiles[i][j] = Field::Empty;
				}
			}
		}

		unsigned int count = Data::GameplayData.PlayerCount;
		Data::GameplayData.PlayerNumber =
			Data::ClientConnectedData.PlayerNumber;
		Data::GameplayData.PlayerInputs =
			std::vector<std::vector<Player::Direction> >(
				count,
				std::vector<Player::Direction>(
					InputData_size, Player::Right));
		Data::GameplayData.ReceivedFrames = std::vector<unsigned short>(count);
		std::vector<Player *> pl, ps;
		for (unsigned int i = 0; i < count; i++)
		{
			if (Data::GameplayData.Characters[i] == Pacman_c)
			{
				pl.push_back(new Pacman());
				ps.push_back(new Pacman());
			}
			else if (Data::GameplayData.Characters[i] == Ghost_c)
			{
				pl.push_back(new Ghost());
				ps.push_back(new Ghost());
			}
		}
		Data::GameplayData.Local = new Game(f, pl);
		Data::GameplayData.Synced = new Game(f, ps);
		// TODO: delete these
	}
	else if (nextState == Exiting) { }
}
<|endoftext|>


<commit_before>8a5e04a1-4b02-11e5-bf5b-28cfe9171a43<commit_msg>The previous fix has been fixed<commit_after>8a69ddc2-4b02-11e5-98ce-28cfe9171a43<|endoftext|>


<commit_before>//#include <stdio.h>
//#include<Model.hpp>
//
//
//int main()
//{
//	printf("Hello World!\n");
//	Model model;
//	model.Import("spider.fbx");
//	model.Import("spider.fbx");
//	getchar();
//	return 0;
//}

#include <stdio.h>
#include <GL/glew.h>

#include <SDL/SDL.h>
#include <SDL/SDL_image.h>

#include <Camera.hpp>
#include<Model.hpp>
#include<VAO.hpp>
#include <VBO.hpp>
#include <ShaderProgram.hpp>
//extern "C" { FILE __iob_func[3] = { *stdin,*stdout,*stderr }; }
//#pragma comment(lib, "legacy_stdio_definitions.lib")

#include<vector>

void renderTexture(SDL_Texture *tex, SDL_Renderer *ren, int x, int y){
	//Setup the destination rectangle to be at the position we want
	SDL_Rect dst;
	dst.x = x;
	dst.y = y;
	//Query the texture to get its width and height to use
	SDL_QueryTexture(tex, NULL, NULL, &dst.w, &dst.h);
	SDL_RenderCopy(ren, tex, NULL, &dst);
}

static const float vertex_list[] =
{
	-0.5f, -0.5f, -0.5f,
	0.5f, -0.5f, -0.5f,
	-0.5f, 0.5f, -0.5f,
	0.5f, 0.5f, -0.5f,
	-0.5f, -0.5f, 0.5f,
	0.5f, -0.5f, 0.5f,
	-0.5f, 0.5f, 0.5f,
	0.5f, 0.5f, 0.5f,
};

static const GLint index_list[] =
{
	0, 1,
	2, 3,
	4, 5,
	6, 7,
	0, 2,
	1, 3,
	4, 6,
	5, 7,
	0, 4,
	1, 5,
	7, 3,
	2, 6
};
Camera *camera;
void initCamera(){
	Vector3d pos(0.0, 0.0, 12.0);
	Vector3d target(0.0, 0.0, 0.0);
	Vector3d up(0.0, 1.0, 0.0);
	camera = new Camera(pos, target, up);

}

void RotateX(float angle)
{
	float d = camera->getDist();
	int cnt = 100;
	float theta = angle / cnt;
	float slide_d = -2 * d*sin(theta*3.14159265 / 360);
	camera->yaw(theta / 2);
	for (; cnt != 0; --cnt)
	{
		camera->slide(slide_d, 0, 0);
		camera->yaw(theta);
	}
	camera->yaw(-theta / 2);
}

void RotateY(float angle)
{
	float d = camera->getDist();
	int cnt = 100;
	float theta = angle / cnt;
	float slide_d = 2 * d*sin(theta*3.14159265 / 360);
	camera->pitch(theta / 2);
	for (; cnt != 0; --cnt)
	{
		camera->slide(0, slide_d, 0);
		camera->pitch(theta);
	}
	camera->pitch(-theta / 2);
}

int main(int argc, char* args[])
{
	SDL_Window	*pWindow = NULL;
	SDL_Renderer*pRenderer = NULL;
	int win_width = 640, win_height = 480;
	// 1. initialize SDL
	if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
	{
		printf("SDL initialize fail:%s\n", SDL_GetError());
		return 1;
	}

	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	// 2. create window
	pWindow = SDL_CreateWindow("LuaSDL",
		SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
		win_width, win_height,
		SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
	if (NULL == pWindow)
	{
		printf("Create window fail:%s\n", SDL_GetError());
	}

	SDL_GLContext glcontext = SDL_GL_CreateContext(pWindow);
	pRenderer = SDL_CreateRenderer(pWindow, -1, 0);
	glewInit();

	initCamera();

	glEnable(GL_DEPTH_TEST);
	glDepthRange(0.0, 10.0);
	glDepthFunc(GL_LEQUAL);
	glClearDepth(10.0);
	glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

	Model model;
	model.Import("box.fbx");

	//float tmp[100] = { 0 };
	//memcpy((void *)tmp, loder.mesh.buff.data, loder.mesh.buff.data_size);

	VAO g_vao;
	g_vao.init();
	const aiMesh* paiMesh = model.scene->mMeshes[0];
	cout << " "<<paiMesh->mNumVertices <<endl;

	int index = g_vao.newVBO(paiMesh->mNumVertices * 3*sizeof(float), (void *)paiMesh->mVertices);
	//int index = g_vao.newVBO(sizeof(vertex_list)*sizeof(float),(void *) vertex_list);

	glEnableVertexAttribArray(0);//????vbo
	glVertexAttribPointer((GLuint)0, 3, GL_FLOAT, true, 0, 0);
	//
	//	int ele_index[] = { 0, 1, 2, 4,5,6  ,7};
	ShaderProgram SP;
	int programShader = SP.buildShader("vert.txt", "frag.txt");
	glUseProgram(programShader);

	float uv[] = {
		0.0, 0.0,
		1.0, 0.0,
		1.0, 1.0,
		0.0, 1.0,
		0.0, 0.0,
		1.0, 0.0,
		1.0, 1.0,
		0.0, 1.0
	};
	//index = g_vao.newVBO(sizeof(uv), (void *)uv);
	//glEnableVertexAttribArray(1);
	//glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0);

	index = g_vao.newVBO(paiMesh->mNumVertices * sizeof(float), (void *)paiMesh->mTextureCoords[0]);
	glEnableVertexAttribArray(1);
	glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0);

	//http://ogldev.atspace.co.uk/www/tutorial22/tutorial22.html
	//http://wiki.jikexueyuan.com/project/modern-opengl-tutorial/tutorial22.html
	//http://assimp.sourceforge.net/lib_html/structai_mesh.html

	vector<int> Indices;
	for (unsigned int i = 0; i < paiMesh->mNumFaces; i++) {
		const aiFace& Face = paiMesh->mFaces[i];
		assert(Face.mNumIndices == 3);
		Indices.push_back(Face.mIndices[0]);
		Indices.push_back(Face.mIndices[1]);
		Indices.push_back(Face.mIndices[2]);
	}

	g_vao.initEBO(Indices.size() * sizeof(int), (void *)&Indices[0]);

	float arg = 1.0;
	int loc = glGetUniformLocation(programShader, "a");
	glUniform1f(loc, arg);

	SDL_Surface * img = IMG_Load("f.jpg");

	SDL_Surface* Picturenew = SDL_ConvertSurfaceFormat(img, SDL_PIXELFORMAT_ABGR8888, 0);

	GLuint texture_id = 0;
	glGenTextures(1, &texture_id);
	glBindTexture(GL_TEXTURE_2D, texture_id);

	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, Picturenew->w, Picturenew->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, Picturenew->pixels);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	//   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapMode);
	//   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapMode);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

	//glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);

	glEnable(GL_TEXTURE_2D);

	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, texture_id);
	glUniform1f(glGetUniformLocation(programShader, "tex"), 0);

	glViewport(0, 0, (GLint)win_width, (GLint)win_height);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(45.0, (GLfloat)win_width / (GLfloat)win_height, 0.1, 1000.0);
	glMatrixMode(GL_MODELVIEW);
	gluLookAt(0.0, 0.0, 12.0, 0.0, 0.0, 0, 0.0, 1.0, 0.0);

	//glVertexAttrib1f(loc, 1.0);
	//glEnableVertexAttribArray(loc);
	//glVertexAttribPointer(loc, 1, GL_FLOAT, 0, 0, &arg);

	//	SDL_SetRenderDrawColor(pRenderer, 255, 255, 255, 255);
	//	SDL_RenderClear(pRenderer);

	//	SDL_RenderPresent(pRenderer);

	//	glTranslatef(0.0f, 0.0f, -20.0f);

	//	SDL_Texture *texture = SDL_CreateTextureFromSurface(pRenderer, img);
	//	renderTexture(texture, pRenderer, 0, 0);
	//	SDL_RenderPresent(pRenderer);

	//	glUseProgram(0);

	bool quit = false;
	int x = 0, y = 0;
	Vector2i lastPos;
	int dx, dy;
	SDL_Event e;
	while (!quit){
		while (SDL_PollEvent(&e)){

			switch (e.type){
			case SDL_QUIT:
				quit = true;
				break;
			case SDL_KEYDOWN:
				switch (e.key.keysym.sym)
				{
				case SDLK_ESCAPE: quit = true; break;
				case SDLK_x: x = x + 1; break;
				case SDLK_y: y = y - 1; break;

				default:
					break;
				}
				break;
			case SDL_MOUSEBUTTONDOWN:
				lastPos << e.button.x, e.button.y;
				if (e.button.button == SDL_BUTTON_LEFT){

				}
				if (e.button.button == SDL_BUTTON_RIGHT){

				}
				if (e.button.button == SDL_BUTTON_MIDDLE){

				}
				break;
			case SDL_MOUSEMOTION:
				dx = e.button.x - lastPos.x();
				dy = e.button.y - lastPos.y();

				switch (e.button.button)
				{
				case SDL_BUTTON_LEFT:
					RotateX(dx);
					RotateY(dy);
					break;
				case SDL_BUTTON_RIGHT:
					camera->roll(dx);
					break;
				case SDL_BUTTON_MIDDLE:
					camera->slide(-dx, dy, 0);
					break;
				}

				lastPos << e.button.x, e.button.y;
				break;
			case SDL_MOUSEWHEEL:

				camera->slide(0, 0, -e.wheel.y);
				break;
			}
		}
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		glBegin(GL_TRIANGLES);
		glTexCoord2f(0.0, 0.0);// glColor3f(0.0f, 1.0f, 0.0f);
		glVertex3f(0.0f, 1.0f, -0.5f);

		glTexCoord2f(1.0, 0.0);// glColor3f(1.0f,0.0f,0.0f);
		glVertex3f(-1.0f, -1.0f, 2.0f);

		glTexCoord2f(0.0, 1.0); //glColor3f(0.0f, 0.0f, 1.0f);
		glVertex3f(1.0f, -1.0f, -0.5f);
		glEnd();

		arg = (arg + 0.1);
		int tmpint = (int)arg;
		arg = arg - tmpint;
		glUniform1f(loc, arg);

		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		camera->setModelViewMatrix();

		//glDrawElements(GL_LINE_STRIP, 3, GL_UNSIGNED_INT, 0);
		glDrawElements(GL_TRIANGLES, Indices.size() , GL_UNSIGNED_INT, 0);//GL_LINES GL_LINE_LOOP

		SDL_GL_SwapWindow(pWindow);
		SDL_Delay(100);

	}

	SDL_Quit();
	return 1;
}<commit_msg>贴图正常了<commit_after>//#include <stdio.h>
//#include<Model.hpp>
//
//
//int main()
//{
//	printf("Hello World!\n");
//	Model model;
//	model.Import("spider.fbx");
//	model.Import("spider.fbx");
//	getchar();
//	return 0;
//}

#include <stdio.h>
#include <GL/glew.h>

#include <SDL/SDL.h>
#include <SDL/SDL_image.h>

#include <Camera.hpp>
#include<Model.hpp>
#include<VAO.hpp>
#include <VBO.hpp>
#include <ShaderProgram.hpp>
//extern "C" { FILE __iob_func[3] = { *stdin,*stdout,*stderr }; }
//#pragma comment(lib, "legacy_stdio_definitions.lib")

#include<vector>

void renderTexture(SDL_Texture *tex, SDL_Renderer *ren, int x, int y){
	//Setup the destination rectangle to be at the position we want
	SDL_Rect dst;
	dst.x = x;
	dst.y = y;
	//Query the texture to get its width and height to use
	SDL_QueryTexture(tex, NULL, NULL, &dst.w, &dst.h);
	SDL_RenderCopy(ren, tex, NULL, &dst);
}

static const float vertex_list[] =
{
	-0.5f, -0.5f, -0.5f,
	0.5f, -0.5f, -0.5f,
	-0.5f, 0.5f, -0.5f,
	0.5f, 0.5f, -0.5f,
	-0.5f, -0.5f, 0.5f,
	0.5f, -0.5f, 0.5f,
	-0.5f, 0.5f, 0.5f,
	0.5f, 0.5f, 0.5f,
};

static const GLint index_list[] =
{
	0, 1,
	2, 3,
	4, 5,
	6, 7,
	0, 2,
	1, 3,
	4, 6,
	5, 7,
	0, 4,
	1, 5,
	7, 3,
	2, 6
};
Camera *camera;
void initCamera(){
	Vector3d pos(0.0, 0.0, 12.0);
	Vector3d target(0.0, 0.0, 0.0);
	Vector3d up(0.0, 1.0, 0.0);
	camera = new Camera(pos, target, up);

}

void RotateX(float angle)
{
	float d = camera->getDist();
	int cnt = 100;
	float theta = angle / cnt;
	float slide_d = -2 * d*sin(theta*3.14159265 / 360);
	camera->yaw(theta / 2);
	for (; cnt != 0; --cnt)
	{
		camera->slide(slide_d, 0, 0);
		camera->yaw(theta);
	}
	camera->yaw(-theta / 2);
}

void RotateY(float angle)
{
	float d = camera->getDist();
	int cnt = 100;
	float theta = angle / cnt;
	float slide_d = 2 * d*sin(theta*3.14159265 / 360);
	camera->pitch(theta / 2);
	for (; cnt != 0; --cnt)
	{
		camera->slide(0, slide_d, 0);
		camera->pitch(theta);
	}
	camera->pitch(-theta / 2);
}

int main(int argc, char* args[])
{
	SDL_Window	*pWindow = NULL;
	SDL_Renderer*pRenderer = NULL;
	int win_width = 640, win_height = 480;
	// 1. initialize SDL
	if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
	{
		printf("SDL initialize fail:%s\n", SDL_GetError());
		return 1;
	}

	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	// 2. create window
	pWindow = SDL_CreateWindow("LuaSDL",
		SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
		win_width, win_height,
		SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
	if (NULL == pWindow)
	{
		printf("Create window fail:%s\n", SDL_GetError());
	}

	SDL_GLContext glcontext = SDL_GL_CreateContext(pWindow);
	pRenderer = SDL_CreateRenderer(pWindow, -1, 0);
	glewInit();

	initCamera();

	glEnable(GL_DEPTH_TEST);
	glDepthRange(0.0, 10.0);
	glDepthFunc(GL_LEQUAL);
	glClearDepth(10.0);
	glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

	Model model;
	model.Import("spider.fbx");

	//float tmp[100] = { 0 };
	//memcpy((void *)tmp, loder.mesh.buff.data, loder.mesh.buff.data_size);

	VAO g_vao;
	g_vao.init();
	const aiMesh* paiMesh = model.scene->mMeshes[0];
	cout << " "<<paiMesh->mNumVertices <<endl;

	int index = g_vao.newVBO(paiMesh->mNumVertices * 3*sizeof(float), (void *)paiMesh->mVertices);
	//int index = g_vao.newVBO(sizeof(vertex_list)*sizeof(float),(void *) vertex_list);

	glEnableVertexAttribArray(0);//????vbo
	glVertexAttribPointer((GLuint)0, 3, GL_FLOAT, true, 0, 0);
	//
	//	int ele_index[] = { 0, 1, 2, 4,5,6  ,7};
	ShaderProgram SP;
	int programShader = SP.buildShader("vert.txt", "frag.txt");
	glUseProgram(programShader);

	float uv1[] = {
		0.0, 0.0,
		1.0, 0.0,
		1.0, 1.0,
		0.0, 1.0,
		0.0, 0.0,
		1.0, 0.0,
		1.0, 1.0,
		0.0, 1.0
	};
	//index = g_vao.newVBO(sizeof(uv), (void *)uv);
	//glEnableVertexAttribArray(1);
	//glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0);
	cout << "Ƿ꣺" << paiMesh->HasTextureCoords(0) << endl;
	vector<float> uv;
	for (unsigned int i = 0; i < paiMesh->mNumVertices; i++) {
		const aiVector3D* pTexCoord =&(paiMesh->mTextureCoords[0][i]);
		uv.push_back(pTexCoord->x);
		uv.push_back(pTexCoord->y);
	}
	//const aiVector3D* pTexCoord = paiMesh->HasTextureCoords(0) ? &(paiMesh->mTextureCoords[0][i]) : &Zero3D;
	index = g_vao.newVBO(uv.size() * sizeof(float), (void *)&uv[0]);
	glEnableVertexAttribArray(1);
	glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0);

	//http://ogldev.atspace.co.uk/www/tutorial22/tutorial22.html
	//http://wiki.jikexueyuan.com/project/modern-opengl-tutorial/tutorial22.html
	//http://assimp.sourceforge.net/lib_html/structai_mesh.html

	vector<int> Indices;
	for (unsigned int i = 0; i < paiMesh->mNumFaces; i++) {
		const aiFace& Face = paiMesh->mFaces[i];
		assert(Face.mNumIndices == 3);
		Indices.push_back(Face.mIndices[0]);
		Indices.push_back(Face.mIndices[1]);
		Indices.push_back(Face.mIndices[2]);
	}

	g_vao.initEBO(Indices.size() * sizeof(int), (void *)&Indices[0]);

	float arg = 1.0;
	int loc = glGetUniformLocation(programShader, "a");
	glUniform1f(loc, arg);

	SDL_Surface * img = IMG_Load("f.jpg");

	SDL_Surface* Picturenew = SDL_ConvertSurfaceFormat(img, SDL_PIXELFORMAT_ABGR8888, 0);

	GLuint texture_id = 0;
	glGenTextures(1, &texture_id);
	glBindTexture(GL_TEXTURE_2D, texture_id);

	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, Picturenew->w, Picturenew->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, Picturenew->pixels);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	//   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapMode);
	//   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapMode);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

	//glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);

	glEnable(GL_TEXTURE_2D);

	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, texture_id);
	glUniform1f(glGetUniformLocation(programShader, "tex"), 0);

	glViewport(0, 0, (GLint)win_width, (GLint)win_height);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(45.0, (GLfloat)win_width / (GLfloat)win_height, 0.1, 1000.0);
	glMatrixMode(GL_MODELVIEW);
	gluLookAt(0.0, 0.0, 12.0, 0.0, 0.0, 0, 0.0, 1.0, 0.0);

	//glVertexAttrib1f(loc, 1.0);
	//glEnableVertexAttribArray(loc);
	//glVertexAttribPointer(loc, 1, GL_FLOAT, 0, 0, &arg);

	//	SDL_SetRenderDrawColor(pRenderer, 255, 255, 255, 255);
	//	SDL_RenderClear(pRenderer);

	//	SDL_RenderPresent(pRenderer);

	//	glTranslatef(0.0f, 0.0f, -20.0f);

	//	SDL_Texture *texture = SDL_CreateTextureFromSurface(pRenderer, img);
	//	renderTexture(texture, pRenderer, 0, 0);
	//	SDL_RenderPresent(pRenderer);

	//	glUseProgram(0);

	bool quit = false;
	int x = 0, y = 0;
	Vector2i lastPos;
	int dx, dy;
	SDL_Event e;
	while (!quit){
		while (SDL_PollEvent(&e)){

			switch (e.type){
			case SDL_QUIT:
				quit = true;
				break;
			case SDL_KEYDOWN:
				switch (e.key.keysym.sym)
				{
				case SDLK_ESCAPE: quit = true; break;
				case SDLK_x: x = x + 1; break;
				case SDLK_y: y = y - 1; break;

				default:
					break;
				}
				break;
			case SDL_MOUSEBUTTONDOWN:
				lastPos << e.button.x, e.button.y;
				if (e.button.button == SDL_BUTTON_LEFT){

				}
				if (e.button.button == SDL_BUTTON_RIGHT){

				}
				if (e.button.button == SDL_BUTTON_MIDDLE){

				}
				break;
			case SDL_MOUSEMOTION:
				dx = e.button.x - lastPos.x();
				dy = e.button.y - lastPos.y();

				switch (e.button.button)
				{
				case SDL_BUTTON_LEFT:
					RotateX(dx);
					RotateY(dy);
					break;
				case SDL_BUTTON_RIGHT:
					camera->roll(dx);
					break;
				case SDL_BUTTON_MIDDLE:
					camera->slide(-dx, dy, 0);
					break;
				}

				lastPos << e.button.x, e.button.y;
				break;
			case SDL_MOUSEWHEEL:

				camera->slide(0, 0, -e.wheel.y);
				break;
			}
		}
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		arg = (arg + 0.1);
		int tmpint = (int)arg;
		arg = arg - tmpint;
		glUniform1f(loc, arg);

		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		camera->setModelViewMatrix();

		//glDrawElements(GL_LINE_STRIP, 3, GL_UNSIGNED_INT, 0);
		glDrawElements(GL_TRIANGLES, Indices.size() , GL_UNSIGNED_INT, 0);//GL_LINES GL_LINE_LOOP

		SDL_GL_SwapWindow(pWindow);
		SDL_Delay(100);

	}

	SDL_Quit();
	return 1;
}<|endoftext|>


<commit_before>dfc38802-4b02-11e5-b645-28cfe9171a43<commit_msg>I hope I am done<commit_after>dfd0887d-4b02-11e5-bdf6-28cfe9171a43<|endoftext|>


<commit_before><commit_msg>merging<commit_after>using namespace std;

#include <iostream>
#include <string>
#include <vector>
//need these?
#include <unistd.h>     // getpid(), getcwd()
#include <sys/types.h>  // type definitions, e.g., pid_t
#include <sys/wait.h>   // wait()
#include <signal.h>     // signal name constants and kill()
#include <boost/algorithm/string.hpp>   // boost::trim_left(string s);

//Here goes the #include "files"
#include "Command.h"
#include "Connector.h"
#include "Connector.cpp"
// #include "Command.cpp"

/*
#include "command.h"                        //jose's main.cpp

int main() {

    string s = "";

    cout << "$: ";
    getline(cin, s);

    Command input(s);
    input.launch();

    return 0;
}
*/

/*
1.  add error checks for consecutive connectors (;; should be fine?)

5.  syntax ERROR: "bash: syntax error near unexpected token `||'"

ls; lsf && echo a; echo a; && lsf; lfs || echo a && echo b; echo a || lsf && echo b
*/

int main()
{

    while(true)                                     //each newline
    {
        string input = "";
        string com = "";                          //each command
        cout << "$ ";
        getline (cin,input);
        vector <string> v;                        //vector of inputs: normal, &&, ||, ;
        for(int i = 0; i < input.size(); i++)       //reads input
        {
            if(input.at(i) == '#')                  //comments out the rest
            {
                break;                  //need to double check if it still
                                        //works if you type \# or somehting
            }
            if(input.at(i) == ';')
            {
                v.push_back(com);
                v.push_back(";");
                com = "";
            }
            else
            {
                if(i < input.size()-1 && input.at(i) == '&' && input.at(i+1)=='&')  //&&
                {
                    i++;
                    v.push_back(com);
                    v.push_back("&&");
                    com = "";
                }
                else if(i < input.size()-1 && input.at(i) == '|' && input.at(i+1)=='|')     //||
                {
                    i++;
                    v.push_back(com);
                    v.push_back("||");
                    com = "";
                }
                else
                    com += input.at(i);               //adds to the string to be read
            }
        }
        v.push_back(com);
        bool checker = false;

        //remove this
        cout<<"input # size: " << v.size()<<endl;
        if(v.size() == 1)
        {
            cout<<"["<<v.at(0)<<"]"<<endl;
        }

        for(int i = 0; i< v.size(); i++)                         //read through v
        {
            if(v.at(i) == "exit")
            {
                return 0;
            }
            if(v.at(i) == ";")
            {
                //  cout<<"SEMI"<<endl;
            }
            else if(v.at(i) == "&&")
            {
                boost::trim_left(v.at(i+1));
                // cout<<"&&: ["<< v.at(i+1)<<"]"<<endl;
                andConnector* a = new andConnector(checker, v.at(i+1));
                i++;
                checker = a->getValidity();              //truth value of &&
                // cout<<v.at(i)<<endl;
            }
            else if(v.at(i) == "||")
            {
                boost::trim_left(v.at(i+1));
                // cout<<"||: ["<< v.at(i+1)<<"]"<<endl;
                orConnector* o = new orConnector(checker, v.at(i+1));
                i++;
                checker = o->getValidity();
            }
            else
            {

                boost::trim_left(v.at(i));

                if(v.at(i) == "exit")
                {
                    // cout<<"exited"<<endl;
                    return 0;
                }

                cout<<"Whats entering: " << v.at(i)<<endl;
                Command c(v.at(i));
                c.launch();
                checker = c.isValid();
                // cout<<v.at(i)<<endl;
            }

        }
    }
    return 0;
}

            // if(v.at(i)->type() == 2 || v.at(i)->type() == 3)    //v.at(i) is a connector
            // {
            //     //add error checks later
            //     v.at(i)->set(left,v.at(i+1));
            //     left = v.at(i);             //this is now the left most operator
            // }
            // if(v.at(i)->type() == 4)    //v.at(i) is a semi-colon;
            // {
            //     if(i < v.size() -1)
            //     {
            //         left = v.at(i+1);
            //     }
            // }<|endoftext|>


<commit_before>24585e59-ad5c-11e7-837b-ac87a332f658<commit_msg>This'll fix that<commit_after>2501310f-ad5c-11e7-b712-ac87a332f658<|endoftext|>


<commit_before>#include <iostream>
#include <algorithm>
#include <map>
std::string reverse(std::string thestring){
    std::reverse(thestring.begin(), thestring.end());
    return thestring;
}

bool isVowel(char let){
    char vowels[] = {'a','e','i','o','u'};
    for(int i=0; i < 5;i ++)
        if (let == vowels[i])
            return true;
    return false;
}

int countVowels(std::string str){
    int count = 0;
    count += std::count_if(str.begin(), str.end(),isVowel);
    return count;
}

bool isPalindrome(std::string str){
    if(str == reverse((str)))
        return true;
    else
        return false;
}

void eatWhite(std::string::iterator &it){
    while(isspace(*it)){
        ++it;
    }
}

int numWords(std::string str){
    int wordlen = 0;
    int numwords = 0;
    std::string::iterator it = str.begin();
    while(it != str.end()){
        wordlen = 0;
        if(isspace(*it))
            eatWhite(it);
        else if(isalnum(*it)){
            while(isalnum(*it)){
                ++it;
                ++wordlen;
            }
        }
        if(wordlen){
            ++numwords;
        }
    }
    return numwords;
}

std::string pigLatin(std::string str){
    std::string::iterator initbeg,beg;
    std::string::iterator end = str.end();
    initbeg=beg= str.begin();
    while( !isVowel(*beg) && beg != end){
        ++beg;
    }
    if(beg == end)
        return str + "ay";
    else{
        std::string piglatin(beg,end);
        std::string cons(initbeg,beg);
        return piglatin + cons + "ay";
    }
}

void getFirtNoRepeatCharacter(const std::string &str, std::map<char, int> &thechar){
    int pos = 0;
    for(auto const &it : str){
        if(thechar.find(it) == thechar.end() && thechar.empty()){
            thechar[it] = pos;
        }
        else{
            thechar.erase(it);
        }
        pos++;
    }

}

int main()
{
    std::string str="aaaaaabt";
    std::map<char, int> character;
    getNoRepeat(str, character);
    for(auto const &it : character)
        std::cout<<it.first<<"->"<<it.second<<std::endl;
    return 0;
}

<commit_msg>added pattern finding and fibonacci fuctions<commit_after>#include <iostream>
#include <algorithm>
#include <map>
#include <limits>
std::string reverse(std::string thestring){
    std::reverse(thestring.begin(), thestring.end());
    return thestring;
}

bool isVowel(char let){
    char vowels[] = {'a','e','i','o','u'};
    for(int i=0; i < 5;i ++)
        if (let == vowels[i])
            return true;
    return false;
}

int countVowels(std::string str){
    int count = 0;
    count += std::count_if(str.begin(), str.end(),isVowel);
    return count;
}

bool isPalindrome(std::string str){
    if(str == reverse((str)))
        return true;
    else
        return false;
}

void eatWhite(std::string::iterator &it){
    while(isspace(*it)){
        ++it;
    }
}

int numWords(std::string str){
    int wordlen = 0;
    int numwords = 0;
    std::string::iterator it = str.begin();
    while(it != str.end()){
        wordlen = 0;
        if(isspace(*it))
            eatWhite(it);
        else if(isalnum(*it)){
            while(isalnum(*it)){
                ++it;
                ++wordlen;
            }
        }
        if(wordlen){
            ++numwords;
        }
    }
    return numwords;
}

std::string pigLatin(std::string str){
    std::string::iterator initbeg,beg;
    std::string::iterator end = str.end();
    initbeg=beg= str.begin();
    while( !isVowel(*beg) && beg != end){
        ++beg;
    }
    if(beg == end)
        return str + "ay";
    else{
        std::string piglatin(beg,end);
        std::string cons(initbeg,beg);
        return piglatin + cons + "ay";
    }
}

void getFirtNoRepeatCharacter(const std::string &str, std::map<char, int> &thechar){
    int pos = 0;
    for(auto const &it : str){
        if(thechar.find(it) == thechar.end() && thechar.empty()){
            thechar[it] = pos;
        }
        else{
            thechar.erase(it);
        }
        pos++;
    }

}
void fibonacci(long int cur, long int prev=1, int count=0, int stopcount=10){
    if(count == stopcount)
        return;
    count++;
    std::cout<<cur<<std::endl;
    long int newcur = prev + cur;
    fibonacci(newcur, cur, count);
}

bool simplePatternMatch(const std::string &text, const std::string &pattern){
    auto pat_it = pattern.begin();
    for(auto const &it : text){
        if(it == *pat_it)
            pat_it++;
        else
            pat_it = pattern.begin();
        if(pat_it == pattern.end())
            return true;
    }
    return false;
}

int main()
{
    fibonacci(1);
    return 0;
}

<|endoftext|>


<commit_before>#include "Standard.h"
#include "glhelpers.h"
#include <SDL.h>

#include "ShaderStructs.h"

#include <btBulletCollisionCommon.h>
#include <btBulletDynamicsCommon.h>

#define GAMENAME "KartBounty"

int main( int argc, char** argv )
{
#ifdef _WIN32
#ifdef _DEBUG
	_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif
#endif

	SDL_Init( SDL_INIT_EVERYTHING );
	SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 ); // Test this with 4.0, 3.3, 3.2
	SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 3 );
	/*
	SDL_GL_SetAttribute( SDL_GL_ACCELERATED_VISUAL, 1 );
	SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE );
	SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); // SDL's default
	SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 24 );
	SDL_GL_SetSwapInterval( 1 );
	*/

	SDL_Window *win = SDL_CreateWindow( GAMENAME,
			SDL_WINDOWPOS_UNDEFINED,
			SDL_WINDOWPOS_UNDEFINED,
			800, 450, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE );
	if( !win )
		return 1;

#ifdef _WIN32
	if( !glhCreateContext( win ) )
		return 1;
#else
	SDL_GLContext glcontext = SDL_GL_CreateContext( win );
	if( !glcontext )
		return 1;

	SDL_GL_MakeCurrent( win, glcontext );
#endif

	if( glewInit() != GLEW_OK )
		return 1;

	GLint major, minor;
	glGetIntegerv( GL_MAJOR_VERSION, &major );
	glGetIntegerv( GL_MINOR_VERSION, &minor );

	const GLchar* aryHeaders[] = { "ShaderStructs.glsl" };
	GLeffect effect = glhLoadEffect( "VShader.glsl", NULL, "PShader.glsl", aryHeaders, 1 );
	if( !effect.program )
		return 1;

	GLbuffer permesh, perframe;
	if( !glhCreateBuffer( effect, "cstPerMesh", sizeof(cstPerMesh), &permesh ) )
		return 1;

	if( !glhCreateBuffer( effect, "cstPerFrame", sizeof(cstPerFrame), &perframe ) )
		return 1;

	cstPerMesh& perMesh = *(cstPerMesh*)permesh.data;
	cstPerFrame& perFrame = *(cstPerFrame*)perframe.data;

	glhCheckUniformNames( effect.program );

	int bRunning = 1;
	SDL_Event event;
	while( bRunning )
	{
		while( SDL_PollEvent( &event ) )
		{
			switch( event.type )
			{
				case SDL_QUIT:
					bRunning = 0;
					break;
			}
		}

		glClearColor( 0, 0, 0, 1 );
		glClear( GL_COLOR_BUFFER_BIT );

#ifdef _WIN32
		SwapBuffers( glhGetHDC() );
#else
		SDL_GL_SwapWindow(win);
#endif
	}

	glhDestroyBuffer( permesh );
	glhDestroyBuffer( perframe );
	glhUnloadEffect( effect );

	SDL_DestroyWindow( win );
	SDL_Quit();

	return 0;
}
<commit_msg>Fix order of GL version requesting<commit_after>#include "Standard.h"
#include "glhelpers.h"
#include <SDL.h>

#include "ShaderStructs.h"

#include <btBulletCollisionCommon.h>
#include <btBulletDynamicsCommon.h>

#define GAMENAME "KartBounty"

int main( int argc, char** argv )
{
#ifdef _WIN32
#ifdef _DEBUG
	_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif
#endif

	SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 ); // Test this with 4.0, 3.3, 3.2
	SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 3 );
	SDL_Init( SDL_INIT_EVERYTHING );

	SDL_Window *win = SDL_CreateWindow( GAMENAME,
			SDL_WINDOWPOS_UNDEFINED,
			SDL_WINDOWPOS_UNDEFINED,
			800, 450, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE );
	if( !win )
		return 1;

#ifdef _WIN32
	if( !glhCreateContext( win ) )
		return 1;
#else
	SDL_GLContext glcontext = SDL_GL_CreateContext( win );
	if( !glcontext )
		return 1;

	SDL_GL_MakeCurrent( win, glcontext );
#endif

	if( glewInit() != GLEW_OK )
		return 1;

	GLint major, minor;
	glGetIntegerv( GL_MAJOR_VERSION, &major );
	glGetIntegerv( GL_MINOR_VERSION, &minor );

	const GLchar* aryHeaders[] = { "ShaderStructs.glsl" };
	GLeffect effect = glhLoadEffect( "VShader.glsl", NULL, "PShader.glsl", aryHeaders, 1 );
	if( !effect.program )
		return 1;

	GLbuffer permesh, perframe;
	if( !glhCreateBuffer( effect, "cstPerMesh", sizeof(cstPerMesh), &permesh ) )
		return 1;

	if( !glhCreateBuffer( effect, "cstPerFrame", sizeof(cstPerFrame), &perframe ) )
		return 1;

	cstPerMesh& perMesh = *(cstPerMesh*)permesh.data;
	cstPerFrame& perFrame = *(cstPerFrame*)perframe.data;

	glhCheckUniformNames( effect.program );

	int bRunning = 1;
	SDL_Event event;
	while( bRunning )
	{
		while( SDL_PollEvent( &event ) )
		{
			switch( event.type )
			{
				case SDL_QUIT:
					bRunning = 0;
					break;
			}
		}

		glClearColor( 0, 0, 0, 1 );
		glClear( GL_COLOR_BUFFER_BIT );

#ifdef _WIN32
		SwapBuffers( glhGetHDC() );
#else
		SDL_GL_SwapWindow(win);
#endif
	}

	glhDestroyBuffer( permesh );
	glhDestroyBuffer( perframe );
	glhUnloadEffect( effect );

	SDL_DestroyWindow( win );
	SDL_Quit();

	return 0;
}
<|endoftext|>


<commit_before>83a7f294-ad5c-11e7-a216-ac87a332f658<commit_msg>I finished programming, there is nothing left to program<commit_after>84147400-ad5c-11e7-8087-ac87a332f658<|endoftext|>


<commit_before>a9409123-2747-11e6-91c4-e0f84713e7b8<commit_msg>This'll fix that<commit_after>a9513a68-2747-11e6-8174-e0f84713e7b8<|endoftext|>


<commit_before>#include <exception>
#include <iostream>
#include <memory>
#include <vector>

#include "engine/engine.hpp"
#include "engine/shader.hpp"
#include "engine/shader_program.hpp"
#include "engine/vertex_buffer.hpp"
#include "engine/window.hpp"

const char *vertex_shader_source = R"glsl(
#version 100

attribute vec4 position;
void main() {
    gl_Position = vec4(position);
}
)glsl";

const char *fragment_shader_source = R"glsl(
#version 100

precision mediump float;
void main() {
   gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
)glsl";

void loop() {
    window main_window;

    auto shaders = std::make_unique<std::vector<std::unique_ptr<shader>>>();
    shaders->push_back(std::make_unique<shader>(GL_VERTEX_SHADER, vertex_shader_source));
    shaders->push_back(std::make_unique<shader>(GL_FRAGMENT_SHADER, fragment_shader_source));
    shader_program main_program(std::move(shaders));

    auto triangle_vertex_vector = std::make_unique<std::vector<GLfloat>, std::initializer_list<GLfloat>>({
            0.0f, 0.5f, 0.0f, 1.0f,
            0.5f, -0.5f, 0.0f, 1.0f,
            -0.5f, -0.5f, 0.0f, 1.0f});
    vertex_buffer triangle_vertices(std::move(triangle_vertex_vector));

    SDL_Event event;
    bool done = false;
    while (!done) {
        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        main_program.use();

        triangle_vertices.bind();
        GLuint position_attrib = main_program.get_attrib_location("position");
        glEnableVertexAttribArray(position_attrib);
        glVertexAttribPointer(position_attrib, 4, GL_FLOAT, GL_FALSE, 0, 0);

        glDrawArrays(GL_TRIANGLES, 0, 3);

        glDisableVertexAttribArray(position_attrib);
        main_program.clear();

        main_window.swap();

        SDL_Delay(10);

        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) {
                done = true;
            }
        }
    }
}

int main(int argv, char** argc) {
    try {
        engine e;
        loop();
    } catch (const std::exception& exc) {
        std::cerr << "error: " << exc.what() << std::endl;
        return 1;
    }

    return 0;
}
<commit_msg>removed superfluous calls to disable attrib and clear program<commit_after>#include <exception>
#include <iostream>
#include <memory>
#include <vector>

#include "engine/engine.hpp"
#include "engine/shader.hpp"
#include "engine/shader_program.hpp"
#include "engine/vertex_buffer.hpp"
#include "engine/window.hpp"

const char *vertex_shader_source = R"glsl(
#version 100

attribute vec4 position;
void main() {
    gl_Position = vec4(position);
}
)glsl";

const char *fragment_shader_source = R"glsl(
#version 100

precision mediump float;
void main() {
   gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
)glsl";

void loop() {
    window main_window;

    auto shaders = std::make_unique<std::vector<std::unique_ptr<shader>>>();
    shaders->push_back(std::make_unique<shader>(GL_VERTEX_SHADER, vertex_shader_source));
    shaders->push_back(std::make_unique<shader>(GL_FRAGMENT_SHADER, fragment_shader_source));
    shader_program main_program(std::move(shaders));

    auto triangle_vertex_vector = std::make_unique<std::vector<GLfloat>, std::initializer_list<GLfloat>>({
            0.0f, 0.5f, 0.0f, 1.0f,
            0.5f, -0.5f, 0.0f, 1.0f,
            -0.5f, -0.5f, 0.0f, 1.0f});
    vertex_buffer triangle_vertices(std::move(triangle_vertex_vector));

    SDL_Event event;
    bool done = false;
    while (!done) {
        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        main_program.use();

        triangle_vertices.bind();
        GLuint position_attrib = main_program.get_attrib_location("position");
        glEnableVertexAttribArray(position_attrib);
        glVertexAttribPointer(position_attrib, 4, GL_FLOAT, GL_FALSE, 0, 0);

        glDrawArrays(GL_TRIANGLES, 0, 3);

        main_window.swap();

        SDL_Delay(10);

        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) {
                done = true;
            }
        }
    }
}

int main(int argv, char** argc) {
    try {
        engine e;
        loop();
    } catch (const std::exception& exc) {
        std::cerr << "error: " << exc.what() << std::endl;
        return 1;
    }

    return 0;
}
<|endoftext|>


<commit_before>//
//  main.cpp
//  aticompress
//
//  Created by Gerard Meier on 5/17/13.
//  Copyright (c) 2013 Gerard Meier. All rights reserved.
//

#include <iostream>
#include <string>
#include <fstream>
#include <cstdio>
#include <unistd.h>

#include "libs/ati/TextureConverter.h"
#include "libs/libPNG/png.h"

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

struct KtxFormat {
    /// Constructor is only required when creating KTX images.
    KtxFormat() :
        endianness(0), glType(0), glTypeSize(0), glFormat(0), glInternalFormat(0),
        glBaseInternalFormat(0), pixelWidth(0), pixelHeight(0), pixelDepth(0),
        numberOfArrayElements(0), numberOfFaces(0), numberOfMipmapLevels(0), bytesOfKeyValueData(0) {

        // As per http://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
        identifier[0]  = 0xAB;
        identifier[1]  = 0x4B;
        identifier[2]  = 0x54;
        identifier[3]  = 0x58;
        identifier[4]  = 0x20;
        identifier[5]  = 0x31;
        identifier[6]  = 0x31;
        identifier[7]  = 0xBB;
        identifier[8]  = 0x0D;
        identifier[9]  = 0x0A;
        identifier[10] = 0x1A;
        identifier[11] = 0x0A;
    }

    unsigned char identifier[12];
    uint32_t endianness;
    uint32_t glType;
    uint32_t glTypeSize;
    uint32_t glFormat;
    uint32_t glInternalFormat;
    uint32_t glBaseInternalFormat;
    uint32_t pixelWidth;
    uint32_t pixelHeight;
    uint32_t pixelDepth;
    uint32_t numberOfArrayElements;
    uint32_t numberOfFaces;
    uint32_t numberOfMipmapLevels;
    uint32_t bytesOfKeyValueData;
};

void error(const std::string& wut) {
    cout << "Error: " << wut << endl;
    cout << "Usage: aticompress input.png output.ktc" << endl;
    exit(EXIT_FAILURE);
}

int main(int argc, const char * argv[]) {

    if(argc < 2) {
        error("No input file specified.");
    }

    if(argc < 3) {
        error("No output file specified.");
    }

    const string filenameIn(argv[1]);
    const string filenameOut(argv[2]);

    FILE* fp = fopen(filenameIn.c_str(), "r");

    if(fp == 0) {
        error("Input file not found: " + filenameIn);
    }

    png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
    png_infop info_ptr  = png_create_info_struct(png_ptr);

    if (setjmp(png_jmpbuf(png_ptr))) {
        error("Whatever just happend wasn't good.");
    }

    png_init_io(png_ptr, fp);

    unsigned int sig_read = 0;
    png_set_sig_bytes(png_ptr, sig_read);
    png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING | PNG_TRANSFORM_EXPAND, NULL);

    png_uint_32 width, height; int bit_depth, color_type, interlace_type;
    png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, NULL, NULL);

    if(color_type != PNG_COLOR_TYPE_RGB && color_type != PNG_COLOR_TYPE_RGBA) {
        error("Only RGB and RGBA are supported. None of that greyscale luminance stuff.");
    }

    unsigned long row_bytes = png_get_rowbytes(png_ptr, info_ptr);
    unsigned char* data = (unsigned char*) malloc(row_bytes * height);

    png_bytepp row_pointers = png_get_rows(png_ptr, info_ptr);

    for (unsigned int i = 0; i < height; i++) {
        memcpy(data+(row_bytes * i), row_pointers[i], row_bytes);
    }

    cout << "Bit depth: " << bit_depth << ", width: " << width
         << ", height: " << height << ", alpha: " << std::boolalpha << ((color_type==PNG_COLOR_TYPE_RGBA)?true:false) << ", ";

    TQonvertImage qualcommTextureInput;

    qualcommTextureInput.pFormatFlags = (TFormatFlags*) malloc(sizeof(TFormatFlags));
    memset(qualcommTextureInput.pFormatFlags, 0, sizeof(TFormatFlags));

    qualcommTextureInput.nWidth     = width;
    qualcommTextureInput.nHeight    = height;
    qualcommTextureInput.nFormat    = (color_type == PNG_COLOR_TYPE_RGB) ? Q_FORMAT_RGB_888 : Q_FORMAT_RGBA_8888;
    qualcommTextureInput.nDataSize  = width * height * bit_depth / 8;
    qualcommTextureInput.pFormatFlags->nMaskRed     = 0x0000FF;
    qualcommTextureInput.pFormatFlags->nMaskGreen   = 0x00FF00;
    qualcommTextureInput.pFormatFlags->nMaskBlue    = 0xFF0000;
    qualcommTextureInput.pFormatFlags->nFlipY       = 0;
    qualcommTextureInput.pData                      = (unsigned char*) data;

    TQonvertImage qualcommTextureOutput;
    qualcommTextureOutput.pFormatFlags = (TFormatFlags*)malloc(sizeof(TFormatFlags));
    memset(qualcommTextureOutput.pFormatFlags, 0, sizeof(TFormatFlags));

    qualcommTextureOutput.nWidth    = qualcommTextureInput.nWidth;
    qualcommTextureOutput.nHeight   = qualcommTextureInput.nHeight;
    qualcommTextureOutput.nFormat   = (color_type == PNG_COLOR_TYPE_RGB) ? Q_FORMAT_ATITC_RGB : Q_FORMAT_ATC_RGBA_EXPLICIT_ALPHA;
    qualcommTextureOutput.nDataSize = 0;
    qualcommTextureOutput.pData     = NULL;

    if(Qonvert(&qualcommTextureInput, &qualcommTextureOutput) != Q_SUCCESS) {
        error("The first Qonvert call failed.");
    }
    qualcommTextureOutput.pData = (unsigned char*) malloc(qualcommTextureOutput.nDataSize);

    if(Qonvert(&qualcommTextureInput, &qualcommTextureOutput) != Q_SUCCESS) {
        error("The first Qonvert call failed.");
    }

    // http://www.khronos.org/registry/gles/extensions/AMD/AMD_compressed_ATC_texture.txt

    KtxFormat ktx;
    ktx.pixelWidth           = width;
    ktx.pixelHeight          = height;
    ktx.pixelDepth           = bit_depth;
    ktx.numberOfMipmapLevels = 1;

    switch(qualcommTextureOutput.nFormat) {
        case Q_FORMAT_ATITC_RGB:
            ktx.glInternalFormat = 0x8C92; // ATC_RGB_AMD
            cout << "outfile: '" << filenameOut << "', format: Q_FORMAT_ATITC_RGB";
            break;
        case Q_FORMAT_ATC_RGBA_EXPLICIT_ALPHA:
            ktx.glInternalFormat = 0x8C93; // ATC_RGBA_EXPLICIT_ALPHA_AMD
            cout << "outfile: '" << filenameOut << "', format: Q_FORMAT_ATC_RGBA_EXPLICIT_ALPHA";
            break;
        case Q_FORMAT_ATC_RGBA_INTERPOLATED_ALPHA:
            ktx.glInternalFormat = 0x87EE; // ATC_RGBA_INTERPOLATED_ALPHA_AMD
            cout << "outfile: '" << filenameOut << "', format: Q_FORMAT_ATC_RGBA_INTERPOLATED_ALPHA";
            break;
        default:
            error("Internal error, no output format specified.");
            break;
    }

    // Remove the old file
    remove(filenameOut.c_str());

    FILE* out = fopen(filenameOut.c_str(), "w");

    // Write the header:
    fwrite((void*) &ktx, 1, sizeof(KtxFormat), out);

    // Write actual data:
    fwrite(qualcommTextureOutput.pData, 1, qualcommTextureOutput.nDataSize, out);

    cout << " - done (" << (sizeof(KtxFormat) + qualcommTextureOutput.nDataSize) << " bytes) !" << endl;
    return EXIT_SUCCESS;
}
<commit_msg>Added missing data size field<commit_after>//
//  main.cpp
//  aticompress
//
//  Created by Gerard Meier on 5/17/13.
//  Copyright (c) 2013 Gerard Meier. All rights reserved.
//

#include <iostream>
#include <string>
#include <fstream>
#include <cstdio>
#include <unistd.h>

#include "libs/ati/TextureConverter.h"
#include "libs/libPNG/png.h"

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

struct KtxFormat {
    /// Constructor is only required when creating KTX images.
    KtxFormat() :
        endianness(0), glType(0), glTypeSize(0), glFormat(0), glInternalFormat(0),
        glBaseInternalFormat(0), pixelWidth(0), pixelHeight(0), pixelDepth(0),
        numberOfArrayElements(0), numberOfFaces(0), numberOfMipmapLevels(0), bytesOfKeyValueData(0) {

        // As per http://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
        identifier[0]  = 0xAB;
        identifier[1]  = 0x4B;
        identifier[2]  = 0x54;
        identifier[3]  = 0x58;
        identifier[4]  = 0x20;
        identifier[5]  = 0x31;
        identifier[6]  = 0x31;
        identifier[7]  = 0xBB;
        identifier[8]  = 0x0D;
        identifier[9]  = 0x0A;
        identifier[10] = 0x1A;
        identifier[11] = 0x0A;
    }

    unsigned char identifier[12];
    uint32_t endianness;
    uint32_t glType;
    uint32_t glTypeSize;
    uint32_t glFormat;
    uint32_t glInternalFormat;
    uint32_t glBaseInternalFormat;
    uint32_t pixelWidth;
    uint32_t pixelHeight;
    uint32_t pixelDepth;
    uint32_t numberOfArrayElements;
    uint32_t numberOfFaces;
    uint32_t numberOfMipmapLevels;
    uint32_t bytesOfKeyValueData;
};

void error(const std::string& wut) {
    cout << "Error: " << wut << endl;
    cout << "Usage: aticompress input.png output.ktc" << endl;
    exit(EXIT_FAILURE);
}

int main(int argc, const char * argv[]) {

    if(argc < 2) {
        error("No input file specified.");
    }

    if(argc < 3) {
        error("No output file specified.");
    }

    const string filenameIn(argv[1]);
    const string filenameOut(argv[2]);

    FILE* fp = fopen(filenameIn.c_str(), "r");

    if(fp == 0) {
        error("Input file not found: " + filenameIn);
    }

    png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
    png_infop info_ptr  = png_create_info_struct(png_ptr);

    if (setjmp(png_jmpbuf(png_ptr))) {
        error("Whatever just happend wasn't good.");
    }

    png_init_io(png_ptr, fp);

    unsigned int sig_read = 0;
    png_set_sig_bytes(png_ptr, sig_read);
    png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING | PNG_TRANSFORM_EXPAND, NULL);

    png_uint_32 width, height; int bit_depth, color_type, interlace_type;
    png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, NULL, NULL);

    if(color_type != PNG_COLOR_TYPE_RGB && color_type != PNG_COLOR_TYPE_RGBA) {
        error("Only RGB and RGBA are supported. None of that greyscale luminance stuff.");
    }

    unsigned long row_bytes = png_get_rowbytes(png_ptr, info_ptr);
    unsigned char* data = (unsigned char*) malloc(row_bytes * height);

    png_bytepp row_pointers = png_get_rows(png_ptr, info_ptr);

    for (unsigned int i = 0; i < height; i++) {
        memcpy(data+(row_bytes * i), row_pointers[i], row_bytes);
    }

    cout << "Bit depth: " << bit_depth << ", width: " << width
         << ", height: " << height << ", alpha: " << std::boolalpha << ((color_type==PNG_COLOR_TYPE_RGBA)?true:false) << ", ";

    TQonvertImage qualcommTextureInput;

    qualcommTextureInput.pFormatFlags = (TFormatFlags*) malloc(sizeof(TFormatFlags));
    memset(qualcommTextureInput.pFormatFlags, 0, sizeof(TFormatFlags));

    qualcommTextureInput.nWidth     = width;
    qualcommTextureInput.nHeight    = height;
    qualcommTextureInput.nFormat    = (color_type == PNG_COLOR_TYPE_RGB) ? Q_FORMAT_RGB_888 : Q_FORMAT_RGBA_8888;
    qualcommTextureInput.nDataSize  = width * height * bit_depth / 8;
    qualcommTextureInput.pFormatFlags->nMaskRed     = 0x0000FF;
    qualcommTextureInput.pFormatFlags->nMaskGreen   = 0x00FF00;
    qualcommTextureInput.pFormatFlags->nMaskBlue    = 0xFF0000;
    qualcommTextureInput.pFormatFlags->nFlipY       = 0;
    qualcommTextureInput.pData                      = (unsigned char*) data;

    TQonvertImage qualcommTextureOutput;
    qualcommTextureOutput.pFormatFlags = (TFormatFlags*)malloc(sizeof(TFormatFlags));
    memset(qualcommTextureOutput.pFormatFlags, 0, sizeof(TFormatFlags));

    qualcommTextureOutput.nWidth    = qualcommTextureInput.nWidth;
    qualcommTextureOutput.nHeight   = qualcommTextureInput.nHeight;
    qualcommTextureOutput.nFormat   = (color_type == PNG_COLOR_TYPE_RGB) ? Q_FORMAT_ATITC_RGB : Q_FORMAT_ATC_RGBA_EXPLICIT_ALPHA;
    qualcommTextureOutput.nDataSize = 0;
    qualcommTextureOutput.pData     = NULL;

    if(Qonvert(&qualcommTextureInput, &qualcommTextureOutput) != Q_SUCCESS) {
        error("The first Qonvert call failed.");
    }
    qualcommTextureOutput.pData = (unsigned char*) malloc(qualcommTextureOutput.nDataSize);

    if(Qonvert(&qualcommTextureInput, &qualcommTextureOutput) != Q_SUCCESS) {
        error("The first Qonvert call failed.");
    }

    // http://www.khronos.org/registry/gles/extensions/AMD/AMD_compressed_ATC_texture.txt

    KtxFormat ktx;
    ktx.pixelWidth           = width;
    ktx.pixelHeight          = height;
    ktx.pixelDepth           = bit_depth;
    ktx.numberOfMipmapLevels = 1;

    switch(qualcommTextureOutput.nFormat) {
        case Q_FORMAT_ATITC_RGB:
            ktx.glInternalFormat = 0x8C92; // ATC_RGB_AMD
            cout << "outfile: '" << filenameOut << "', format: Q_FORMAT_ATITC_RGB";
            break;
        case Q_FORMAT_ATC_RGBA_EXPLICIT_ALPHA:
            ktx.glInternalFormat = 0x8C93; // ATC_RGBA_EXPLICIT_ALPHA_AMD
            cout << "outfile: '" << filenameOut << "', format: Q_FORMAT_ATC_RGBA_EXPLICIT_ALPHA";
            break;
        case Q_FORMAT_ATC_RGBA_INTERPOLATED_ALPHA:
            ktx.glInternalFormat = 0x87EE; // ATC_RGBA_INTERPOLATED_ALPHA_AMD
            cout << "outfile: '" << filenameOut << "', format: Q_FORMAT_ATC_RGBA_INTERPOLATED_ALPHA";
            break;
        default:
            error("Internal error, no output format specified.");
            break;
    }

    // Remove the old file
    remove(filenameOut.c_str());

    FILE* out = fopen(filenameOut.c_str(), "w");

    // Write the header:
    fwrite((void*) &ktx, 1, sizeof(KtxFormat), out);

    // Write the data size:
    fwrite((void*) &(qualcommTextureOutput.nDataSize), 1, sizeof(unsigned int), out);

    // Write actual data:
    fwrite(qualcommTextureOutput.pData, 1, qualcommTextureOutput.nDataSize, out);

    cout << " - done (" << (sizeof(KtxFormat) + sizeof(unsigned int) + qualcommTextureOutput.nDataSize) << " bytes) !" << endl;
    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <cstdint>
#include <algorithm>
#include <memory>
#include <thread>

#include <stdio.h>
#include <chrono>

#include "dcpu.hpp"
#include "disassembler.hpp"
#include "fake_lem1802.hpp"
#include "lem1802.hpp"

using namespace cpu;

const long TOTALCPUS    = 215*16;
const long PERTHREAD    = 16;  // At 16 looks that is the ideal for the FX-4100
#define THREADS           (TOTALCPUS/PERTHREAD)
const long CYCLES       = 1000*1000;

const int BATCH         = 10;

std::vector<std::vector<std::shared_ptr<DCPU>>> threads;
uint16_t* data;
size_t size = 0;

void benchmark();
void step();
void one_bench();

void cpu_in_thread(int n);

int main (int argc, char **argv)
{

    char* filename;
    std::ifstream binfile;

   /* std::cout << "cpu " << sizeof(DCPU) << " IHardware " << sizeof(IHardware);
    std::cout << " fake_LEM1802 " << sizeof(Fake_Lem1802) << std::endl;*/

    if (argc <= 1) {
        std::cerr << "Missing input file\n";
        return 0;
    }

    filename = argv[1];
    std::cout <<  "Input BIN File : " << filename << "\n";

    binfile.open (filename, std::ios::in | std::ios::binary );

    if (!binfile) {
        std::cerr << "ERROR: I can open file\n";
        exit (1);
    }

    // get length of file:
    binfile.seekg (0, binfile.end);
    size = binfile.tellg();
    binfile.seekg (0, binfile.beg);

    data = new uint16_t[size / 2 + 1]();
    std::fill_n (data, size / 2, 0); // Clean it

    int i = 0;

    while (! binfile.eof() ) {
        uint16_t word = 0;
        binfile.read ( (char*) &word, 2);
        unsigned char tmp = ( (word & 0xFF00) >> 8) & 0x00FF;
        word = ( (word & 0x00FF) << 8) | tmp;
        data[i] = word;
        i++;
    }

    binfile.close();

    std::cout << "Readed " << size << " bytes - " << size / 2 << " words\n";
    size /= 2;

badchar:
    std::cout << "Select what to do :" << std::endl;
    std::cout << "\tb -> benchmark  s -> step execution o-> benchmark one VM";
    std::cout << std::endl << std::endl;
    char choose;
    std::cin >> choose;

    if (choose == 'b' || choose == 'B') {
        benchmark();
    } else if ( choose == 's' || choose == 'S') {
        step();
    } else if ( choose == 'o' || choose == 'O') {
        one_bench();
    } else {
        goto badchar; /// HATE ME!!!!
    }

    delete[] data;

    return 0;
}

void benchmark()
{
    // Load program to all CPUs
    for (int u=0; u< THREADS; u++) {
        std::vector<std::shared_ptr<DCPU>> cpus;
        cpus.reserve (PERTHREAD);
        for (int i = 0; i< PERTHREAD; i++) {
            auto cpu = std::make_shared<DCPU>();
            auto screen = std::make_shared<Fake_Lem1802>();
            screen->setEnable(false); // We not desire to write to stdout
            cpu->attachHardware (screen);
            cpu->reset();
            cpu->loadProgram (data, size);

            cpus.push_back(cpu);
        }

        threads.push_back(cpus);

    }

    std::thread tds[THREADS];

    printf("Threads %ld\t CPU PerThread %ld\t", THREADS, PERTHREAD);
    printf("N cpus %ld\n", PERTHREAD * THREADS);
    printf("Cycles %ld\n", CYCLES);

    auto start = std::chrono::high_resolution_clock::now();

    for (int i=0; i< THREADS; i++) {
        tds[i] = std::thread(cpu_in_thread, i);
    }

    for (int i=0; i< THREADS; i++) {
        tds[i].join();
    }

	auto end = std::chrono::high_resolution_clock::now();
    auto dur = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
	std::cout << "Measured time: " << dur.count() << "ms" << std::endl;

}

void step() {
    using namespace std;
    auto cpu = make_shared<DCPU>();
    auto screen = make_shared<Lem1802>();
    cpu->attachHardware (screen);
    cpu->reset();
    cpu->loadProgram (data, size);

    char c = getchar();
    while (1) {
        c = getchar();
        if (c == 'f' || c == 'q' || c == '\n' )
            break;
    }

    while (c != 'q') {

        cout << cpu->dumpRegisters() << endl;
        cout << "T cycles " << dec << cpu->getTotCycles() << endl;
        cout << "> " << cpu->dumpRam() << " - ";
        string s = disassembly(cpu->getMem() + cpu->GetPC(), 3);
        cout << s << endl;

        if (cpu->GetSP() != 0x0000)
            cout << "STACK : "<< cpu->dumpRam(cpu->GetSP(), 0xFFFF) << endl;

        if (c == 'f') {
            for (int i = 0; i < 100; i++)
                cpu->tick();
        } else {
            if (cpu->tick())
                cout << "Execute! ";
        }
        cout << endl;

        while (1) {
            c = getchar();
            if (c == 'f' || c == 'q' || c == '\n' )
                break;
        }

    }

}

void one_bench() {
    using namespace std;
    using namespace std::chrono;

    const int times = 1;

    high_resolution_clock::time_point  starts[times];
    high_resolution_clock::time_point  creates[times];
    high_resolution_clock::time_point  loadstarts[times];
    high_resolution_clock::time_point  loads[times];
    high_resolution_clock::time_point  finishs[times];

    for (int x=0; x < times; x++) {
        using namespace std::chrono;
        starts[x] = high_resolution_clock::now();
        auto cpu = make_shared<DCPU>();

        creates[x] = high_resolution_clock::now();

        auto screen = make_shared<Lem1802>();
        //screen->setEnable(false); // We not desire to write to stdout
        cpu->attachHardware (screen);

        loadstarts[x] = high_resolution_clock::now();

        cpu->reset();
        cpu->loadProgram (data, size);

        loads[x] = high_resolution_clock::now();

        for (int i=0; i < 10000; i++) {
            cpu->tick();
        }
        finishs[x] = high_resolution_clock::now();
        char c;
		cin >> c;
    }

    double d_create, d_load, d_execute;
    d_create = d_load = d_execute = 0;

    for (int x=0; x < times; x++) {

        auto tmp = duration_cast<chrono::microseconds>
            (creates[x] - starts[x]);
        d_create += tmp.count();

        tmp = duration_cast<chrono::microseconds>
            (loads[x] - loadstarts[x]);
        d_load += tmp.count();

        tmp = duration_cast<chrono::microseconds>
            (finishs[x] - loads[x]);

        d_execute += tmp.count();

    }
    d_create /= times;
    d_load /= times;
    d_execute /= times;

    cout << "Measured time: " << endl;
    cout << "\tCreating time "<< d_create << "us" << endl;
    cout << "\tLoad time "<< d_load << "us" << endl;
    cout << "\tExecute 10k cycles time "<< d_execute << "us" << endl;

}

// Runs PERTHREAD cpus, doing CYCLES cycles
void cpu_in_thread(int n) {
    auto cpus = threads[n];
    for (long i=0; i < CYCLES; i+= BATCH) {
        for (auto c = cpus.begin(); c != cpus.end(); c++) {
            for ( int j=0; j < BATCH; j++)
                (*c)->tick();
        }
    }
}

<commit_msg>Added a option to run 100K cycles with working LEM1802<commit_after>#include <iostream>
#include <fstream>
#include <cstdint>
#include <algorithm>
#include <memory>
#include <thread>

#include <stdio.h>
#include <chrono>

#include "dcpu.hpp"
#include "disassembler.hpp"
#include "fake_lem1802.hpp"
#include "lem1802.hpp"

using namespace cpu;

const long TOTALCPUS    = 215*16;
const long PERTHREAD    = 16;  // At 16 looks that is the ideal for the FX-4100
#define THREADS           (TOTALCPUS/PERTHREAD)
const long CYCLES       = 1000*1000;

const int BATCH         = 10;

std::vector<std::vector<std::shared_ptr<DCPU>>> threads;
uint16_t* data;
size_t size = 0;

void benchmark();
void step();
void one_bench();
void run100k();

void cpu_in_thread(int n);

int main (int argc, char **argv)
{

    char* filename;
    std::ifstream binfile;

   /* std::cout << "cpu " << sizeof(DCPU) << " IHardware " << sizeof(IHardware);
    std::cout << " fake_LEM1802 " << sizeof(Fake_Lem1802) << std::endl;*/

    if (argc <= 1) {
        std::cerr << "Missing input file\n";
        return 0;
    }

    filename = argv[1];
    std::cout <<  "Input BIN File : " << filename << "\n";

    binfile.open (filename, std::ios::in | std::ios::binary );

    if (!binfile) {
        std::cerr << "ERROR: I can open file\n";
        exit (1);
    }

    // get length of file:
    binfile.seekg (0, binfile.end);
    size = binfile.tellg();
    binfile.seekg (0, binfile.beg);

    data = new uint16_t[size / 2 + 1]();
    std::fill_n (data, size / 2, 0); // Clean it

    int i = 0;

    while (! binfile.eof() ) {
        uint16_t word = 0;
        binfile.read ( (char*) &word, 2);
        unsigned char tmp = ( (word & 0xFF00) >> 8) & 0x00FF;
        word = ( (word & 0x00FF) << 8) | tmp;
        data[i] = word;
        i++;
    }

    binfile.close();

    std::cout << "Readed " << size << " bytes - " << size / 2 << " words\n";
    size /= 2;

badchar:
    std::cout << "Select what to do :" << std::endl;
    std::cout << "\tb -> benchmark  s -> step execution o-> benchmark one VM r-> run 100k cycles";
    std::cout << std::endl << std::endl;
    char choose;
    std::cin >> choose;

    if (choose == 'b' || choose == 'B') {
        benchmark();
    } else if ( choose == 's' || choose == 'S') {
        step();
    } else if ( choose == 'o' || choose == 'O') {
        one_bench();
    } else if ( choose == 'r' || choose == 'R') {
        run100k();
    } else {
        goto badchar; /// HATE ME!!!!
    }

    delete[] data;

    return 0;
}

void benchmark()
{
    // Load program to all CPUs
    for (int u=0; u< THREADS; u++) {
        std::vector<std::shared_ptr<DCPU>> cpus;
        cpus.reserve (PERTHREAD);
        for (int i = 0; i< PERTHREAD; i++) {
            auto cpu = std::make_shared<DCPU>();
            auto screen = std::make_shared<Fake_Lem1802>();
            screen->setEnable(false); // We not desire to write to stdout
            cpu->attachHardware (screen);
            cpu->reset();
            cpu->loadProgram (data, size);

            cpus.push_back(cpu);
        }

        threads.push_back(cpus);

    }

    std::thread tds[THREADS];

    printf("Threads %ld\t CPU PerThread %ld\t", THREADS, PERTHREAD);
    printf("N cpus %ld\n", PERTHREAD * THREADS);
    printf("Cycles %ld\n", CYCLES);

    auto start = std::chrono::high_resolution_clock::now();

    for (int i=0; i< THREADS; i++) {
        tds[i] = std::thread(cpu_in_thread, i);
    }

    for (int i=0; i< THREADS; i++) {
        tds[i].join();
    }

	auto end = std::chrono::high_resolution_clock::now();
    auto dur = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
	std::cout << "Measured time: " << dur.count() << "ms" << std::endl;

}

void step() {
    using namespace std;
    auto cpu = make_shared<DCPU>();
    auto screen = make_shared<Lem1802>();
    cpu->attachHardware (screen);
    cpu->reset();
    cpu->loadProgram (data, size);

    char c = getchar();
    while (1) {
        c = getchar();
        if (c == 'f' || c == 'q' || c == '\n' )
            break;
    }

    while (c != 'q') {

        cout << cpu->dumpRegisters() << endl;
        cout << "T cycles " << dec << cpu->getTotCycles() << endl;
        cout << "> " << cpu->dumpRam() << " - ";
        string s = disassembly(cpu->getMem() + cpu->GetPC(), 3);
        cout << s << endl;

        if (cpu->GetSP() != 0x0000)
            cout << "STACK : "<< cpu->dumpRam(cpu->GetSP(), 0xFFFF) << endl;

        if (c == 'f') {
            for (int i = 0; i < 100; i++)
                cpu->tick();
        } else {
            if (cpu->tick())
                cout << "Execute! ";
        }
        cout << endl;

        while (1) {
            c = getchar();
            if (c == 'f' || c == 'q' || c == '\n' )
                break;
        }

    }

}

void one_bench() {
    using namespace std;
    using namespace std::chrono;

    const int times = 200;

    high_resolution_clock::time_point  starts[times];
    high_resolution_clock::time_point  creates[times];
    high_resolution_clock::time_point  loadstarts[times];
    high_resolution_clock::time_point  loads[times];
    high_resolution_clock::time_point  finishs[times];

    for (int x=0; x < times; x++) {
        using namespace std::chrono;
        starts[x] = high_resolution_clock::now();
        auto cpu = make_shared<DCPU>();

        creates[x] = high_resolution_clock::now();

        auto screen = make_shared<Fake_Lem1802>();
        screen->setEnable(false); // We not desire to write to stdout
        cpu->attachHardware (screen);

        loadstarts[x] = high_resolution_clock::now();

        cpu->reset();
        cpu->loadProgram (data, size);

        loads[x] = high_resolution_clock::now();

        for (int i=0; i < 10000; i++) {
            cpu->tick();
        }
        finishs[x] = high_resolution_clock::now();
    }

    double d_create, d_load, d_execute;
    d_create = d_load = d_execute = 0;

    for (int x=0; x < times; x++) {

        auto tmp = duration_cast<chrono::microseconds>
            (creates[x] - starts[x]);
        d_create += tmp.count();

        tmp = duration_cast<chrono::microseconds>
            (loads[x] - loadstarts[x]);
        d_load += tmp.count();

        tmp = duration_cast<chrono::microseconds>
            (finishs[x] - loads[x]);

        d_execute += tmp.count();

    }
    d_create /= times;
    d_load /= times;
    d_execute /= times;

    cout << "Measured time: " << endl;
    cout << "\tCreating time "<< d_create << "us" << endl;
    cout << "\tLoad time "<< d_load << "us" << endl;
    cout << "\tExecute 10k cycles time "<< d_execute << "us" << endl;

}

void run100k() {

    auto cpu = std::make_shared<DCPU>();
    auto screen = std::make_shared<Lem1802>();
    cpu->attachHardware (screen);

    cpu->reset();
    cpu->loadProgram (data, size);

    for (int i=0; i < 100000; i++) {
        cpu->tick();
    }

    std::cout << "Finished" << std::endl;
    char c;
    std::cin >> c;

}

// Runs PERTHREAD cpus, doing CYCLES cycles
void cpu_in_thread(int n) {
    auto cpus = threads[n];
    for (long i=0; i < CYCLES; i+= BATCH) {
        for (auto c = cpus.begin(); c != cpus.end(); c++) {
            for ( int j=0; j < BATCH; j++)
                (*c)->tick();
        }
    }
}

<|endoftext|>


<commit_before>
<commit_msg>added main<commit_after>#include <SFML/Graphics.hpp>

int main(){
	int rows = 20;
	int cols = 10;
	const int WIDTH = 40*rows + 4*40 + 10*40;
	const int HEIGHT = 40*cols + 3*40;

	sf::RenderWindow window(sf::Videomode(WIDTH,HEIGHT), "Tetris");
<|endoftext|>


<commit_before>#include <climits>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cassert>
#include <string>
#include <vector>
#include <zlib.h>

#include "kseq.h"

KSEQ_INIT(gzFile, gzread)

using namespace std;

void usage() {
	cout << "Program: distmat - compute distance matrix from a FASTA alignment file" << endl;
	cout << "Usage:   distmat <inp.aln>" << endl;
	return;
}

/*
 * Compute number of differences between two sequences (N's ignored).
 */
int dist(const string &s1, const string &s2) {
	assert (s1.size()==s2.size());
	int dist=0;
	for (int i=0;i<s1.size();i++){
		if (s1[i]!=s2[i] && s1[i]!='N' && s2[i] != 'N'){
			dist++;
		}
	}
	return dist;
}

/*
 * Compute divergence between two sequences (N's ommited from stats)
 */
float diver(const string &s1, const string &s2) {
	assert (s1.size()==s2.size());
	int poss=0;
	int diff=0;
	for (int i=0;i<s1.size();i++){
		if (s1[i]=='N' || s2[j]=='N') {
			continue;
		}

		poss++;

		if (s1[i]!=s2[i]){
			diff++;
		}
	}
	return 1.0*diff/poss;
}

int main (int argc, const char **argv) {
	if (argc!=2){
		usage();
		return EXIT_FAILURE;
	}

	vector<string> names, seqs;

	gzFile fp;
	kseq_t *seq;
	int l;
	if (argc == 1) {
		fprintf(stderr, "Usage: %s <in.seq>\n", argv[0]);
		return 1;
	}
	fp = gzopen(argv[1], "r");
	seq = kseq_init(fp);

	int count=0;
	while ((l = kseq_read(seq)) >= 0) {
		names.push_back(seq->name.s);
		string s(seq->seq.s);
		for (auto & c: s) {
			c = toupper(c);
		}
		seqs.push_back(s);
		count++;
	}
	kseq_destroy(seq);
	gzclose(fp);

	int d[count][count];

	for (int i=0;i<count;i++){
		for (int j=0;j<=i;j++){
			d[i][j]=d[j][i]=dist(seqs[i],seqs[j]);
		}
	}

	cout << "#taxid";
	for (int j=0;j<count;j++){
		cout << "\t" << names[j];
	}
	cout << endl;

	for (int i=0;i<count;i++){
		cout << names[i];
		for (int j=0;j<count;j++){
			cout << "\t" << d[i][j];
		}
		cout << endl;
	}

	return 0;
}
<commit_msg>Compute multiple matrices<commit_after>#include <climits>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cassert>
#include <string>
#include <vector>
#include <cmath>
#include <zlib.h>

#include "kseq.h"

KSEQ_INIT(gzFile, gzread)

using namespace std;

void usage() {
	cout << "Program: distmat - compute distance matrix from a FASTA alignment file" << endl;
	cout << "Usage:   distmat <inp.aln>" << endl;
	return;
}

/*
 * Compute number of differences between two sequences (N's ignored) and the number of non-N positions.
 */
void compare_seqs(const string &s1, const string &s2, int &non_ns, int &non_ns_diff) {
	assert (s1.size()==s2.size());

	non_ns=0;
	non_ns_diff=0;

	for (int i=0;i<s1.size();i++){
		if (s1[i]!='N' && s2[i]!='N') {
			non_ns++;

			if (s1[i]!=s2[i]) {
				non_ns_diff++;
			}
		}
	}
}

template <typename T, typename U>
void dist_mat(const T &seqs, U &non_ns, U &non_ns_diff){
	for (int i=0;i<seqs.size();i++){
		for (int j=0;j<=i;j++){
			compare_seqs(seqs[i], seqs[j], non_ns[i][j], non_ns_diff[i][j]);
			non_ns[j][i]=non_ns[i][j];
			non_ns_diff[j][i]=non_ns_diff[i][j];
		}
	}
}

int main (int argc, const char **argv) {
	if (argc!=2){
		usage();
		return EXIT_FAILURE;
	}

	vector<string> names, seqs;

	gzFile fp;
	kseq_t *seq;
	int l;
	if (argc == 1) {
		fprintf(stderr, "Usage: %s <in.seq>\n", argv[0]);
		return 1;
	}
	fp = gzopen(argv[1], "r");
	seq = kseq_init(fp);

	int count=0;
	while ((l = kseq_read(seq)) >= 0) {
		names.push_back(seq->name.s);
		string s(seq->seq.s);
		for (auto & c: s) {
			c = toupper(c);
		}
		seqs.push_back(s);
		count++;
	}
	kseq_destroy(seq);
	gzclose(fp);

	int len=seqs[0].size();

	cerr << "Constructing empty matrices" << std::endl;

	vector<vector<int>> non_ns(count, vector<int>(count, 0));
	vector<vector<int>> non_ns_diff(count, vector<int>(count, 0));

	cerr << "Computing distance matrices" << std::endl;

	dist_mat(seqs, non_ns, non_ns_diff);

	/*
	 * print the output
	 */

	cout << "#taxid";
	for (int j=0;j<count;j++){
		cout << "\t" << names[j];
	}
	cout << endl;

	for (int i=0;i<count;i++){
		cout << names[i];
		for (int j=0;j<count;j++){
			cout << "\t" << (int) round( (1.0*non_ns_diff[i][j]/non_ns[i][j])*len );
		}
		cout << endl;
	}

	return 0;
}
<|endoftext|>


<commit_before>/*
an AI for solving 8 puzzle
written by Its Mahdi
visit me on
https://github.com/itsMahdi/
Be happy :)
*/
#include <iostream>
#include <vector>
using namespace std;

class state_table //this class will show every state and situations
{
public:
	int table[3][3];
	state_table(){
		int i,j,c=0;
		for (i = 0; i < 3; ++i)
			for (j = 0; j < 3 ; ++j)
			{
				table[i][j]=c;
				c++;
			}
	}

	void show_table()
	{
		int i,j;
		for (i = 0; i < 3 ; ++i)
		{
			cout<<endl;
			for (j = 0; j < 3 ; ++j)
				cout<</*"i , j = "<<i<<" , "<<j<<" = "<<*/table[i][j]<<"  ";
		}
	cout<<endl;
	}

};
class table_search //making a tree and seaching in that to reach the goal state
{
public:
	state_table *start_state;
	state_table *goal_state;
	std::vector<state_table *> table_list_vector;

	state_table* actions()
	{
		int void_row, void_col;
		int i=0,j=0;

		table_list_vector.push_back(start_state);

		state_table *temp = new state_table,*current_state;

		while(1)
		{
		current_state = table_list_vector.front();
		cout<<"size: "<<table_list_vector.size()<<"\n";
		cout<<"current_state\n";
		current_state->show_table();
		//cout<<"goal \n";
		//goal_state->show_table();
		char x;
		cin>>x;
			if(check_goal(current_state) == true)
			{
				cout<<"founded\n\n\n";
				return goal_state;
			}

		for (i = 0; i < 3; ++i)
			for (j = 0; j < 3 ; ++j)
				if (current_state->table[i][j] == 0)
				{
					void_row = i;
					void_col = j;
					i=2;j=2;
				}
		static int temp_row=void_row,
		temp_col=void_col;

		if (void_col > 0)
		{
		temp = current_state;
		void_col = temp_col;
		void_row = temp_row;
		switch_state (temp->table[void_row][void_col],temp->table[void_row][void_col -1]);
			cout<<"***\n temp:1 \n";
		temp->show_table();
		table_list_vector.push_back(temp);

		}

		if (void_col < 2)
		{
		temp = current_state;
		void_col = temp_col;
		void_row = temp_row;
		switch_state (temp->table[void_row][void_col],temp->table[void_row][void_col +1]);
		table_list_vector.push_back(temp);
					cout<<"***\n temp:2 \n";
		temp->show_table();
		}

		if (void_row > 0)
		{
		temp = current_state;
		void_col = temp_col;
		void_row = temp_row;
		switch_state (temp->table[void_row][void_col],temp->table[void_row-1][void_col]);
		table_list_vector.push_back(temp);
					cout<<"***\n temp:3 \n";
		temp->show_table();
		}

		if (void_row < 2)
		{
		temp = current_state;
		void_col = temp_col;
		void_row = temp_row;
		switch_state (temp->table[void_row][void_col],temp->table[void_row+1][void_col]);
		table_list_vector.push_back(temp);
					cout<<"***\n temp:4 \n";
		temp->show_table();
		}

		table_list_vector.erase(table_list_vector.begin());
		}

	}

	void switch_state (int &a,int &b)
	{
		int temp;
		temp = a;
		a = b;
		b = temp;
	}

	table_search()
	{
		goal_state = new state_table;
		start_state = new state_table;
		int i,j,c=0;
		cout<< "enter start state:\n";
		for (i = 0; i < 3; ++i)
			for (j = 0; j < 3 ; ++j)
			{
				cout<<"table["<<i<<"]["<<j<<"] :";
				cin>>start_state->table[i][j];
				goal_state->table[i][j]=c;
				c++;
			}
	}

	bool check_goal (state_table *current_state)
	{
		int i,j,c=0;
		for (i = 0; i < 3 ; ++i)
			for (j = 0; j < 3 ; ++j)
			{
				if(current_state->table[i][j] != c) return false;
				c++;
			}

		return true;
	}
};

int main() {
	table_search puzzle_8;

	puzzle_8.actions();

	cout << "sashcaisclka";

return 0;
}<commit_msg>add copy constructor function for state table and code improvement<commit_after>/*
an AI for solving 8 puzzle
written by Its Mahdi
visit me on
https://github.com/itsMahdi/
Be happy :)
*/
#include <iostream>
#include <vector>
using namespace std;

class state_table //this class will show every state and situations
{
public:
	int table[3][3];
	state_table(){
		int i,j,c=0;
		for (i = 0; i < 3; ++i)
			for (j = 0; j < 3 ; ++j)
			{
				table[i][j]=c;
				c++;
			}
	}
///////////
	state_table(state_table *state)
	{  // tabeye sazandeye copy
		int i,j,c=0;

		for (i = 0; i < 3; ++i)
			for (j = 0; j < 3 ; ++j)
				table[i][j]=state->table[i][j];
	}
///////////
	void show_table()
	{
		int i,j;
		for (i = 0; i < 3 ; ++i)
		{
			cout<<endl;
			for (j = 0; j < 3 ; ++j)
				cout<</*"i , j = "<<i<<" , "<<j<<" = "<<*/table[i][j]<<"  ";
		}
	cout<<endl;
	}

};
class table_search //making a tree and seaching in that to reach the goal state
{
public:
	state_table *start_state;
	state_table *goal_state;
	std::vector<state_table *> table_list_vector;

	bool check_goal (state_table *current_state)
	{
		int i,j,c=0;
		for (i = 0; i < 3 ; ++i)
			for (j = 0; j < 3 ; ++j)
			{
				if(current_state->table[i][j] != c) return false;
				c++;
			}

		return true;
	}

	state_table* actions()
	{
		int void_row, void_col;
		int i=0,j=0;

		table_list_vector.push_back(start_state);

		state_table *temp,*current_state;

		while(1)
		{
		current_state = table_list_vector.front();
		cout<<"size: "<<table_list_vector.size()<<"\n";
		cout<<"current_state\n";
		current_state->show_table();
		//cout<<"goal \n";
		//goal_state->show_table();
		char x;
		cin>>x;
			if(check_goal(current_state) == true)
			{
				cout<<"founded\n\n\n";
				return goal_state;
			}

		for (i = 0; i < 3; ++i)
			for (j = 0; j < 3 ; ++j)
				if (current_state->table[i][j] == 0)
				{
					void_row = i;
					void_col = j;
					i=2;j=2;
				}
		static int temp_row=void_row,
		temp_col=void_col;

		if (void_col > 0)
		{
		temp =  new state_table(*current_state);
		void_col = temp_col;
		void_row = temp_row;
		switch_state (temp->table[void_row][void_col],temp->table[void_row][void_col -1]);
			cout<<"***\n temp:1 \n";
		temp->show_table();
		table_list_vector.push_back(temp);

		}

		if (void_col < 2)
		{
		temp = current_state;
		void_col = temp_col;
		void_row = temp_row;
		switch_state (temp->table[void_row][void_col],temp->table[void_row][void_col +1]);
		table_list_vector.push_back(temp);
					cout<<"***\n temp:2 \n";
		temp->show_table();
		}

		if (void_row > 0)
		{
		temp = current_state;
		void_col = temp_col;
		void_row = temp_row;
		switch_state (temp->table[void_row][void_col],temp->table[void_row-1][void_col]);
		table_list_vector.push_back(temp);
					cout<<"***\n temp:3 \n";
		temp->show_table();
		}

		if (void_row < 2)
		{
		temp = current_state;
		void_col = temp_col;
		void_row = temp_row;
		switch_state (temp->table[void_row][void_col],temp->table[void_row+1][void_col]);
		table_list_vector.push_back(temp);
					cout<<"***\n temp:4 \n";
		temp->show_table();
		}

		table_list_vector.erase(table_list_vector.begin());
		}

	}

	void switch_state (int &a,int &b)
	{
		int temp;
		temp = a;
		a = b;
		b = temp;
	}

	table_search()
	{
		goal_state = new state_table;
		start_state = new state_table;
		int i,j,c=0;
		cout<< "enter start state:\n";
		for (i = 0; i < 3; ++i)
			for (j = 0; j < 3 ; ++j)
			{
				cout<<"table["<<i<<"]["<<j<<"] :";
				cin>>start_state->table[i][j];
				goal_state->table[i][j]=c;
				c++;
			}
	}

};

int main() {
	table_search puzzle_8;

	puzzle_8.actions();

	cout << "sashcaisclka";

return 0;
}<|endoftext|>


<commit_before>cfcfcd70-4b02-11e5-9413-28cfe9171a43<commit_msg>more fixes<commit_after>cfdd1ba6-4b02-11e5-b095-28cfe9171a43<|endoftext|>


<commit_before>2ce9abcc-ad58-11e7-8671-ac87a332f658<commit_msg>This'll fix that<commit_after>2d57f597-ad58-11e7-8ac3-ac87a332f658<|endoftext|>