<commit_before>#include "j1App.h"
#include "j1Textures.h"
#include "j1Input.h"
#include "j1Render.h"
#include "j1Collision.h"
#include "j1Player.h"
#include "p2Log.h"
#include "j1Window.h"
#include "j1Map.h"
#include "j1Gui.h"
#include "j1Scene.h"
#include "j1Audio.h"
#include "j1entityManager.h"
#include "j1Transitions.h"
#include "j1PathFinding.h"
#include "Brofiler\Brofiler.h"

#include<stdio.h>

// Reference at https://www.youtube.com/watch?v=OEhmUuehGOA

j1Player::j1Player() : Entity("player")
{
	name.create("player");

	// Animations
	jump_cloud = LoadAnimation("animations/player.tmx", "jump_cloud");
	cloud_offset.x = -16;
	cloud_offset.y = 17;

	SSJ_aura = LoadAnimation("animations/player.tmx", "SSJ_aura");
	aura_offset.x = -7;
	aura_offset.y = -12;

	type = PLAYER;
}

j1Player::~j1Player()
{
	App->tex->UnLoad(graphics);
	graphics = nullptr;
	App->tex->UnLoad(graphics_god);
	graphics_god = nullptr;
}

// Load assets
bool j1Player::Start()
{
	LOG("Loading player");

	if (graphics == nullptr)
		graphics = App->tex->Load("textures/character/Character spritesheet.png");

	if (graphics_god == nullptr)
		graphics_god = App->tex->Load("textures/character/godmode_spritesheet.png");

	if (collider == nullptr)
		collider = App->collision->AddCollider({ 0, 0, 15, 29 }, COLLIDER_PLAYER, this);
	else
		collider->SetPos(0, 0);

	collider_offset.x = 3;
	collider_offset.y = 2;

	collidingFloor = nullptr;
	colliding_bottom = false;
	colliding_left = false;
	colliding_right = false;

	going_right = false;
	going_left = false;
	going_down = false;
	jumping = false;

	dead = false;
	sound_one_time = false;
	loading = false;
	won = false;

	old_savedCol = nullptr;

	v.x = 0;
	v.y = 0;

	if (lives <= 0)
	{
		score = 0;
		lives = 3;
		coins[0] = coins[1] = coins[2] = false;
	}

	animation = idle_right;

	virtualPosition.x = position.x;
	virtualPosition.y = position.y;

	if (step_fx == 0)
		step_fx = App->audio->LoadFx("audio/fx/step.wav");
	if (jump_fx == 0)
		jump_fx = App->audio->LoadFx("audio/fx/jump.wav");
	if (double_jump_fx == 0)
		double_jump_fx = App->audio->LoadFx("audio/fx/double_jump.wav");
	if (landing_fx == 0)
		landing_fx = App->audio->LoadFx("audio/fx/landing.wav");
	if (die_fx == 0)
		die_fx = App->audio->LoadFx("audio/fx/die.wav");
	if (SSJ_transformation == 0)
		SSJ_transformation = App->audio->LoadFx("audio/fx/SSJ_transformation.wav");
	if (SSJ_off == 0)
		SSJ_off = App->audio->LoadFx("audio/fx/SSJ_off.wav");
	if (killed_fx == 0)
		killed_fx = App->audio->LoadFx("audio/fx/killed_by_enemy.wav");

	return true;
}

// Update: draw background
bool j1Player::Update(float dt)
{
	BROFILER_CATEGORY("Player Update", Profiler::Color::Red);

	if (!dead)
	{
		if (App->input->GetKey(SDL_SCANCODE_F10) == KEY_DOWN)
		{
			if (App->entityManager->player_god_mode)
			{
				App->entityManager->player_god_mode = false;
				App->audio->PlayFx(SSJ_off, 0);
			}
			else
			{
				App->entityManager->player_god_mode = true;
				App->audio->PlayFx(SSJ_transformation, 0);
			}
		}

		if (App->input->GetKey(SDL_SCANCODE_A) == KEY_DOWN)
		{
			v.x = -speed;
			going_left = true;
			if (state != JUMPING && state != DEAD)
			{
				state = LEFT;
			}
		}
		else if (App->input->GetKey(SDL_SCANCODE_A) == KEY_UP)
		{
			going_left = false;
			if (state == LEFT)
			{
				v.x = 0;
				state = IDLE;
			}
		}
		if (App->input->GetKey(SDL_SCANCODE_D) == KEY_DOWN)
		{
			v.x = speed;
			going_right = true;
			if (state != JUMPING && state != DEAD)
			{
				state = RIGHT;
			}
		}
		else if (App->input->GetKey(SDL_SCANCODE_D) == KEY_UP)
		{
			going_right = false;
			if (state == RIGHT)
			{
				v.x = 0;
				state = IDLE;
			}
		}
		if (App->input->GetKey(SDL_SCANCODE_SPACE) == KEY_DOWN)
		{
			jumping = true;
			if (!double_jump)
			{
				if (state == JUMPING || state == FALLING)
				{
					double_jump = true;
					cloud_pos.x = position.x + cloud_offset.x;
					cloud_pos.y = position.y + cloud_offset.y;
					v.y = (jump_force * 2 / 3);
					if (state == FALLING)
					{
						state = JUMPING;
					}
					App->audio->PlayFx(double_jump_fx, 0);
				}
				else
				{
					v.y = jump_force;
					state = JUMPING;
					App->audio->PlayFx(jump_fx, 0);
				}
			}
		}
		else if (App->input->GetKey(SDL_SCANCODE_SPACE) == KEY_UP)
		{
			// If player release space in mid jump, the character won't reach max height
			if (!double_jump && v.y > (jump_force * 2 / 3) / 2)
			{
				v.y = (jump_force * 2 / 3) / 2;
			}
		}
	}
	if (v.x != 0 && colliding_bottom && SDL_GetTicks() > step_time)
	{
		App->audio->PlayFx(step_fx, 0);
		step_time = SDL_GetTicks() + (1 / right->speed) + 450;
	}

	return true;
}

bool j1Player::PostUpdate(float dt)
{
	if (!dead)
	{
		if (App->input->GetKey(SDL_SCANCODE_D) == KEY_REPEAT && !colliding_right && v.x == 0)
		{
			v.x = speed;
			state = RIGHT;
		}
		if (App->input->GetKey(SDL_SCANCODE_A) == KEY_REPEAT && !colliding_left && v.x == 0)
		{
			v.x = -speed;
			state = LEFT;
		}
	}
	if (App->paused)
	{
		v.x = 0;
		state = IDLE;
	}

	// Win condition
	if ((((collider->rect.x + collider->rect.w) > App->scene->current_lvl->data->end_rect.x) && (position.y + collider->rect.h) < (App->scene->current_lvl->data->end_rect.y + App->scene->current_lvl->data->end_rect.h)) && !won && !loading)
	{
		if (end_reached == 0)
		{
			won = true;
			loading = true;
			App->uiScene->pauseChronos();
			end_reached = SDL_GetTicks();
			if (App->scene->current_lvl == (App->scene->levels.end->prev))
			{
				App->audio->PlayFx(App->scene->win_fx, 0);
			}
			else
			{
				App->audio->PlayFx(App->scene->complete_level_fx, 0);
			}
		}
	}

	if (!App->paused)
	{
		if (won && loading && ((App->scene->current_lvl != App->scene->levels.end && SDL_GetTicks() > end_reached + 500)))
		{
			end_reached = 0;
			won = false;
			dead = false;
			App->transitions->sceneTransition(0);
		}

		// Lose condition
		//By enemyy
		if (dead && SDL_GetTicks() > killed_finished + 1500 && !won && loading)
		{
			loading = false;
			if (lives > 0)
			{
				App->transitions->sceneTransition(App->scene->current_lvl->data->lvl);
				App->scene->respawn_enemies = false;
			}
			else
			{
				App->setSaveFileLoadable(false);
				App->transitions->sceneTransition(1);
			}

			killed_finished = 0;
		}
		//By falling
		int win_scale = App->win->GetScale();
		if (position.y > App->win->screen_surface->h / win_scale + 50 && !won && !dead)
		{
			if (App->entityManager->player_god_mode)
			{
				App->LoadGame(true);
			}
			else
			{
				lives--;
				dead = true;

				if (lives > 0)
				{
					App->transitions->sceneTransition(App->scene->current_lvl->data->lvl);
					App->scene->respawn_enemies = false;
					App->audio->PlayFx(killed_fx, 0);
				}
				else
				{
					App->setSaveFileLoadable(false);
					App->transitions->sceneTransition(1);
					App->audio->PlayFx(die_fx, 0);
				}
			}
		}
	}
	else if (dead)
	{
		killed_finished += dt * 1000;
	}

	//When f10 is clicked he converts into super sayan (god mode)
	if (App->entityManager->player_god_mode)
	{
		App->render->Blit(graphics_god, position.x + aura_offset.x, position.y + aura_offset.y, &SSJ_aura->GetCurrentFrame(dt));
		App->render->Blit(graphics_god, position.x, position.y, &animation->GetCurrentFrame(dt));
		App->render->Blit(graphics_god, position.x + aura_offset.x, position.y + aura_offset.y, &SSJ_aura->GetCurrentFrame(dt));
	}
	else if (App->entityManager->player_god_mode == false)
	{
		App->render->Blit(graphics, position.x, position.y, &animation->GetCurrentFrame(dt));
	}

	if (double_jump)
	{
		App->render->Blit(graphics, cloud_pos.x, cloud_pos.y, &jump_cloud->GetCurrentFrame(dt));
	}

	return true;
}

void j1Player::OnCollision(Collider* c1, Collider* c2)
{
	if (c2->type == COLLIDER_FLOOR || c2->type == COLLIDER_JUMPABLE)
	{
		if (Collision_from_bottom(c1, c2))
		{
			double_jump = false;
			jump_cloud->Reset();
		}
	}

	//If player touches the charger he must die, if the player hits the bat from the top the bat must die
	if (!dead && c2->type == COLLIDER_ENEMY)
	{
		p2SString c2_name = c2->callback->name.GetString();
		if (c2_name == "bat" && Collision_from_bottom(c1, c2, 3) && v.y < 0)
		{
			score += 250;
			v.y = (jump_force * 2 / 3);
			c2->entity->dead = true;
		}
		else if (!App->entityManager->player_god_mode && (c2_name == "charger" || (c2_name == "bat" && !c2->entity->dead && !Collision_from_bottom(c1, c2, 3))))
		{
			v.x = 0;
			dead = true;
			loading = true;
			if (!sound_one_time && killed_finished == 0)
			{
				lives--;
				killed_finished = SDL_GetTicks();
				sound_one_time = true;
				if (lives > 0)
					App->audio->PlayFx(killed_fx, 0);
				else
					App->audio->PlayFx(die_fx, 0);
			}
		}
	}

	Entity_OnCollision(c1, c2);
}

bool j1Player::Load(pugi::xml_node& data)
{
	App->scene->respawn_enemies = false;
	App->scene->LoadLvl(data.attribute("level").as_int());
	lives = data.attribute("lives").as_uint();
	virtualPosition.x = data.attribute("position_x").as_int();
	virtualPosition.y = data.attribute("position_y").as_int();
	coins[0] = data.attribute("coin1").as_bool();
	coins[1] = data.attribute("coin2").as_bool();
	coins[2] = data.attribute("coin3").as_bool();
	App->render->virtualCamPos = -(virtualPosition.x * (int)App->win->GetScale() - 300);
	if (App->render->virtualCamPos > 0)
	{
		App->render->virtualCamPos = 0;
	}
	if (App->render->virtualCamPos < App->scene->max_camera_pos)
	{
		App->render->virtualCamPos = App->scene->max_camera_pos;
	}

	return true;
}

bool j1Player::Save(pugi::xml_node& data) const
{
	data.append_attribute("position_x") = position.x;

	data.append_attribute("position_y") = position.y - 8;

	data.append_attribute("level") = App->scene->current_lvl->data->lvl;

	data.append_attribute("lives") = lives;

	data.append_attribute("coin1") = coins[0];

	data.append_attribute("coin2") = coins[1];

	data.append_attribute("coin3") = coins[2];

	return true;
}<commit_msg>solved a bug with player load file<commit_after>#include "j1App.h"
#include "j1Textures.h"
#include "j1Input.h"
#include "j1Render.h"
#include "j1Collision.h"
#include "j1Player.h"
#include "p2Log.h"
#include "j1Window.h"
#include "j1Map.h"
#include "j1Gui.h"
#include "j1Scene.h"
#include "j1Audio.h"
#include "j1entityManager.h"
#include "j1Transitions.h"
#include "j1PathFinding.h"
#include "Brofiler\Brofiler.h"

#include<stdio.h>

// Reference at https://www.youtube.com/watch?v=OEhmUuehGOA

j1Player::j1Player() : Entity("player")
{
	name.create("player");

	// Animations
	jump_cloud = LoadAnimation("animations/player.tmx", "jump_cloud");
	cloud_offset.x = -16;
	cloud_offset.y = 17;

	SSJ_aura = LoadAnimation("animations/player.tmx", "SSJ_aura");
	aura_offset.x = -7;
	aura_offset.y = -12;

	type = PLAYER;
}

j1Player::~j1Player()
{
	App->tex->UnLoad(graphics);
	graphics = nullptr;
	App->tex->UnLoad(graphics_god);
	graphics_god = nullptr;
}

// Load assets
bool j1Player::Start()
{
	LOG("Loading player");

	if (graphics == nullptr)
		graphics = App->tex->Load("textures/character/Character spritesheet.png");

	if (graphics_god == nullptr)
		graphics_god = App->tex->Load("textures/character/godmode_spritesheet.png");

	if (collider == nullptr)
		collider = App->collision->AddCollider({ 0, 0, 15, 29 }, COLLIDER_PLAYER, this);
	else
		collider->SetPos(0, 0);

	collider_offset.x = 3;
	collider_offset.y = 2;

	collidingFloor = nullptr;
	colliding_bottom = false;
	colliding_left = false;
	colliding_right = false;

	going_right = false;
	going_left = false;
	going_down = false;
	jumping = false;

	dead = false;
	sound_one_time = false;
	loading = false;
	won = false;

	old_savedCol = nullptr;

	v.x = 0;
	v.y = 0;

	if (lives <= 0)
	{
		score = 0;
		lives = 3;
		coins[0] = coins[1] = coins[2] = false;
	}

	animation = idle_right;

	virtualPosition.x = position.x;
	virtualPosition.y = position.y;

	if (step_fx == 0)
		step_fx = App->audio->LoadFx("audio/fx/step.wav");
	if (jump_fx == 0)
		jump_fx = App->audio->LoadFx("audio/fx/jump.wav");
	if (double_jump_fx == 0)
		double_jump_fx = App->audio->LoadFx("audio/fx/double_jump.wav");
	if (landing_fx == 0)
		landing_fx = App->audio->LoadFx("audio/fx/landing.wav");
	if (die_fx == 0)
		die_fx = App->audio->LoadFx("audio/fx/die.wav");
	if (SSJ_transformation == 0)
		SSJ_transformation = App->audio->LoadFx("audio/fx/SSJ_transformation.wav");
	if (SSJ_off == 0)
		SSJ_off = App->audio->LoadFx("audio/fx/SSJ_off.wav");
	if (killed_fx == 0)
		killed_fx = App->audio->LoadFx("audio/fx/killed_by_enemy.wav");

	return true;
}

// Update: draw background
bool j1Player::Update(float dt)
{
	BROFILER_CATEGORY("Player Update", Profiler::Color::Red);

	if (!dead)
	{
		if (App->input->GetKey(SDL_SCANCODE_F10) == KEY_DOWN)
		{
			if (App->entityManager->player_god_mode)
			{
				App->entityManager->player_god_mode = false;
				App->audio->PlayFx(SSJ_off, 0);
			}
			else
			{
				App->entityManager->player_god_mode = true;
				App->audio->PlayFx(SSJ_transformation, 0);
			}
		}

		if (App->input->GetKey(SDL_SCANCODE_A) == KEY_DOWN)
		{
			v.x = -speed;
			going_left = true;
			if (state != JUMPING && state != DEAD)
			{
				state = LEFT;
			}
		}
		else if (App->input->GetKey(SDL_SCANCODE_A) == KEY_UP)
		{
			going_left = false;
			if (state == LEFT)
			{
				v.x = 0;
				state = IDLE;
			}
		}
		if (App->input->GetKey(SDL_SCANCODE_D) == KEY_DOWN)
		{
			v.x = speed;
			going_right = true;
			if (state != JUMPING && state != DEAD)
			{
				state = RIGHT;
			}
		}
		else if (App->input->GetKey(SDL_SCANCODE_D) == KEY_UP)
		{
			going_right = false;
			if (state == RIGHT)
			{
				v.x = 0;
				state = IDLE;
			}
		}
		if (App->input->GetKey(SDL_SCANCODE_SPACE) == KEY_DOWN)
		{
			jumping = true;
			if (!double_jump)
			{
				if (state == JUMPING || state == FALLING)
				{
					double_jump = true;
					cloud_pos.x = position.x + cloud_offset.x;
					cloud_pos.y = position.y + cloud_offset.y;
					v.y = (jump_force * 2 / 3);
					if (state == FALLING)
					{
						state = JUMPING;
					}
					App->audio->PlayFx(double_jump_fx, 0);
				}
				else
				{
					v.y = jump_force;
					state = JUMPING;
					App->audio->PlayFx(jump_fx, 0);
				}
			}
		}
		else if (App->input->GetKey(SDL_SCANCODE_SPACE) == KEY_UP)
		{
			// If player release space in mid jump, the character won't reach max height
			if (!double_jump && v.y > (jump_force * 2 / 3) / 2)
			{
				v.y = (jump_force * 2 / 3) / 2;
			}
		}
	}
	if (v.x != 0 && colliding_bottom && SDL_GetTicks() > step_time)
	{
		App->audio->PlayFx(step_fx, 0);
		step_time = SDL_GetTicks() + (1 / right->speed) + 450;
	}

	return true;
}

bool j1Player::PostUpdate(float dt)
{
	if (!dead)
	{
		if (App->input->GetKey(SDL_SCANCODE_D) == KEY_REPEAT && !colliding_right && v.x == 0)
		{
			v.x = speed;
			state = RIGHT;
		}
		if (App->input->GetKey(SDL_SCANCODE_A) == KEY_REPEAT && !colliding_left && v.x == 0)
		{
			v.x = -speed;
			state = LEFT;
		}
	}
	if (App->paused)
	{
		v.x = 0;
		state = IDLE;
	}

	// Win condition
	if ((((collider->rect.x + collider->rect.w) > App->scene->current_lvl->data->end_rect.x) && (position.y + collider->rect.h) < (App->scene->current_lvl->data->end_rect.y + App->scene->current_lvl->data->end_rect.h)) && !won && !loading)
	{
		if (end_reached == 0)
		{
			won = true;
			loading = true;
			App->uiScene->pauseChronos();
			end_reached = SDL_GetTicks();
			if (App->scene->current_lvl == (App->scene->levels.end->prev))
			{
				App->audio->PlayFx(App->scene->win_fx, 0);
			}
			else
			{
				App->audio->PlayFx(App->scene->complete_level_fx, 0);
			}
		}
	}

	if (!App->paused)
	{
		if (won && loading && ((App->scene->current_lvl != App->scene->levels.end && SDL_GetTicks() > end_reached + 500)))
		{
			end_reached = 0;
			won = false;
			dead = false;
			App->transitions->sceneTransition(0);
		}

		// Lose condition
		//By enemyy
		if (dead && SDL_GetTicks() > killed_finished + 1500 && !won && loading)
		{
			loading = false;
			if (lives > 0)
			{
				App->transitions->sceneTransition(App->scene->current_lvl->data->lvl);
				App->scene->respawn_enemies = false;
			}
			else
			{
				App->setSaveFileLoadable(false);
				App->transitions->sceneTransition(1);
			}

			killed_finished = 0;
		}
		//By falling
		int win_scale = App->win->GetScale();
		if (position.y > App->win->screen_surface->h / win_scale + 50 && !won && !dead)
		{
			if (App->entityManager->player_god_mode)
			{
				App->LoadGame(true);
			}
			else
			{
				lives--;
				dead = true;

				if (lives > 0)
				{
					App->transitions->sceneTransition(App->scene->current_lvl->data->lvl);
					App->scene->respawn_enemies = false;
					App->audio->PlayFx(killed_fx, 0);
				}
				else
				{
					App->setSaveFileLoadable(false);
					App->transitions->sceneTransition(1);
					App->audio->PlayFx(die_fx, 0);
				}
			}
		}
	}
	else if (dead)
	{
		killed_finished += dt * 1000;
	}

	//When f10 is clicked he converts into super sayan (god mode)
	if (App->entityManager->player_god_mode)
	{
		App->render->Blit(graphics_god, position.x + aura_offset.x, position.y + aura_offset.y, &SSJ_aura->GetCurrentFrame(dt));
		App->render->Blit(graphics_god, position.x, position.y, &animation->GetCurrentFrame(dt));
		App->render->Blit(graphics_god, position.x + aura_offset.x, position.y + aura_offset.y, &SSJ_aura->GetCurrentFrame(dt));
	}
	else if (App->entityManager->player_god_mode == false)
	{
		App->render->Blit(graphics, position.x, position.y, &animation->GetCurrentFrame(dt));
	}

	if (double_jump)
	{
		App->render->Blit(graphics, cloud_pos.x, cloud_pos.y, &jump_cloud->GetCurrentFrame(dt));
	}

	return true;
}

void j1Player::OnCollision(Collider* c1, Collider* c2)
{
	if (c2->type == COLLIDER_FLOOR || c2->type == COLLIDER_JUMPABLE)
	{
		if (Collision_from_bottom(c1, c2))
		{
			double_jump = false;
			jump_cloud->Reset();
		}
	}

	//If player touches the charger he must die, if the player hits the bat from the top the bat must die
	if (!dead && c2->type == COLLIDER_ENEMY)
	{
		p2SString c2_name = c2->callback->name.GetString();
		if (c2_name == "bat" && Collision_from_bottom(c1, c2, 3) && v.y < 0)
		{
			score += 250;
			v.y = (jump_force * 2 / 3);
			c2->entity->dead = true;
		}
		else if (!App->entityManager->player_god_mode && (c2_name == "charger" || (c2_name == "bat" && !c2->entity->dead && !Collision_from_bottom(c1, c2, 3))))
		{
			v.x = 0;
			dead = true;
			loading = true;
			if (!sound_one_time && killed_finished == 0)
			{
				lives--;
				killed_finished = SDL_GetTicks();
				sound_one_time = true;
				if (lives > 0)
					App->audio->PlayFx(killed_fx, 0);
				else
					App->audio->PlayFx(die_fx, 0);
			}
		}
	}

	Entity_OnCollision(c1, c2);
}

bool j1Player::Load(pugi::xml_node& data)
{
	lives = data.attribute("lives").as_uint();
	score = data.attribute("score").as_int();
	coins[0] = data.attribute("coin1").as_bool();
	coins[1] = data.attribute("coin2").as_bool();
	coins[2] = data.attribute("coin3").as_bool();
	App->scene->respawn_enemies = false;
	App->scene->LoadLvl(data.attribute("level").as_int());
	virtualPosition.x = data.attribute("position_x").as_int();
	virtualPosition.y = data.attribute("position_y").as_int();
	App->render->virtualCamPos = -(virtualPosition.x * (int)App->win->GetScale() - 300);
	if (App->render->virtualCamPos > 0)
	{
		App->render->virtualCamPos = 0;
	}
	if (App->render->virtualCamPos < App->scene->max_camera_pos)
	{
		App->render->virtualCamPos = App->scene->max_camera_pos;
	}

	return true;
}

bool j1Player::Save(pugi::xml_node& data) const
{
	data.append_attribute("position_x") = position.x;

	data.append_attribute("position_y") = position.y - 8;

	data.append_attribute("level") = App->scene->current_lvl->data->lvl;

	data.append_attribute("lives") = lives;

	data.append_attribute("score") = score;

	data.append_attribute("coin1") = coins[0];

	data.append_attribute("coin2") = coins[1];

	data.append_attribute("coin3") = coins[2];

	return true;
}<|endoftext|>


<commit_before>
using System;
int a = 100;

if (int a != 600)
{

project element static[object(slider) {
	slider.static.Movable.object(for {user::prefs} meta::element)
} if [[element.slider: IOerror(pre: set, re-set: center)].post:'./makefile'];
else [[ property.element(construct::meta, _init_, propert: null, event: (ev:EventArgs()))
		]]
	  try:
	  const InitUI init;

}
namespace userAuth
{
	[SystemProperty]
	 public class Property
	 {
		SystemProperty property;

		[define]
		 public enum ForEachProperty ()
		 {
			const property = DefineProperty.Android.StoreValue ();
		 }
	 };

}

<commit_msg>Modify File property.cpp<commit_after>
using System;
int a = 100;

if (int a != 600)
{

project element static[object(slider) {
	slider.static.Movable.object(for {user::prefs} meta::element)
} if [[element.slider: IOerror(pre: set, re-set: center)].post:'./makefile'];
else [[ property.element(construct::meta, _init_, propert: null, event: (ev:EventArgs()))
		]]
	  try:
	  const InitUI init;

}
namespace userAuth
{
	[SystemProperty]
	 public class Property
	 {
		SystemProperty property;

		[define]
		 public enum ForEachProperty ()
		 {
			const property = DefineProperty.Android.StoreValue ();
		 }
		cout << ("This is System Property Element") + property
	 };

}

<|endoftext|>


<commit_before>/*
 * keyframe_object.cpp
 *
 * Copyright (c) 2014 Gareth Cross, Chao Qu. All rights reserved.
 */

#include <rviz_ba_viewer/keyframe_object.hpp>

#include <OGRE/OgreManualObject.h>
#include <OGRE/OgreSceneManager.h>
#include <OGRE/OgreSceneNode.h>

Ogre::TexturePtr textureFromMat(const cv::Mat& mat, const std::string& name) {
  assert(!mat.empty());
  //  place mat data into a stream for ogre
  Ogre::TexturePtr texture;
  Ogre::DataStreamPtr data_stream;
  data_stream.bind(new Ogre::MemoryDataStream((void *)mat.data,
                                              mat.total() * mat.elemSize()));

  const Ogre::String res_group =
      Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME;
  Ogre::TextureManager &texture_manager = Ogre::TextureManager::getSingleton();
  //  swap byte order when going to Ogre
  texture = texture_manager.loadRawData(name, res_group, data_stream,
                                        mat.cols, mat.rows,
                                        Ogre::PF_B8G8R8, Ogre::TEX_TYPE_2D, 0);
  //std::cout << "Created texture with dims: " << mat.cols << "," << mat.rows << "\n";
  return texture;
}

KeyFrameObject::KeyFrameObject(Ogre::SceneManager * scene_manager, int id) :
  id_(id), scene_manager_(scene_manager) {

  //  create objects and nodes
  scene_node_ = scene_manager_->createSceneNode();
  scene_node_->setVisible(true);
  frustum_object_= scene_manager_->createManualObject();
  plane_object_ = scene_manager_->createManualObject();
  scene_node_->attachObject(frustum_object_);
  scene_node_->attachObject(plane_object_);

  //  create a material
  const Ogre::String& group =
      Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME;
  Ogre::MaterialManager& man = Ogre::MaterialManager::getSingleton();
  //  some boring settings...
  material_ = man.create("kf_mat_" + std::to_string(id), group);
  material_->setReceiveShadows(false);
  material_->getTechnique(0)->setLightingEnabled(false);
  material_->setCullingMode(Ogre::CULL_NONE);
  material_->setDepthWriteEnabled(true);
  material_->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA);
  //material_->setSceneBlending(Ogre::SBT_REPLACE);
  //material_->setDepthBias(-16.0f, 0.0f);

  frustum_material_ = man.create("kf_mat_frust_" + std::to_string(id), group);
  frustum_material_->setReceiveShadows(false);
  frustum_material_->getTechnique(0)->setLightingEnabled(false);
  frustum_material_->setCullingMode(Ogre::CULL_NONE);
  frustum_material_->setDepthWriteEnabled(true);
  frustum_material_->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA);
}

KeyFrameObject::~KeyFrameObject() {
  //  teardown ogre objects
  scene_node_->detachAllObjects();
  scene_manager_->destroySceneNode(scene_node_);
  scene_manager_->destroyManualObject(frustum_object_);
  scene_manager_->destroyManualObject(plane_object_);
}

void KeyFrameObject::setImage(const cv::Mat& image) {
  image_ = image;
  //  also re-create the ogre texture
  texture_ = textureFromMat(image, "kf_tex_" + std::to_string(id_));
  //std::cout << "Created texture " << texture_->getName() << "\n";
  //std::cout << "Dimensions: " << texture_->getWidth() << ","
  //          << texture_->getHeight() << std::endl;
  dirty_ = true;
}

void KeyFrameObject::setCameraModel(
    const image_geometry::PinholeCameraModel& model,
    int width, int height) {
  cam_model_ = model;
  width_ = width;
  height_ = height;
  dirty_ = true;
}

void KeyFrameObject::setPose(const Ogre::Vector3& position,
                             const Ogre::Quaternion& orientation) {
  scene_node_->setPosition(position);
  scene_node_->setOrientation(orientation);
}

void KeyFrameObject::setColor(const Ogre::Vector4& color) {
  if (color_ != color) {
    color_ = color;
    dirty_ = true;
  }
}

void KeyFrameObject::setImageEnabled(bool imageEnabled) {
  if (imageEnabled != imageEnabled_) {
    imageEnabled_ = imageEnabled;
    dirty_ = true;
  }
}

void KeyFrameObject::createGeometry() {
  if (!dirty_) {
    return; //  no need to re-create geometry
  }
  dirty_ = false;

  const double fx = cam_model_.fx(), fy = cam_model_.fy();
  const double cx = cam_model_.cx(), cy = cam_model_.cy();
  //  generate coordinates of the frustum
  Ogre::Vector3 points[] = {{0,0,1},            //  top left
                            {0,height_,1},      //  bottom left
                            {width_,height_,1}, //  bottom right
                            {width_,0,1}};      //  top right
  for (int i=0; i < 4; i++) {
    points[i].x = (points[i].x - cx) / fx;
    points[i].y = (points[i].y - cy) / fy;
  }
  const Ogre::Vector3 centre(0,0,0);  //  optical centre

  frustum_object_->setRenderQueueGroup(Ogre::RENDER_QUEUE_MAIN);
  frustum_object_->begin(frustum_material_->getName(),
                         Ogre::RenderOperation::OT_LINE_LIST);
  {
    frustum_object_->colour(color_.x,color_.y,color_.z,color_.w);
    //  left side
    frustum_object_->position(points[0]);
    frustum_object_->position(centre);
    frustum_object_->position(centre);
    frustum_object_->position(points[1]);
    //  right side
    frustum_object_->position(points[2]);
    frustum_object_->position(centre);
    frustum_object_->position(centre);
    frustum_object_->position(points[3]);
    //  front rectangle
    for (int i=0; i < 4; i++) {
      frustum_object_->position(points[i]);
      frustum_object_->position(points[(i+1) % 4]);
    }
  }
  frustum_object_->end();

  if (imageEnabled_ && texture_->isLoaded()) {
    //  now the textured quad w/ our image
    //  first set up the material for textured drawing
    Ogre::Pass * pass = material_->getTechnique(0)->getPass(0);
    Ogre::TextureUnitState * tex_unit;
    if (pass->getNumTextureUnitStates() > 0) {
      tex_unit = pass->getTextureUnitState(0);
    } else {
      tex_unit = pass->createTextureUnitState();
    }
    tex_unit->setTextureName(texture_->getName());
    tex_unit->setTextureFiltering(Ogre::TFO_BILINEAR);
    tex_unit->setAlphaOperation(Ogre::LBX_SOURCE1, Ogre::LBS_MANUAL,
                                Ogre::LBS_CURRENT, color_.w); //  use alpha

    plane_object_->setRenderQueueGroup(Ogre::RENDER_QUEUE_MAIN);
    plane_object_->begin(material_->getName(),
                         Ogre::RenderOperation::OT_TRIANGLE_LIST);
    {
      //plane_object_->colour(1.0,0,0,1);
      plane_object_->position(points[0]); //  top left
      plane_object_->textureCoord(0,0);

      plane_object_->position(points[1]); //  bottom left
      plane_object_->textureCoord(0,1);

      plane_object_->position(points[2]); //  bottom right
      plane_object_->textureCoord(1,1);

      plane_object_->position(points[2]); //  bottom right
      plane_object_->textureCoord(1,1);

      plane_object_->position(points[3]); //  top right
      plane_object_->textureCoord(1,0);

      plane_object_->position(points[0]); //  top left
      plane_object_->textureCoord(0,0);
    }
    plane_object_->end();
  } else {
    plane_object_->clear(); //  lazy: just clear it for now
  }
}
<commit_msg>Fixed null pointer crash<commit_after>/*
 * keyframe_object.cpp
 *
 * Copyright (c) 2014 Gareth Cross, Chao Qu. All rights reserved.
 */

#include <rviz_ba_viewer/keyframe_object.hpp>

#include <OGRE/OgreManualObject.h>
#include <OGRE/OgreSceneManager.h>
#include <OGRE/OgreSceneNode.h>

Ogre::TexturePtr textureFromMat(const cv::Mat& mat, const std::string& name) {
  assert(!mat.empty());
  //  place mat data into a stream for ogre
  Ogre::TexturePtr texture;
  Ogre::DataStreamPtr data_stream;
  data_stream.bind(new Ogre::MemoryDataStream((void *)mat.data,
                                              mat.total() * mat.elemSize()));

  const Ogre::String res_group =
      Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME;
  Ogre::TextureManager &texture_manager = Ogre::TextureManager::getSingleton();
  //  swap byte order when going to Ogre
  texture = texture_manager.loadRawData(name, res_group, data_stream,
                                        mat.cols, mat.rows,
                                        Ogre::PF_B8G8R8, Ogre::TEX_TYPE_2D, 0);
  //std::cout << "Created texture with dims: " << mat.cols << "," << mat.rows << "\n";
  return texture;
}

KeyFrameObject::KeyFrameObject(Ogre::SceneManager * scene_manager, int id) :
  id_(id), scene_manager_(scene_manager) {

  //  create objects and nodes
  scene_node_ = scene_manager_->createSceneNode();
  scene_node_->setVisible(true);
  frustum_object_= scene_manager_->createManualObject();
  plane_object_ = scene_manager_->createManualObject();
  scene_node_->attachObject(frustum_object_);
  scene_node_->attachObject(plane_object_);

  //  create a material
  const Ogre::String& group =
      Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME;
  Ogre::MaterialManager& man = Ogre::MaterialManager::getSingleton();
  //  some boring settings...
  material_ = man.create("kf_mat_" + std::to_string(id), group);
  material_->setReceiveShadows(false);
  material_->getTechnique(0)->setLightingEnabled(false);
  material_->setCullingMode(Ogre::CULL_NONE);
  material_->setDepthWriteEnabled(true);
  material_->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA);
  //material_->setSceneBlending(Ogre::SBT_REPLACE);
  //material_->setDepthBias(-16.0f, 0.0f);

  frustum_material_ = man.create("kf_mat_frust_" + std::to_string(id), group);
  frustum_material_->setReceiveShadows(false);
  frustum_material_->getTechnique(0)->setLightingEnabled(false);
  frustum_material_->setCullingMode(Ogre::CULL_NONE);
  frustum_material_->setDepthWriteEnabled(true);
  frustum_material_->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA);
}

KeyFrameObject::~KeyFrameObject() {
  //  teardown ogre objects
  scene_node_->detachAllObjects();
  scene_manager_->destroySceneNode(scene_node_);
  scene_manager_->destroyManualObject(frustum_object_);
  scene_manager_->destroyManualObject(plane_object_);
}

void KeyFrameObject::setImage(const cv::Mat& image) {
  image_ = image;
  //  also re-create the ogre texture
  texture_ = textureFromMat(image, "kf_tex_" + std::to_string(id_));
  //std::cout << "Created texture " << texture_->getName() << "\n";
  //std::cout << "Dimensions: " << texture_->getWidth() << ","
  //          << texture_->getHeight() << std::endl;
  dirty_ = true;
}

void KeyFrameObject::setCameraModel(
    const image_geometry::PinholeCameraModel& model,
    int width, int height) {
  cam_model_ = model;
  width_ = width;
  height_ = height;
  dirty_ = true;
}

void KeyFrameObject::setPose(const Ogre::Vector3& position,
                             const Ogre::Quaternion& orientation) {
  scene_node_->setPosition(position);
  scene_node_->setOrientation(orientation);
}

void KeyFrameObject::setColor(const Ogre::Vector4& color) {
  if (color_ != color) {
    color_ = color;
    dirty_ = true;
  }
}

void KeyFrameObject::setImageEnabled(bool imageEnabled) {
  if (imageEnabled != imageEnabled_) {
    imageEnabled_ = imageEnabled;
    dirty_ = true;
  }
}

void KeyFrameObject::createGeometry() {
  if (!dirty_) {
    return; //  no need to re-create geometry
  }
  dirty_ = false;

  const double fx = cam_model_.fx(), fy = cam_model_.fy();
  const double cx = cam_model_.cx(), cy = cam_model_.cy();
  //  generate coordinates of the frustum
  Ogre::Vector3 points[] = {{0,0,1},            //  top left
                            {0,height_,1},      //  bottom left
                            {width_,height_,1}, //  bottom right
                            {width_,0,1}};      //  top right
  for (int i=0; i < 4; i++) {
    points[i].x = (points[i].x - cx) / fx;
    points[i].y = (points[i].y - cy) / fy;
  }
  const Ogre::Vector3 centre(0,0,0);  //  optical centre

  frustum_object_->setRenderQueueGroup(Ogre::RENDER_QUEUE_MAIN);
  frustum_object_->begin(frustum_material_->getName(),
                         Ogre::RenderOperation::OT_LINE_LIST);
  {
    frustum_object_->colour(color_.x,color_.y,color_.z,color_.w);
    //  left side
    frustum_object_->position(points[0]);
    frustum_object_->position(centre);
    frustum_object_->position(centre);
    frustum_object_->position(points[1]);
    //  right side
    frustum_object_->position(points[2]);
    frustum_object_->position(centre);
    frustum_object_->position(centre);
    frustum_object_->position(points[3]);
    //  front rectangle
    for (int i=0; i < 4; i++) {
      frustum_object_->position(points[i]);
      frustum_object_->position(points[(i+1) % 4]);
    }
  }
  frustum_object_->end();

  if (imageEnabled_ && !texture_.isNull() && texture_->isLoaded()) {
    //  now the textured quad w/ our image
    //  first set up the material for textured drawing
    Ogre::Pass * pass = material_->getTechnique(0)->getPass(0);
    Ogre::TextureUnitState * tex_unit;
    if (pass->getNumTextureUnitStates() > 0) {
      tex_unit = pass->getTextureUnitState(0);
    } else {
      tex_unit = pass->createTextureUnitState();
    }
    tex_unit->setTextureName(texture_->getName());
    tex_unit->setTextureFiltering(Ogre::TFO_BILINEAR);
    tex_unit->setAlphaOperation(Ogre::LBX_SOURCE1, Ogre::LBS_MANUAL,
                                Ogre::LBS_CURRENT, color_.w); //  use alpha

    plane_object_->setRenderQueueGroup(Ogre::RENDER_QUEUE_MAIN);
    plane_object_->begin(material_->getName(),
                         Ogre::RenderOperation::OT_TRIANGLE_LIST);
    {
      //plane_object_->colour(1.0,0,0,1);
      plane_object_->position(points[0]); //  top left
      plane_object_->textureCoord(0,0);

      plane_object_->position(points[1]); //  bottom left
      plane_object_->textureCoord(0,1);

      plane_object_->position(points[2]); //  bottom right
      plane_object_->textureCoord(1,1);

      plane_object_->position(points[2]); //  bottom right
      plane_object_->textureCoord(1,1);

      plane_object_->position(points[3]); //  top right
      plane_object_->textureCoord(1,0);

      plane_object_->position(points[0]); //  top left
      plane_object_->textureCoord(0,0);
    }
    plane_object_->end();
  } else {
    plane_object_->clear(); //  lazy: just clear it for now
  }
}
<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (C) 2009 by Lothar May                                      *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include <net/downloaderthread.h>
#include <net/downloadhelper.h>
#include <net/netexception.h>
#include <boost/filesystem.hpp>
#include <core/loghelper.h>

#include <fstream>
#include <algorithm>

#define DOWNLOAD_DELAY_MSEC					10

using namespace std;
using namespace boost::filesystem;

DownloaderThread::DownloaderThread()
: m_downloadInProgress(false)
{
	m_downloadHelper.reset(new DownloadHelper());
}

DownloaderThread::~DownloaderThread()
{
}

void
DownloaderThread::QueueDownload(unsigned downloadId, const std::string &url, const std::string &filename)
{
	boost::mutex::scoped_lock lock(m_downloadQueueMutex);
	m_downloadQueue.push(DownloadData(downloadId, url, filename));
}

bool
DownloaderThread::HasDownloadResult() const
{
	boost::mutex::scoped_lock lock(m_downloadDoneQueueMutex);
	return !m_downloadDoneQueue.empty();
}

bool
DownloaderThread::GetDownloadResult(unsigned &downloadId, std::vector<unsigned char> &filedata)
{
	bool result = false;
	boost::mutex::scoped_lock lock(m_downloadDoneQueueMutex);
	if (!m_downloadDoneQueue.empty())
	{
		const ResultData &d = m_downloadDoneQueue.front();
		downloadId = d.id;
		filedata = d.data;
		m_downloadDoneQueue.pop();
		result = true;
	}
	return result;
}

void
DownloaderThread::Main()
{
	while (!ShouldTerminate())
	{
		try
		{
			if (m_downloadInProgress)
			{
				m_downloadInProgress = !m_downloadHelper->Process();
			}

			if (!m_downloadInProgress)
			{
				// Previous download was finished.
				if (m_curDownloadData)
				{
					path filepath(m_curDownloadData->filename);
					ifstream instream(filepath.file_string().c_str(), ios_base::in | ios_base::binary);
					vector<unsigned char> fileData;
					copy(istream_iterator<unsigned char>(instream), istream_iterator<unsigned char>(), back_inserter(fileData));
					instream.close();
					remove(filepath);

					{
						boost::mutex::scoped_lock lock(m_downloadDoneQueueMutex);
						m_downloadDoneQueue.push(ResultData(m_curDownloadData->id, fileData));
					}
					m_curDownloadData.reset();
				}

				// Take a break.
				Msleep(DOWNLOAD_DELAY_MSEC);

				// Start next download.
				{
					boost::mutex::scoped_lock lock(m_downloadQueueMutex);
					if (!m_downloadQueue.empty())
					{
						m_curDownloadData.reset(new DownloadData(m_downloadQueue.front()));
						m_downloadQueue.pop();
					}
				}
				if (m_curDownloadData && !m_curDownloadData->filename.empty())
				{
					LOG_MSG("URL: " + m_curDownloadData->address);
					LOG_MSG("File: " + filepath.file_string());
					path filepath(m_curDownloadData->filename);
					m_downloadHelper->Init(m_curDownloadData->address, filepath.file_string());
					m_downloadInProgress = true;
				}
			}
		}
		catch (const NetException &e)
		{
			LOG_ERROR(e.what());
			m_downloadInProgress = false;
			m_curDownloadData.reset();
		}
	}
}

<commit_msg>Fixed logging.<commit_after>/***************************************************************************
 *   Copyright (C) 2009 by Lothar May                                      *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include <net/downloaderthread.h>
#include <net/downloadhelper.h>
#include <net/netexception.h>
#include <boost/filesystem.hpp>
#include <core/loghelper.h>

#include <fstream>
#include <algorithm>

#define DOWNLOAD_DELAY_MSEC					10

using namespace std;
using namespace boost::filesystem;

DownloaderThread::DownloaderThread()
: m_downloadInProgress(false)
{
	m_downloadHelper.reset(new DownloadHelper());
}

DownloaderThread::~DownloaderThread()
{
}

void
DownloaderThread::QueueDownload(unsigned downloadId, const std::string &url, const std::string &filename)
{
	boost::mutex::scoped_lock lock(m_downloadQueueMutex);
	m_downloadQueue.push(DownloadData(downloadId, url, filename));
}

bool
DownloaderThread::HasDownloadResult() const
{
	boost::mutex::scoped_lock lock(m_downloadDoneQueueMutex);
	return !m_downloadDoneQueue.empty();
}

bool
DownloaderThread::GetDownloadResult(unsigned &downloadId, std::vector<unsigned char> &filedata)
{
	bool result = false;
	boost::mutex::scoped_lock lock(m_downloadDoneQueueMutex);
	if (!m_downloadDoneQueue.empty())
	{
		const ResultData &d = m_downloadDoneQueue.front();
		downloadId = d.id;
		filedata = d.data;
		m_downloadDoneQueue.pop();
		result = true;
	}
	return result;
}

void
DownloaderThread::Main()
{
	while (!ShouldTerminate())
	{
		try
		{
			if (m_downloadInProgress)
			{
				m_downloadInProgress = !m_downloadHelper->Process();
			}

			if (!m_downloadInProgress)
			{
				// Previous download was finished.
				if (m_curDownloadData)
				{
					path filepath(m_curDownloadData->filename);
					ifstream instream(filepath.file_string().c_str(), ios_base::in | ios_base::binary);
					vector<unsigned char> fileData;
					copy(istream_iterator<unsigned char>(instream), istream_iterator<unsigned char>(), back_inserter(fileData));
					instream.close();
					remove(filepath);

					{
						boost::mutex::scoped_lock lock(m_downloadDoneQueueMutex);
						m_downloadDoneQueue.push(ResultData(m_curDownloadData->id, fileData));
					}
					m_curDownloadData.reset();
				}

				// Take a break.
				Msleep(DOWNLOAD_DELAY_MSEC);

				// Start next download.
				{
					boost::mutex::scoped_lock lock(m_downloadQueueMutex);
					if (!m_downloadQueue.empty())
					{
						m_curDownloadData.reset(new DownloadData(m_downloadQueue.front()));
						m_downloadQueue.pop();
					}
				}
				if (m_curDownloadData && !m_curDownloadData->filename.empty())
				{
					path filepath(m_curDownloadData->filename);
					LOG_MSG("URL: " + m_curDownloadData->address);
					LOG_MSG("File: " + filepath.file_string());
					m_downloadHelper->Init(m_curDownloadData->address, filepath.file_string());
					m_downloadInProgress = true;
				}
			}
		}
		catch (const NetException &e)
		{
			LOG_ERROR(e.what());
			m_downloadInProgress = false;
			m_curDownloadData.reset();
		}
	}
}

<|endoftext|>


<commit_before>/*
 * Copyright 2016 - 2021 gary@drinkingtea.net
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <ox/claw/claw.hpp>
#include <nostalgia/core/gfx.hpp>
#include <nostalgia/core/gfx.hpp>

#include "gfx.hpp"

namespace nostalgia::core {

static ox::Result<ox::Vector<char>> readFile(Context *ctx, const ox::FileAddress &file) noexcept {
	oxRequire(stat, ctx->rom->stat(file));
	ox::Vector<char> buff(stat.size);
	oxReturnError(ctx->rom->read(file, buff.data(), buff.size()));
	return ox::move(buff);
}

template<typename T>
ox::Result<T> readObj(Context *ctx, const ox::FileAddress &file) noexcept {
	oxRequire(buff, readFile(ctx, file));
	T t;
	oxReturnError(ox::readClaw(buff.data(), buff.size(), &t));
	return ox::move(t);
}

ox::Error initConsole(Context *ctx) noexcept {
	constexpr auto TilesheetAddr = "/TileSheets/Charset.ng";
	constexpr auto PaletteAddr = "/Palettes/Charset.npal";
	setBgStatus(ctx, 0b0001);
	return loadBgTileSheet(ctx, 0, TilesheetAddr, PaletteAddr);
}

ox::Error loadSpriteTileSheet(Context*,
                              int,
                              ox::FileAddress,
                              ox::FileAddress) noexcept {
	return OxError(0);
}

ox::Error loadBgTileSheet(Context *ctx,
                          int section,
                          ox::FileAddress tilesheetPath,
                          ox::FileAddress palettePath) noexcept {
	oxRequire(tilesheet, readObj<NostalgiaGraphic>(ctx, tilesheetPath));
	if (!palettePath) {
		palettePath = tilesheet.defaultPalette;
	}
	oxRequire(palette, readObj<NostalgiaPalette>(ctx, palettePath));
	const unsigned bytesPerTile = tilesheet.bpp == 8 ? 64 : 32;
	const auto tiles = tilesheet.pixels.size() / bytesPerTile;
	constexpr int width = 8;
	const int height = 8 * tiles;
	ox::Vector<uint32_t> pixels;
	if (bytesPerTile == 64) { // 8 BPP
		pixels.resize(tilesheet.pixels.size());
		for (std::size_t i = 0; i < tilesheet.pixels.size(); ++i) {
			pixels[i] = toColor32(palette.colors[tilesheet.pixels[i]]);
		}
	} else { // 4 BPP
		pixels.resize(tilesheet.pixels.size() * 2);
		for (std::size_t i = 0; i < tilesheet.pixels.size(); ++i) {
			pixels[i * 2 + 0] = toColor32(palette.colors[tilesheet.pixels[i] & 0xF]);
			pixels[i * 2 + 1] = toColor32(palette.colors[tilesheet.pixels[i] >> 4]);
		}
	}
	return renderer::loadBgTexture(ctx, section, pixels.data(), width, height);
}

void puts(Context *ctx, int column, int row, const char *str) noexcept {
	for (int i = 0; str[i]; ++i) {
		setTile(ctx, 0, column + i, row, static_cast<uint8_t>(charMap[static_cast<int>(str[i])]));
	}
}

}
<commit_msg>[nostalgia/core/userland] Cleanup readObj<commit_after>/*
 * Copyright 2016 - 2021 gary@drinkingtea.net
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <ox/claw/claw.hpp>
#include <nostalgia/core/gfx.hpp>
#include <nostalgia/core/gfx.hpp>

#include "gfx.hpp"

namespace nostalgia::core {

template<typename T>
static ox::Result<T> readObj(Context *ctx, const ox::FileAddress &file) noexcept {
	oxRequire(buff, ctx->rom->read(file));
	return ox::readClaw<T>(buff);
}

ox::Error initConsole(Context *ctx) noexcept {
	constexpr auto TilesheetAddr = "/TileSheets/Charset.ng";
	constexpr auto PaletteAddr = "/Palettes/Charset.npal";
	setBgStatus(ctx, 0b0001);
	return loadBgTileSheet(ctx, 0, TilesheetAddr, PaletteAddr);
}

ox::Error loadSpriteTileSheet(Context*,
                              int,
                              ox::FileAddress,
                              ox::FileAddress) noexcept {
	return OxError(0);
}

ox::Error loadBgTileSheet(Context *ctx,
                          int section,
                          ox::FileAddress tilesheetPath,
                          ox::FileAddress palettePath) noexcept {
	oxRequire(tilesheet, readObj<NostalgiaGraphic>(ctx, tilesheetPath));
	if (!palettePath) {
		palettePath = tilesheet.defaultPalette;
	}
	oxRequire(palette, readObj<NostalgiaPalette>(ctx, palettePath));
	const unsigned bytesPerTile = tilesheet.bpp == 8 ? 64 : 32;
	const auto tiles = tilesheet.pixels.size() / bytesPerTile;
	constexpr int width = 8;
	const int height = 8 * tiles;
	ox::Vector<uint32_t> pixels;
	if (bytesPerTile == 64) { // 8 BPP
		pixels.resize(tilesheet.pixels.size());
		for (std::size_t i = 0; i < tilesheet.pixels.size(); ++i) {
			pixels[i] = toColor32(palette.colors[tilesheet.pixels[i]]);
		}
	} else { // 4 BPP
		pixels.resize(tilesheet.pixels.size() * 2);
		for (std::size_t i = 0; i < tilesheet.pixels.size(); ++i) {
			pixels[i * 2 + 0] = toColor32(palette.colors[tilesheet.pixels[i] & 0xF]);
			pixels[i * 2 + 1] = toColor32(palette.colors[tilesheet.pixels[i] >> 4]);
		}
	}
	return renderer::loadBgTexture(ctx, section, pixels.data(), width, height);
}

void puts(Context *ctx, int column, int row, const char *str) noexcept {
	for (int i = 0; str[i]; ++i) {
		setTile(ctx, 0, column + i, row, static_cast<uint8_t>(charMap[static_cast<int>(str[i])]));
	}
}

}
<|endoftext|>


<commit_before>/*
 *
 * $Id$
 *
 * History:
 *
 * Bernd Wuebben, wuebben@math.cornell.edu:
 *
 * Much of this  is taken from the pppd sources in particular
 * /pppstat/pppstat.c, and modified to suit the needs of kppp.
 *
 *
 * Here the original history of pppstat.c:
 *
 * perkins@cps.msu.edu: Added compression statistics and alternate
 *                display. 11/94
 *
 * Brad Parker (brad@cayman.com) 6/92
 *
 * from the original "slstats" by Van Jaconson
 *
 * Copyright (c) 1989 Regents of the University of California.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms are permitted
 * provided that the above copyright notice and this paragraph are
 * duplicated in all such forms and that any documentation,
 * advertising materials, and other materials related to such
 * distribution and use acknowledge that the software was developed
 * by the University of California, Berkeley.  The name of the
 * University may not be used to endorse or promote products derived
 * from this software without specific prior written permission.
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 *	Van Jacobson (van@helios.ee.lbl.gov), Dec 31, 1989:
 *	- Initial distribution.
 */

#include <kdefakes.h>
#include <config.h>

#include <ctype.h>
#include <errno.h>

#include <stdio.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>
#include <net/ppp_defs.h>

#include "config.h"
#include "config-kppp.h"
#include "pppstats.h"

#ifndef STREAMS
 #if defined(__linux__) && defined(__powerpc__) \
    && (__GLIBC__ == 2 && __GLIBC_MINOR__ == 0)
  /* kludge alert! */
  #undef __GLIBC__
 #endif
 #include <sys/socket.h>		/* *BSD, Linux, NeXT, Ultrix etc. */
 #ifndef HAVE_NET_IF_PPP_H
  #ifdef HAVE_LINUX_IF_PPP_H
   #include <linux/if.h>
   #include <linux/if_ppp.h>
  #endif
 #else
  #include <net/if.h>
  #include <net/if_ppp.h>
 #endif

#else	/* STREAMS */
 #include <sys/socket.h>
 #include <sys/stropts.h>	/* SVR4, Solaris 2, SunOS 4, OSF/1, etc. */
 #include <net/ppp_defs.h>
 #include <net/pppio.h>
 #include <net/if.h>
 #include <sys/sockio.h>

#endif	/* STREAMS */

#include <qtimer.h>
#include <kdebug.h>

PPPStats::PPPStats()
{
  clear();
  timer = new QTimer;
  connect(timer, SIGNAL(timeout()), SLOT(timerClick()));
}

PPPStats::~PPPStats() {
  stop();
  delete timer;
}

void PPPStats::clear()
{
  ibytes = 0;
  ipackets = 0;
  ibytes_last = 0;
  obytes_last = 0;
  compressedin = 0;
  uncompressedin = 0;
  errorin = 0;
  obytes = 0;
  opackets = 0;
  compressed = 0;
  packetsunc = 0;
  packetsoutunc = 0;
  ioStatus = BytesNone;
}

void PPPStats::timerClick() {
  enum IOStatus newStatus;

  doStats();

  if((ibytes != ibytes_last) && (obytes != obytes_last))
    newStatus = BytesBoth;
  else if(ibytes != ibytes_last)
    newStatus = BytesIn;
  else if(obytes != obytes_last)
    newStatus = BytesOut;
  else
    newStatus = BytesNone;

  if(newStatus != ioStatus)
    emit statsChanged(ioStatus = newStatus);

  ibytes_last = ibytes;
  obytes_last = obytes;
}

void PPPStats::setUnit(int u) {
  unit = u;
  sprintf(unitName, "ppp%d", unit);
}

void PPPStats::start() {
  timer->start(PPP_STATS_INTERVAL);
}

void PPPStats::stop() {
  emit statsChanged(BytesNone);
  timer->stop();
}

bool PPPStats::ifIsUp() {
  bool is_up;
  struct ifreq ifr;

#if defined(__svr4__ )
  usleep(1000000); // Needed for Solaris ?!
#endif

#ifdef STREAMS
    if ((t = open("/dev/ppp", O_RDONLY)) < 0) {
	perror("pppstats: Couldn't open /dev/ppp: ");
	return false;
    }
    if (!strioctl(t, PPPIO_ATTACH, (char*)&unit, sizeof(int), 0)) {
	fprintf(stderr, "pppstats: ppp%d is not available\n", unit);
	::close(t);
	return false;
    }
    // TODO: close t somewhere again
#endif
    if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
	perror("Couldn't create IP socket");
	return false;
    }

    strlcpy(ifr.ifr_name, unitName, sizeof(ifr.ifr_name));

    if(ioctl(s, SIOCGIFFLAGS, (caddr_t) &ifr) < 0) {
        if (errno)
          fprintf(stderr, "Couldn't find interface %s: %s\n",
                  unitName, strerror(errno));
	::close(s);
	s = 0;
	return 0;
    }

    if ((ifr.ifr_flags & IFF_UP) && (ifr.ifr_flags & IFF_RUNNING)) {
	is_up = true;
	kDebug(5002) << "Interface is up" << endl;
    }
    else{
      is_up = false;
      ::close(s);
      s = 0;
      kDebug(5002) << "Interface is down" << endl;
    }

    return is_up;
}

bool PPPStats::initStats() {

  struct sockaddr_in *sinp;
  struct ifreq ifr;

  clear();

  strlcpy(ifr.ifr_name, unitName, sizeof(ifr.ifr_name));

  if (ioctl(s, SIOCGIFADDR, &ifr) < 0) {
  }

  sinp = (struct sockaddr_in*)&ifr.ifr_addr;

  if(sinp->sin_addr.s_addr)
    local_ip_address = inet_ntoa(sinp->sin_addr);
  else
    local_ip_address = "";
  kDebug(5002) << "Local IP: " << local_ip_address << endl;

  if (ioctl(s, SIOCGIFDSTADDR, &ifr) < 0)
    ;

  sinp = (struct sockaddr_in*)&ifr.ifr_dstaddr;

  if(sinp->sin_addr.s_addr)
    remote_ip_address = inet_ntoa(sinp->sin_addr);
  else
    remote_ip_address = "";
  kDebug(5002) << "Remote IP: " << remote_ip_address << endl;

  return true;

}

bool PPPStats::doStats() {
  struct ppp_stats cur;

  if(! get_ppp_stats(&cur)){
    return false;
  }

  // "in"  "pack"  "comp"  "uncomp"  "err"
  // IN    PACK    VJCOMP  VJUNC     VJERR

  ibytes =   cur.p.ppp_ibytes; 			// bytes received
  ipackets =   cur.p.ppp_ipackets; 		// packets received
  compressedin =  cur.vj.vjs_compressedin; 	// inbound compressed packets
  uncompressedin =   cur.vj.vjs_uncompressedin; // inbound uncompressed packets
  errorin =  cur.vj.vjs_errorin; 		//receive errors

  //  "out"  "pack"  "comp"  "uncomp"  "ip"
  // OUT       PACK   JCOMP   VJUNC    NON-VJ

  obytes =  cur.p.ppp_obytes; 		       	// raw bytes sent
  opackets =  cur.p.ppp_opackets; 		// packets sent
  compressed =  cur.vj.vjs_compressed; 		//outbound compressed packets

  // outbound packets - outbound compressed packets
  packetsunc =  cur.vj.vjs_packets - cur.vj.vjs_compressed;

  // packets sent - oubount compressed
  packetsoutunc = cur.p.ppp_opackets - cur.vj.vjs_packets;

  return true;
}

#ifndef STREAMS
bool PPPStats::get_ppp_stats(struct ppp_stats *curp){

  struct ifpppstatsreq req;

    if(s==0)
      return false;

#ifdef __linux__
    req.stats_ptr = (caddr_t) &req.stats;
    sprintf(req.ifr__name, "ppp%d", unit);
#else
    sprintf(req.ifr_name, "ppp%d", unit);
#endif
    if (ioctl(s, SIOCGPPPSTATS, &req) < 0) {
	if (errno == ENOTTY)
	    fprintf(stderr, "pppstats: kernel support missing\n");
	else
	    perror("ioctl(SIOCGPPPSTATS)");
	return false;
    }
    *curp = req.stats;
    return true;
}

#else	/* STREAMS */
bool PPPStats::get_ppp_stats( struct ppp_stats *curp){

    if (!strioctl(t, PPPIO_GETSTAT, (char*)curp, 0, sizeof(*curp))) {
	if (errno == EINVAL)
	    fprintf(stderr, "pppstats: kernel support missing\n");
	else
	    perror("pppstats: Couldn't get statistics");
	return false;
    }
    return true;
}

bool PPPStats::strioctl(int fd, int cmd, char* ptr, int ilen, int olen){

    struct strioctl str;

    str.ic_cmd = cmd;
    str.ic_timout = 0;
    str.ic_len = ilen;
    str.ic_dp = ptr;
    if (ioctl(fd, I_STR, &str) == -1)
	return false;
    if (str.ic_len != olen)
	fprintf(stderr, "strioctl: expected %d bytes, got %d for cmd %x\n",
	       olen, str.ic_len, cmd);
    return true;
}
#endif /* STREAMS */

#include "pppstats.moc"

<commit_msg>avoid gcc empty body warning<commit_after>/*
 *
 * $Id$
 *
 * History:
 *
 * Bernd Wuebben, wuebben@math.cornell.edu:
 *
 * Much of this  is taken from the pppd sources in particular
 * /pppstat/pppstat.c, and modified to suit the needs of kppp.
 *
 *
 * Here the original history of pppstat.c:
 *
 * perkins@cps.msu.edu: Added compression statistics and alternate
 *                display. 11/94
 *
 * Brad Parker (brad@cayman.com) 6/92
 *
 * from the original "slstats" by Van Jaconson
 *
 * Copyright (c) 1989 Regents of the University of California.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms are permitted
 * provided that the above copyright notice and this paragraph are
 * duplicated in all such forms and that any documentation,
 * advertising materials, and other materials related to such
 * distribution and use acknowledge that the software was developed
 * by the University of California, Berkeley.  The name of the
 * University may not be used to endorse or promote products derived
 * from this software without specific prior written permission.
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 *	Van Jacobson (van@helios.ee.lbl.gov), Dec 31, 1989:
 *	- Initial distribution.
 */

#include <kdefakes.h>
#include <config.h>

#include <ctype.h>
#include <errno.h>

#include <stdio.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>
#include <net/ppp_defs.h>

#include "config.h"
#include "config-kppp.h"
#include "pppstats.h"

#ifndef STREAMS
 #if defined(__linux__) && defined(__powerpc__) \
    && (__GLIBC__ == 2 && __GLIBC_MINOR__ == 0)
  /* kludge alert! */
  #undef __GLIBC__
 #endif
 #include <sys/socket.h>		/* *BSD, Linux, NeXT, Ultrix etc. */
 #ifndef HAVE_NET_IF_PPP_H
  #ifdef HAVE_LINUX_IF_PPP_H
   #include <linux/if.h>
   #include <linux/if_ppp.h>
  #endif
 #else
  #include <net/if.h>
  #include <net/if_ppp.h>
 #endif

#else	/* STREAMS */
 #include <sys/socket.h>
 #include <sys/stropts.h>	/* SVR4, Solaris 2, SunOS 4, OSF/1, etc. */
 #include <net/ppp_defs.h>
 #include <net/pppio.h>
 #include <net/if.h>
 #include <sys/sockio.h>

#endif	/* STREAMS */

#include <qtimer.h>
#include <kdebug.h>

PPPStats::PPPStats()
{
  clear();
  timer = new QTimer;
  connect(timer, SIGNAL(timeout()), SLOT(timerClick()));
}

PPPStats::~PPPStats() {
  stop();
  delete timer;
}

void PPPStats::clear()
{
  ibytes = 0;
  ipackets = 0;
  ibytes_last = 0;
  obytes_last = 0;
  compressedin = 0;
  uncompressedin = 0;
  errorin = 0;
  obytes = 0;
  opackets = 0;
  compressed = 0;
  packetsunc = 0;
  packetsoutunc = 0;
  ioStatus = BytesNone;
}

void PPPStats::timerClick() {
  enum IOStatus newStatus;

  doStats();

  if((ibytes != ibytes_last) && (obytes != obytes_last))
    newStatus = BytesBoth;
  else if(ibytes != ibytes_last)
    newStatus = BytesIn;
  else if(obytes != obytes_last)
    newStatus = BytesOut;
  else
    newStatus = BytesNone;

  if(newStatus != ioStatus)
    emit statsChanged(ioStatus = newStatus);

  ibytes_last = ibytes;
  obytes_last = obytes;
}

void PPPStats::setUnit(int u) {
  unit = u;
  sprintf(unitName, "ppp%d", unit);
}

void PPPStats::start() {
  timer->start(PPP_STATS_INTERVAL);
}

void PPPStats::stop() {
  emit statsChanged(BytesNone);
  timer->stop();
}

bool PPPStats::ifIsUp() {
  bool is_up;
  struct ifreq ifr;

#if defined(__svr4__ )
  usleep(1000000); // Needed for Solaris ?!
#endif

#ifdef STREAMS
    if ((t = open("/dev/ppp", O_RDONLY)) < 0) {
	perror("pppstats: Couldn't open /dev/ppp: ");
	return false;
    }
    if (!strioctl(t, PPPIO_ATTACH, (char*)&unit, sizeof(int), 0)) {
	fprintf(stderr, "pppstats: ppp%d is not available\n", unit);
	::close(t);
	return false;
    }
    // TODO: close t somewhere again
#endif
    if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
	perror("Couldn't create IP socket");
	return false;
    }

    strlcpy(ifr.ifr_name, unitName, sizeof(ifr.ifr_name));

    if(ioctl(s, SIOCGIFFLAGS, (caddr_t) &ifr) < 0) {
        if (errno)
          fprintf(stderr, "Couldn't find interface %s: %s\n",
                  unitName, strerror(errno));
	::close(s);
	s = 0;
	return 0;
    }

    if ((ifr.ifr_flags & IFF_UP) && (ifr.ifr_flags & IFF_RUNNING)) {
	is_up = true;
	kDebug(5002) << "Interface is up" << endl;
    }
    else{
      is_up = false;
      ::close(s);
      s = 0;
      kDebug(5002) << "Interface is down" << endl;
    }

    return is_up;
}

bool PPPStats::initStats() {

  struct sockaddr_in *sinp;
  struct ifreq ifr;

  clear();

  strlcpy(ifr.ifr_name, unitName, sizeof(ifr.ifr_name));

  if (ioctl(s, SIOCGIFADDR, &ifr) < 0) {
  }

  sinp = (struct sockaddr_in*)&ifr.ifr_addr;

  if(sinp->sin_addr.s_addr)
    local_ip_address = inet_ntoa(sinp->sin_addr);
  else
    local_ip_address = "";
  kDebug(5002) << "Local IP: " << local_ip_address << endl;

  if (ioctl(s, SIOCGIFDSTADDR, &ifr) < 0) {
  }

  sinp = (struct sockaddr_in*)&ifr.ifr_dstaddr;

  if(sinp->sin_addr.s_addr)
    remote_ip_address = inet_ntoa(sinp->sin_addr);
  else
    remote_ip_address = "";
  kDebug(5002) << "Remote IP: " << remote_ip_address << endl;

  return true;

}

bool PPPStats::doStats() {
  struct ppp_stats cur;

  if(! get_ppp_stats(&cur)){
    return false;
  }

  // "in"  "pack"  "comp"  "uncomp"  "err"
  // IN    PACK    VJCOMP  VJUNC     VJERR

  ibytes =   cur.p.ppp_ibytes; 			// bytes received
  ipackets =   cur.p.ppp_ipackets; 		// packets received
  compressedin =  cur.vj.vjs_compressedin; 	// inbound compressed packets
  uncompressedin =   cur.vj.vjs_uncompressedin; // inbound uncompressed packets
  errorin =  cur.vj.vjs_errorin; 		//receive errors

  //  "out"  "pack"  "comp"  "uncomp"  "ip"
  // OUT       PACK   JCOMP   VJUNC    NON-VJ

  obytes =  cur.p.ppp_obytes; 		       	// raw bytes sent
  opackets =  cur.p.ppp_opackets; 		// packets sent
  compressed =  cur.vj.vjs_compressed; 		//outbound compressed packets

  // outbound packets - outbound compressed packets
  packetsunc =  cur.vj.vjs_packets - cur.vj.vjs_compressed;

  // packets sent - oubount compressed
  packetsoutunc = cur.p.ppp_opackets - cur.vj.vjs_packets;

  return true;
}

#ifndef STREAMS
bool PPPStats::get_ppp_stats(struct ppp_stats *curp){

  struct ifpppstatsreq req;

    if(s==0)
      return false;

#ifdef __linux__
    req.stats_ptr = (caddr_t) &req.stats;
    sprintf(req.ifr__name, "ppp%d", unit);
#else
    sprintf(req.ifr_name, "ppp%d", unit);
#endif
    if (ioctl(s, SIOCGPPPSTATS, &req) < 0) {
	if (errno == ENOTTY)
	    fprintf(stderr, "pppstats: kernel support missing\n");
	else
	    perror("ioctl(SIOCGPPPSTATS)");
	return false;
    }
    *curp = req.stats;
    return true;
}

#else	/* STREAMS */
bool PPPStats::get_ppp_stats( struct ppp_stats *curp){

    if (!strioctl(t, PPPIO_GETSTAT, (char*)curp, 0, sizeof(*curp))) {
	if (errno == EINVAL)
	    fprintf(stderr, "pppstats: kernel support missing\n");
	else
	    perror("pppstats: Couldn't get statistics");
	return false;
    }
    return true;
}

bool PPPStats::strioctl(int fd, int cmd, char* ptr, int ilen, int olen){

    struct strioctl str;

    str.ic_cmd = cmd;
    str.ic_timout = 0;
    str.ic_len = ilen;
    str.ic_dp = ptr;
    if (ioctl(fd, I_STR, &str) == -1)
	return false;
    if (str.ic_len != olen)
	fprintf(stderr, "strioctl: expected %d bytes, got %d for cmd %x\n",
	       olen, str.ic_len, cmd);
    return true;
}
#endif /* STREAMS */

#include "pppstats.moc"

<|endoftext|>


<commit_before>#include "dynet/init.h"

#include "dynet/aligned-mem-pool.h"
#include "dynet/dynet.h"
#include "dynet/weight-decay.h"
#include "dynet/globals.h"
#include "dynet/str-util.h"
#include "dynet/devices.h"

#include <iostream>
#include <random>
#include <cmath>

#if HAVE_CUDA
#include "dynet/cuda.h"
#include <device_launch_parameters.h>
#endif

using namespace std;

namespace dynet {

DynetParams::DynetParams() : random_seed(0), mem_descriptor("512"), weight_decay(0), autobatch(0), profiling(0),
  shared_parameters(false), ngpus_requested(false), ids_requested(false), cpu_requested(false), requested_gpus(-1)
{
#if HAVE_CUDA
  gpu_mask = std::vector<int>(MAX_GPUS, 0);
#endif
}

DynetParams::~DynetParams()
{
}

static bool has_arg(int argi, int argc, char** argv) {
  const std::string arg(argv[argi]);
  auto pos = arg.find('=');
  if (pos == std::string::npos) {
    if ((argi + 1) < argc) {
      const std::string argn(argv[argi + 1]);
      if (argn.size() < 2 || !(argn[0] == '-' && argn[1] == '-'))
        return true;
    }
  } else {
    // check that there is actually a string present
    if ((pos + 1) < arg.size()) {
      return true;
    }
  }
  return false;
}

static void remove_args(int& argc, char**& argv, int& argi, int n) {
  if (n == 2) {
    // when we want a single argument, check to see if it was specified with
    // an '=', if so decrement the argument count.
    const std::string arg(argv[argi]);
    if (arg.find('=') != std::string::npos) {
      --n;
    }
  }
  for (int i = argi + n; i < argc; ++i)
    argv[i - n] = argv[i];
  argc -= n;
  DYNET_ASSERT(argc >= 0, "remove_args less than 0");
}

static std::string get_arg(int argi, char** argv) {
  const std::string arg(argv[argi]);
  auto pos = arg.find('=');
  if (pos != std::string::npos) {
    return arg.substr(pos+1);
  }
  return argv[argi + 1];
}

DynetParams extract_dynet_params(int& argc,
                                 char**& argv, bool shared_parameters) {
  DynetParams params;
  params.shared_parameters = shared_parameters;

  int argi = 1;

#if HAVE_CUDA
  params.gpu_mask = std::vector<int>(MAX_GPUS, 0);
#endif

  while (argi < argc) {
    string arg = argv[argi];

    // Memory
    if (startswith(arg, "--dynet-mem") || startswith(arg, "--dynet_mem")) {
      if (!has_arg(argi, argc, argv)) {
        throw std::invalid_argument("[dynet] --dynet-mem expects an argument (the memory, in megabytes, to reserve)");
      } else {
        params.mem_descriptor = get_arg(argi, argv);
        remove_args(argc, argv, argi, 2);
      }
    }

    // Weight decay
    else if (startswith(arg, "--dynet-weight-decay") ||
             startswith(arg, "--dynet_weight_decay")) {
      if (!has_arg(argi, argc, argv)) {
        throw std::invalid_argument("[dynet] --dynet-weight-decay requires an argument (the weight decay per update)");
      } else {
        string a2 = get_arg(argi, argv);
        istringstream d(a2); d >> params.weight_decay;
        remove_args(argc, argv, argi, 2);
      }
    }

    // Random seed
    else if (startswith(arg, "--dynet-seed") ||
             startswith(arg, "--dynet_seed")) {
      if (!has_arg(argi, argc, argv)) {
        throw std::invalid_argument("[dynet] --dynet-seed expects an argument (the random number seed)");
      } else {
        string a2 = get_arg(argi, argv);
        istringstream c(a2); c >> params.random_seed;
        remove_args(argc, argv, argi, 2);
      }
    }

    // Autobatching
    else if (startswith(arg, "--dynet-autobatch") ||
             startswith(arg, "--dynet_autobatch")) {
      if (!has_arg(argi, argc, argv)) {
        throw std::invalid_argument("[dynet] --dynet-autobatch expects an argument (0 for none 1 for on)");
      } else {
        string a2 = get_arg(argi, argv);
        istringstream c(a2); c >> params.autobatch;
        remove_args(argc, argv, argi, 2);
      }
    }

    // Profiling
    else if (startswith(arg, "--dynet-profiling") ||
             startswith(arg, "--dynet_profiling")) {
      if (!has_arg(argi, argc, argv)) {
        throw std::invalid_argument("[dynet] --dynet-profiling expects an argument (0 for none 1 for on)");
      } else {
        string a2 = get_arg(argi, argv);
        istringstream c(a2); c >> params.profiling;
        remove_args(argc, argv, argi, 2);
      }
    }

#if HAVE_CUDA
    else if (startswith(arg, "--dynet-gpus") ||
             startswith(arg, "--dynet_gpus")) {
      if (!has_arg(argi, argc, argv)) {
        throw std::invalid_argument("[dynet] --dynet-gpus expects an argument (number of GPUs to use)");
      } else {
        if (params.ngpus_requested)
          throw std::invalid_argument("Multiple instances of --dynet-gpus");
        params.ngpus_requested = true;
        string a2 = get_arg(argi, argv);
        istringstream c(a2); c >> params.requested_gpus;
        remove_args(argc, argv, argi, 2);
      }
    }
#endif

    // Devices
    else if (startswith(arg, "--dynet-devices") ||
             startswith(arg, "--dynet_devices")) {
      if (!has_arg(argi, argc, argv)) {
        throw std::invalid_argument("[dynet] --dynet-devices expects an argument (comma separated list of CPU and physical GPU ids to use)");
      } else {
        string devices_str = get_arg(argi, argv);
        if (params.ids_requested)
           throw std::invalid_argument("Multiple instances of --dynet-devices");
        params.ids_requested = true;
        auto devices_info_lst = str_split(devices_str, ',');
        for (auto & devices_info : devices_info_lst) {
          if (startswith(devices_info, "CPU:")) {
            throw std::invalid_argument("DyNet doesn't support specifying CPU id");
          } else if (startswith(devices_info, "CPU")) {
            if (params.cpu_requested)
              throw std::invalid_argument("Bad argument to --dynet-devices");
            params.cpu_requested = true;
          } else if (startswith(devices_info, "GPU:")) {
            int gpu_id = std::stoi(devices_info.substr(4, devices_info.size() - 4));
            if (gpu_id >= 256) // MAX_GPUS
              throw std::runtime_error("DyNet hard limit on maximum number of GPUs (MAX_GPUS) exceeded. If you need more, modify the code to raise this hard limit.");
            params.gpu_mask[gpu_id] ++;
            params.requested_gpus++;
            if (params.gpu_mask[gpu_id] != 1) {
              ostringstream oss; oss << "Bad argument to --dynet-devices: " << devices_info;
              throw std::invalid_argument(oss.str());
            }
          } else {
            throw std::invalid_argument("Bad argument to --dynet-devices");
          }
        }
        params.cpu_requested = true;
        remove_args(argc, argv, argi, 2);
      }
    }

    // Go to next argument
    else {
      argi++;
    }
  }

#if HAVE_CUDA
  // Check for conflict between the two ways of requesting GPUs
  if (params.ids_requested && params.ngpus_requested)
    throw std::invalid_argument("Use only --dynet_gpus or --dynet_gpu_ids, not both\n");
#endif

  return params;
}

void initialize(DynetParams& params) {
  if (default_device != nullptr) {
    cerr << "WARNING: Attempting to initialize dynet twice. Ignoring duplicate initialization." << endl;
    return;
  }

  DeviceManager* device_manager = get_device_manager();

  // initialize CUDA
  vector<Device*> gpudevices;
#if HAVE_CUDA
  if (!(params.cpu_requested && (params.requested_gpus == -1))) {
    cerr << "[dynet] initializing CUDA\n";
    gpudevices = initialize_gpu(params);
    for (auto gpu : gpudevices)
      device_manager->add(gpu);
  }
#endif

  // Set random seed
  if (params.random_seed == 0) {
    random_device rd;
    params.random_seed = rd();
  }
  cerr << "[dynet] random seed: " << params.random_seed << endl;
  reset_rng(params.random_seed);
  rndeng = new mt19937(params.random_seed);

  // Set weight decay rate
  if (params.weight_decay < 0 || params.weight_decay >= 1)
    throw std::invalid_argument("[dynet] weight decay parameter must be between 0 and 1 (probably very small like 1e-6)\n");
  default_weight_decay_lambda = params.weight_decay;

  // Set autobatch
  if(params.autobatch)
    cerr << "[dynet] using autobatching" << endl;
  autobatch_flag = params.autobatch;

  if(params.profiling)
    cerr << "[dynet] using profiling level " << params.profiling << endl;
  profiling_flag = params.profiling;

  // Allocate memory
  cerr << "[dynet] allocating memory: " << params.mem_descriptor << "MB\n";
  int default_index = 0;

  Device *d;
  if (gpudevices.size()) {
    d = new Device_CPU(device_manager->num_devices(), std::string("128"), params.shared_parameters);
  } else {
    d = new Device_CPU(device_manager->num_devices(), params.mem_descriptor, params.shared_parameters);
  }
  device_manager->add(d);
  default_device = device_manager->get(default_index);
#if HAVE_CUDA
  if (default_device->type == DeviceType::GPU) {
    auto default_gpu_device = static_cast<Device_GPU *>(default_device);
    CUDA_CHECK(cudaSetDevice(default_gpu_device->cuda_device_id));
  }
#endif

  // TODO these should be accessed through the relevant device and removed here
  kSCALAR_MINUSONE = default_device->kSCALAR_MINUSONE;
  kSCALAR_ONE = default_device->kSCALAR_ONE;
  kSCALAR_ZERO = default_device->kSCALAR_ZERO;
  cerr << "[dynet] memory allocation done.\n";

}

void initialize(int& argc, char**& argv, bool shared_parameters) {
  DynetParams params = extract_dynet_params(argc, argv, shared_parameters);
  initialize(params);
}

void cleanup() {
  delete rndeng;
  get_device_manager()->clear();
  default_device = nullptr;
}

void reset_rng(unsigned seed) {
  rndeng = new mt19937(seed);
#if HAVE_CUDA
  DeviceManager* device_manager = get_device_manager();
  for (unsigned device_id=0; device_id < device_manager->num_devices(); device_id++){
      Device* dev = device_manager->get(device_id);
      if (dev->type == DeviceType::GPU) {
        Device_GPU* dev_gpu = (Device_GPU*)dev;
        dev_gpu->reset_rng(seed);
      }
  }
#endif
}

} // namespace dynet
<commit_msg>Update init.cc<commit_after>#include "dynet/init.h"

#include "dynet/aligned-mem-pool.h"
#include "dynet/dynet.h"
#include "dynet/weight-decay.h"
#include "dynet/globals.h"
#include "dynet/str-util.h"
#include "dynet/devices.h"

#include <iostream>
#include <random>
#include <cmath>

#if HAVE_CUDA
#include "dynet/cuda.h"
#include <device_launch_parameters.h>
#endif

using namespace std;

namespace dynet {

DynetParams::DynetParams() : random_seed(0), mem_descriptor("512"), weight_decay(0), autobatch(0), profiling(0),
  shared_parameters(false), ngpus_requested(false), ids_requested(false), cpu_requested(false), requested_gpus(-1)
{
#if HAVE_CUDA
  gpu_mask = std::vector<int>(MAX_GPUS, 0);
#endif
}

DynetParams::~DynetParams()
{
}

static bool has_arg(int argi, int argc, char** argv) {
  const std::string arg(argv[argi]);
  auto pos = arg.find('=');
  if (pos == std::string::npos) {
    if ((argi + 1) < argc) {
      const std::string argn(argv[argi + 1]);
      if (argn.size() < 2 || !(argn[0] == '-' && argn[1] == '-'))
        return true;
    }
  } else {
    // check that there is actually a string present
    if ((pos + 1) < arg.size()) {
      return true;
    }
  }
  return false;
}

static void remove_args(int& argc, char**& argv, int& argi, int n) {
  if (n == 2) {
    // when we want a single argument, check to see if it was specified with
    // an '=', if so decrement the argument count.
    const std::string arg(argv[argi]);
    if (arg.find('=') != std::string::npos) {
      --n;
    }
  }
  for (int i = argi + n; i < argc; ++i)
    argv[i - n] = argv[i];
  argc -= n;
  DYNET_ASSERT(argc >= 0, "remove_args less than 0");
}

static std::string get_arg(int argi, char** argv) {
  const std::string arg(argv[argi]);
  auto pos = arg.find('=');
  if (pos != std::string::npos) {
    return arg.substr(pos+1);
  }
  return argv[argi + 1];
}

DynetParams extract_dynet_params(int& argc,
                                 char**& argv, bool shared_parameters) {
  DynetParams params;
  params.shared_parameters = shared_parameters;

  int argi = 1;

#if HAVE_CUDA
  params.gpu_mask = std::vector<int>(MAX_GPUS, 0);
#endif

  while (argi < argc) {
    string arg = argv[argi];

    // Memory
    if (startswith(arg, "--dynet-mem") || startswith(arg, "--dynet_mem")) {
      if (!has_arg(argi, argc, argv)) {
        throw std::invalid_argument("[dynet] --dynet-mem expects an argument (the memory, in megabytes, to reserve)");
      } else {
        params.mem_descriptor = get_arg(argi, argv);
        remove_args(argc, argv, argi, 2);
      }
    }

    // Weight decay
    else if (startswith(arg, "--dynet-weight-decay") ||
             startswith(arg, "--dynet_weight_decay")) {
      if (!has_arg(argi, argc, argv)) {
        throw std::invalid_argument("[dynet] --dynet-weight-decay requires an argument (the weight decay per update)");
      } else {
        string a2 = get_arg(argi, argv);
        istringstream d(a2); d >> params.weight_decay;
        remove_args(argc, argv, argi, 2);
      }
    }

    // Random seed
    else if (startswith(arg, "--dynet-seed") ||
             startswith(arg, "--dynet_seed")) {
      if (!has_arg(argi, argc, argv)) {
        throw std::invalid_argument("[dynet] --dynet-seed expects an argument (the random number seed)");
      } else {
        string a2 = get_arg(argi, argv);
        istringstream c(a2); c >> params.random_seed;
        remove_args(argc, argv, argi, 2);
      }
    }

    // Autobatching
    else if (startswith(arg, "--dynet-autobatch") ||
             startswith(arg, "--dynet_autobatch")) {
      if (!has_arg(argi, argc, argv)) {
        throw std::invalid_argument("[dynet] --dynet-autobatch expects an argument (0 for none 1 for on)");
      } else {
        string a2 = get_arg(argi, argv);
        istringstream c(a2); c >> params.autobatch;
        remove_args(argc, argv, argi, 2);
      }
    }

    // Profiling
    else if (startswith(arg, "--dynet-profiling") ||
             startswith(arg, "--dynet_profiling")) {
      if (!has_arg(argi, argc, argv)) {
        throw std::invalid_argument("[dynet] --dynet-profiling expects an argument (0 for none 1 for on)");
      } else {
        string a2 = get_arg(argi, argv);
        istringstream c(a2); c >> params.profiling;
        remove_args(argc, argv, argi, 2);
      }
    }

#if HAVE_CUDA
    else if (startswith(arg, "--dynet-gpus") ||
             startswith(arg, "--dynet_gpus")) {
      if (!has_arg(argi, argc, argv)) {
        throw std::invalid_argument("[dynet] --dynet-gpus expects an argument (number of GPUs to use)");
      } else {
        if (params.ngpus_requested)
          throw std::invalid_argument("Multiple instances of --dynet-gpus");
        params.ngpus_requested = true;
        string a2 = get_arg(argi, argv);
        istringstream c(a2); c >> params.requested_gpus;
        remove_args(argc, argv, argi, 2);
      }
    }
#endif

    // Devices
    else if (startswith(arg, "--dynet-devices") ||
             startswith(arg, "--dynet_devices")) {
      if (!has_arg(argi, argc, argv)) {
        throw std::invalid_argument("[dynet] --dynet-devices expects an argument (comma separated list of CPU and physical GPU ids to use)");
      } else {
        string devices_str = get_arg(argi, argv);
        if (params.ids_requested)
           throw std::invalid_argument("Multiple instances of --dynet-devices");
        params.ids_requested = true;
        auto devices_info_lst = str_split(devices_str, ',');
        for (auto & devices_info : devices_info_lst) {
          if (startswith(devices_info, "CPU:")) {
            throw std::invalid_argument("DyNet doesn't support specifying CPU id");
          } else if (startswith(devices_info, "CPU")) {
            if (params.cpu_requested)
              throw std::invalid_argument("Bad argument to --dynet-devices");
            params.cpu_requested = true;
          } else if (startswith(devices_info, "GPU:")) {
            int gpu_id = std::stoi(devices_info.substr(4, devices_info.size() - 4));
            if (gpu_id >= 256) // MAX_GPUS
              throw std::runtime_error("DyNet hard limit on maximum number of GPUs (MAX_GPUS) exceeded. If you need more, modify the code to raise this hard limit.");
            params.gpu_mask[gpu_id] ++;
            params.requested_gpus++;
            if (params.gpu_mask[gpu_id] != 1) {
              ostringstream oss; oss << "Bad argument to --dynet-devices: " << devices_info;
              throw std::invalid_argument(oss.str());
            }
          } else {
            throw std::invalid_argument("Bad argument to --dynet-devices");
          }
        }
        params.cpu_requested = true;
        remove_args(argc, argv, argi, 2);
      }
    }

    // Go to next argument
    else {
      argi++;
    }
  }

#if HAVE_CUDA
  // Check for conflict between the two ways of requesting GPUs
  if (params.ids_requested && params.ngpus_requested)
    throw std::invalid_argument("Use only --dynet_gpus or --dynet_devices, not both\n");
#endif

  return params;
}

void initialize(DynetParams& params) {
  if (default_device != nullptr) {
    cerr << "WARNING: Attempting to initialize dynet twice. Ignoring duplicate initialization." << endl;
    return;
  }

  DeviceManager* device_manager = get_device_manager();

  // initialize CUDA
  vector<Device*> gpudevices;
#if HAVE_CUDA
  if (!(params.cpu_requested && (params.requested_gpus == -1))) {
    cerr << "[dynet] initializing CUDA\n";
    gpudevices = initialize_gpu(params);
    for (auto gpu : gpudevices)
      device_manager->add(gpu);
  }
#endif

  // Set random seed
  if (params.random_seed == 0) {
    random_device rd;
    params.random_seed = rd();
  }
  cerr << "[dynet] random seed: " << params.random_seed << endl;
  reset_rng(params.random_seed);
  rndeng = new mt19937(params.random_seed);

  // Set weight decay rate
  if (params.weight_decay < 0 || params.weight_decay >= 1)
    throw std::invalid_argument("[dynet] weight decay parameter must be between 0 and 1 (probably very small like 1e-6)\n");
  default_weight_decay_lambda = params.weight_decay;

  // Set autobatch
  if(params.autobatch)
    cerr << "[dynet] using autobatching" << endl;
  autobatch_flag = params.autobatch;

  if(params.profiling)
    cerr << "[dynet] using profiling level " << params.profiling << endl;
  profiling_flag = params.profiling;

  // Allocate memory
  cerr << "[dynet] allocating memory: " << params.mem_descriptor << "MB\n";
  int default_index = 0;

  Device *d;
  if (gpudevices.size()) {
    d = new Device_CPU(device_manager->num_devices(), std::string("128"), params.shared_parameters);
  } else {
    d = new Device_CPU(device_manager->num_devices(), params.mem_descriptor, params.shared_parameters);
  }
  device_manager->add(d);
  default_device = device_manager->get(default_index);
#if HAVE_CUDA
  if (default_device->type == DeviceType::GPU) {
    auto default_gpu_device = static_cast<Device_GPU *>(default_device);
    CUDA_CHECK(cudaSetDevice(default_gpu_device->cuda_device_id));
  }
#endif

  // TODO these should be accessed through the relevant device and removed here
  kSCALAR_MINUSONE = default_device->kSCALAR_MINUSONE;
  kSCALAR_ONE = default_device->kSCALAR_ONE;
  kSCALAR_ZERO = default_device->kSCALAR_ZERO;
  cerr << "[dynet] memory allocation done.\n";

}

void initialize(int& argc, char**& argv, bool shared_parameters) {
  DynetParams params = extract_dynet_params(argc, argv, shared_parameters);
  initialize(params);
}

void cleanup() {
  delete rndeng;
  get_device_manager()->clear();
  default_device = nullptr;
}

void reset_rng(unsigned seed) {
  rndeng = new mt19937(seed);
#if HAVE_CUDA
  DeviceManager* device_manager = get_device_manager();
  for (unsigned device_id=0; device_id < device_manager->num_devices(); device_id++){
      Device* dev = device_manager->get(device_id);
      if (dev->type == DeviceType::GPU) {
        Device_GPU* dev_gpu = (Device_GPU*)dev;
        dev_gpu->reset_rng(seed);
      }
  }
#endif
}

} // namespace dynet
<|endoftext|>


<commit_before>#include "dynet/init.h"
#include "dynet/aligned-mem-pool.h"
#include "dynet/dynet.h"
#include "dynet/weight-decay.h"

#include <iostream>
#include <random>
#include <cmath>

#if HAVE_CUDA
#include "dynet/cuda.h"
#include <device_launch_parameters.h>
#endif

using namespace std;

namespace dynet {

static void remove_args(int& argc, char**& argv, int& argi, int n) {
  for (int i = argi + n; i < argc; ++i)
    argv[i - n] = argv[i];
  argc -= n;
  assert(argc >= 0);
}

DynetParams extract_dynet_params(int& argc, char**& argv, bool shared_parameters) {
  DynetParams params;
  params.shared_parameters = shared_parameters;

  int argi = 1;

#if HAVE_CUDA
  params.gpu_mask = std::vector<int>(MAX_GPUS, 0);
#endif

  while (argi < argc) {
    string arg = argv[argi];

    // Memory
    if (arg == "--dynet-mem" || arg == "--dynet_mem") {
      if ((argi + 1) > argc) {
        cerr << "[dynet] --dynet-mem expects an argument (the memory, in megabytes, to reserve)\n";
        abort();
      } else {
        params.mem_descriptor = argv[argi + 1];
        remove_args(argc, argv, argi, 2);
      }
    }

    // Weight decay
    else if (arg == "--dynet-weight-decay" || arg == "--dynet_weight_decay") {
      if ((argi + 1) > argc) {
        cerr << "[dynet] --dynet-weight-decay requires an argument (the weight decay per update)\n";
        abort();
      } else {
        string a2 = argv[argi + 1];
        istringstream d(a2); d >> params.weight_decay;
        remove_args(argc, argv, argi, 2);
      }
    }

    // Random seed
    else if (arg == "--dynet-seed" || arg == "--dynet_seed") {
      if ((argi + 1) > argc) {
        cerr << "[dynet] --dynet-seed expects an argument (the random number seed)\n";
        abort();
      } else {
        string a2 = argv[argi + 1];
        istringstream c(a2); c >> params.random_seed;
        remove_args(argc, argv, argi, 2);
      }
    }

#if HAVE_CUDA
    // Number of GPUs
    else if (arg == "--dynet_gpus" || arg == "--dynet-gpus") {
      if ((argi + 1) > argc) {
        cerr << "[dynet] --dynet-gpus expects an argument (number of GPUs to use)\n";
        abort();
      } else {
        if (params.ngpus_requested) {
          cerr << "Multiple instances of --dynet-gpus" << endl; abort();
        }
        params.ngpus_requested = true;
        string a2 = argv[argi + 1];
        istringstream c(a2); c >> params.requested_gpus;
        remove_args(argc, argv, argi, 2);
      }
    }

    // GPU ids
    else if (arg == "--dynet_gpu_ids" || arg == "--dynet-gpu-ids") {
      if ((argi + 1) > argc) {
        cerr << "[dynet] --dynet-gpu-ids expects an argument (comma separated list of physical GPU ids to use)\n";
        abort();
      } else {
        string a2 = argv[argi + 1];
        if (params.ids_requested) {
          cerr << "Multiple instances of --dynet-gpu-ids" << endl; abort();
        }
        params.ids_requested = true;
        if (a2.size() % 2 != 1) {
          cerr << "Bad argument to --dynet-gpu-ids: " << a2 << endl; abort();
        }
        for (unsigned i = 0; i < a2.size(); ++i) {
          if ((i % 2 == 0 && (a2[i] < '0' || a2[i] > '9')) ||
              (i % 2 == 1 && a2[i] != ',')) {
            cerr << "Bad argument to --dynet-gpu-ids: " << a2 << endl; abort();
          }
          if (i % 2 == 0) {
            int gpu_id = a2[i] - '0';
            if (gpu_id >= MAX_GPUS) { cerr << "Raise MAX_GPUS\n"; abort(); }
            params.gpu_mask[gpu_id]++;
            params.requested_gpus++;
            if (params.gpu_mask[gpu_id] != 1) {
              cerr << "Bad argument to --dynet-gpu-ids: " << a2 << endl; abort();
            }
          }
        }
        remove_args(argc, argv, argi, 2);
      }
    }
#endif

    // Go to next argument
    else {
      argi++;
    }

  }

#if HAVE_CUDA
  // Check for conflict between the two ways of requesting GPUs
  if (params.ids_requested && params.ngpus_requested) {
    cerr << "Use only --dynet_gpus or --dynet_gpu_ids, not both\n";
    abort();
  }
#endif

  return params;
}

void initialize(DynetParams params) {
  if (default_device != nullptr) {
    cerr << "WARNING: Attempting to initialize dynet twice. Ignoring duplicate initialization." << endl;
    return;
  }

  // initialize CUDA
  vector<Device*> gpudevices;
#if HAVE_CUDA
  cerr << "[dynet] initializing CUDA\n";
  gpudevices = initialize_gpu(params);
#endif

  // Set random seed
  if (params.random_seed == 0) {
    random_device rd;
    params.random_seed = rd();
  }
  cerr << "[dynet] random seed: " << params.random_seed << endl;
  rndeng = new mt19937(params.random_seed);

  // Set weight decay rate
  if (params.weight_decay < 0 || params.weight_decay >= 1) {
    cerr << "[dynet] weight decay parameter must be between 0 and 1 (probably very small like 1e-6)\n";
    abort();
  }
  weight_decay_lambda = params.weight_decay;

  // Allocate memory
  cerr << "[dynet] allocating memory: " << params.mem_descriptor << "MB\n";
  devices.push_back(new Device_CPU(devices.size(), params.mem_descriptor, params.shared_parameters));
  int default_index = 0;
  if (gpudevices.size() > 0) {
    for (auto gpu : gpudevices)
      devices.push_back(gpu);
    default_index++;
  }
  default_device = devices[default_index];

  // TODO these should be accessed through the relevant device and removed here
  kSCALAR_MINUSONE = default_device->kSCALAR_MINUSONE;
  kSCALAR_ONE = default_device->kSCALAR_ONE;
  kSCALAR_ZERO = default_device->kSCALAR_ZERO;
  cerr << "[dynet] memory allocation done.\n";

}

void initialize(int& argc, char**& argv, bool shared_parameters) {
  DynetParams params = extract_dynet_params(argc, argv, shared_parameters);
  initialize(params);
}

void cleanup() {
  delete rndeng;
  // TODO: Devices cannot be deleted at the moment
  // for(Device* device : devices) delete device;
  devices.clear();
  default_device = nullptr;
}

} // namespace dynet

<commit_msg>Removed unnecessary CPU mem alloc when using GPU<commit_after>#include "dynet/init.h"
#include "dynet/aligned-mem-pool.h"
#include "dynet/dynet.h"
#include "dynet/weight-decay.h"

#include <iostream>
#include <random>
#include <cmath>

#if HAVE_CUDA
#include "dynet/cuda.h"
#include <device_launch_parameters.h>
#endif

using namespace std;

namespace dynet {

static void remove_args(int& argc, char**& argv, int& argi, int n) {
  for (int i = argi + n; i < argc; ++i)
    argv[i - n] = argv[i];
  argc -= n;
  assert(argc >= 0);
}

DynetParams extract_dynet_params(int& argc, char**& argv, bool shared_parameters) {
  DynetParams params;
  params.shared_parameters = shared_parameters;

  int argi = 1;

#if HAVE_CUDA
  params.gpu_mask = std::vector<int>(MAX_GPUS, 0);
#endif

  while (argi < argc) {
    string arg = argv[argi];

    // Memory
    if (arg == "--dynet-mem" || arg == "--dynet_mem") {
      if ((argi + 1) > argc) {
        cerr << "[dynet] --dynet-mem expects an argument (the memory, in megabytes, to reserve)\n";
        abort();
      } else {
        params.mem_descriptor = argv[argi + 1];
        remove_args(argc, argv, argi, 2);
      }
    }

    // Weight decay
    else if (arg == "--dynet-weight-decay" || arg == "--dynet_weight_decay") {
      if ((argi + 1) > argc) {
        cerr << "[dynet] --dynet-weight-decay requires an argument (the weight decay per update)\n";
        abort();
      } else {
        string a2 = argv[argi + 1];
        istringstream d(a2); d >> params.weight_decay;
        remove_args(argc, argv, argi, 2);
      }
    }

    // Random seed
    else if (arg == "--dynet-seed" || arg == "--dynet_seed") {
      if ((argi + 1) > argc) {
        cerr << "[dynet] --dynet-seed expects an argument (the random number seed)\n";
        abort();
      } else {
        string a2 = argv[argi + 1];
        istringstream c(a2); c >> params.random_seed;
        remove_args(argc, argv, argi, 2);
      }
    }

#if HAVE_CUDA
    // Number of GPUs
    else if (arg == "--dynet_gpus" || arg == "--dynet-gpus") {
      if ((argi + 1) > argc) {
        cerr << "[dynet] --dynet-gpus expects an argument (number of GPUs to use)\n";
        abort();
      } else {
        if (params.ngpus_requested) {
          cerr << "Multiple instances of --dynet-gpus" << endl; abort();
        }
        params.ngpus_requested = true;
        string a2 = argv[argi + 1];
        istringstream c(a2); c >> params.requested_gpus;
        remove_args(argc, argv, argi, 2);
      }
    }

    // GPU ids
    else if (arg == "--dynet_gpu_ids" || arg == "--dynet-gpu-ids") {
      if ((argi + 1) > argc) {
        cerr << "[dynet] --dynet-gpu-ids expects an argument (comma separated list of physical GPU ids to use)\n";
        abort();
      } else {
        string a2 = argv[argi + 1];
        if (params.ids_requested) {
          cerr << "Multiple instances of --dynet-gpu-ids" << endl; abort();
        }
        params.ids_requested = true;
        if (a2.size() % 2 != 1) {
          cerr << "Bad argument to --dynet-gpu-ids: " << a2 << endl; abort();
        }
        for (unsigned i = 0; i < a2.size(); ++i) {
          if ((i % 2 == 0 && (a2[i] < '0' || a2[i] > '9')) ||
              (i % 2 == 1 && a2[i] != ',')) {
            cerr << "Bad argument to --dynet-gpu-ids: " << a2 << endl; abort();
          }
          if (i % 2 == 0) {
            int gpu_id = a2[i] - '0';
            if (gpu_id >= MAX_GPUS) { cerr << "Raise MAX_GPUS\n"; abort(); }
            params.gpu_mask[gpu_id]++;
            params.requested_gpus++;
            if (params.gpu_mask[gpu_id] != 1) {
              cerr << "Bad argument to --dynet-gpu-ids: " << a2 << endl; abort();
            }
          }
        }
        remove_args(argc, argv, argi, 2);
      }
    }
#endif

    // Go to next argument
    else {
      argi++;
    }

  }

#if HAVE_CUDA
  // Check for conflict between the two ways of requesting GPUs
  if (params.ids_requested && params.ngpus_requested) {
    cerr << "Use only --dynet_gpus or --dynet_gpu_ids, not both\n";
    abort();
  }
#endif

  return params;
}

void initialize(DynetParams params) {
  if (default_device != nullptr) {
    cerr << "WARNING: Attempting to initialize dynet twice. Ignoring duplicate initialization." << endl;
    return;
  }

  // initialize CUDA
  vector<Device*> gpudevices;
#if HAVE_CUDA
  cerr << "[dynet] initializing CUDA\n";
  gpudevices = initialize_gpu(params);
#endif

  // Set random seed
  if (params.random_seed == 0) {
    random_device rd;
    params.random_seed = rd();
  }
  cerr << "[dynet] random seed: " << params.random_seed << endl;
  rndeng = new mt19937(params.random_seed);

  // Set weight decay rate
  if (params.weight_decay < 0 || params.weight_decay >= 1) {
    cerr << "[dynet] weight decay parameter must be between 0 and 1 (probably very small like 1e-6)\n";
    abort();
  }
  weight_decay_lambda = params.weight_decay;

  // Allocate memory
  cerr << "[dynet] allocating memory: " << params.mem_descriptor << "MB\n";
  // TODO: Once multi-device support is added, we will potentially allocate both CPU
  //       and GPU, not either-or
  int default_index = 0;
  if (gpudevices.size() > 0) {
    for (auto gpu : gpudevices)
      devices.push_back(gpu);
  } else {
    devices.push_back(new Device_CPU(devices.size(), params.mem_descriptor, params.shared_parameters));
  }
  default_device = devices[default_index];

  // TODO these should be accessed through the relevant device and removed here
  kSCALAR_MINUSONE = default_device->kSCALAR_MINUSONE;
  kSCALAR_ONE = default_device->kSCALAR_ONE;
  kSCALAR_ZERO = default_device->kSCALAR_ZERO;
  cerr << "[dynet] memory allocation done.\n";

}

void initialize(int& argc, char**& argv, bool shared_parameters) {
  DynetParams params = extract_dynet_params(argc, argv, shared_parameters);
  initialize(params);
}

void cleanup() {
  delete rndeng;
  // TODO: Devices cannot be deleted at the moment
  // for(Device* device : devices) delete device;
  devices.clear();
  default_device = nullptr;
}

} // namespace dynet

<|endoftext|>