<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "getopt.h"
#include "bitio.h"
#include "h264.h"

#ifdef __RENESAS_VERSION__

extern "C" {

#define O_RDONLY 1
#define O_WRONLY 2
#define MAX_FILESIZE 8 * 1024 * 1024
#define MAX_MD5SIZE 128 * 1024
char InputFile[MAX_FILESIZE];
char OutputFile[MAX_MD5SIZE];

void abort() {while (1);}
static int infilepos;
static int outfilepos;

static void exit(int err) {
	while (err);
}

int fseek(FILE *fp, long offset, int whence) {
	return 0;
}
int open(char *name, int mode, int flg) {
	if (mode & O_RDONLY) {
		infilepos = 0;
	} else if (mode & O_WRONLY) {
		infilepos = 0;
	}
	return 4;
}
int close(int fineno) {return 0;}
int read(int fileno, char *buf, unsigned int count) {
	if (sizeof(InputFile) < infilepos + count) {
		count = sizeof(InputFile) - infilepos;
		if ((signed)count <= 0) {
			return 0;
		}
	}
	memcpy(buf, InputFile + infilepos, count);
	infilepos += count;
	return count;
}
int lseek() {return 0;}
int write(int fileno, char *buf, unsigned int count) {return count;}
char *getenv(const char *name) {return 0;}

}

#endif

static int alloc_frames(h264d_frame **mem, int width, int height, int num_mem)
{
	h264d_frame *m;
	int luma_len = ((width + 15) & ~15) * ((height + 15) & ~15) + 15;

	if (luma_len <= 0) {
		return -1;
	}
	*mem = m = new h264d_frame[num_mem];
	for (int i = 0; i < num_mem; ++i) {
		m[i].luma_len = luma_len;
		m[i].luma = new uint8_t[luma_len];
		m[i].chroma = new uint8_t[luma_len >> 1];
	}
	return 0;
}

static void free_frames(h264d_frame *mem, int num_mem)
{
	for (int i = 0; i < num_mem; ++i) {
		delete[] mem[i].luma;
		delete[] mem[i].chroma;
	}
}

struct input_data_t {
	uint8_t *data_;
	size_t len_;
	size_t pos_;
	void *var_;
	FILE *fo_;
	input_data_t(int argc, char *argv[], void *v) : pos_(0), var_(v), fo_(0) {
		FILE *fi;
		int opt;
		while ((opt = getopt(argc, argv, "o:O:")) != -1) {
			switch (opt) {
			case 'o':
				fo_ = fopen(optarg, "wb");
				break;
			default:
				BlameUser();
				/* NOTREACHED */
			}
		}
		if ((argc <= optind) ||	!(fi = fopen(argv[optind], "rb"))) {
			BlameUser();
			/* NOTREACHED */
		}
		fseek(fi, 0, SEEK_END);
		len_ = ftell(fi);
		fseek(fi, 0, SEEK_SET);
		data_ = new uint8_t[len_];
		fread(data_, 1, len_, fi);
		fclose(fi);
	}
	~input_data_t() {
		delete[] data_;
		if (fo_) {
			fclose(fo_);
		}
	}
	size_t write(const void *data, size_t size) {
		if (fo_) {
			fwrite(data, 1, size, fo_);
			return size;
		}
		return 0;
	}
	void BlameUser() {
		fprintf(stderr,
			"Usage:\n"
			"\th264dec [-o <outfile>] <infile>\n");
		exit(-1);
	}
};

static int reread_file(void *var)
{
	input_data_t *d = (input_data_t *)var;
	if (d->pos_ < d->len_) {
		dec_bits_set_data(((h264d_context *)d->var_)->stream, d->data_ + d->pos_, d->len_);
		d->pos_ += d->len_;
		return 0;
	} else {
		return -1;
	}
}

int main(int argc, char *argv[])
{
	h264d_context *h2d;
	h264d_frame *mem;
	int err;

	h2d = new h264d_context;
	err = h264d_init(h2d);
	if (err) {
		return err;
	}
	input_data_t data(argc, argv, (void *)h2d);
	if (data.len_ <= 0) {
		return -1;
	}
	err = h264d_read_header(h2d, data.data_, data.len_);
	data.pos_ = data.len_;
	if (err) {
		return err;
	}
	h264d_info_t info;
	h264d_get_info(h2d, &info);
	fprintf(stderr,
		"length: %ld\n"
		"width x height x num: %d x %d x %d\n",
		data.len_, info.src_width, info.src_height, info.frame_num);
	info.frame_num = info.frame_num < 3 ? 3 : info.frame_num;
	alloc_frames(&mem, info.src_width, info.src_height, info.frame_num);
	uint8_t *second_frame = new uint8_t[info.additional_size];
	err = h264d_set_frames(h2d, info.frame_num, mem, second_frame);
	if (err) {
		return err;
	}
	jmp_buf jmp;
	dec_bits_set_callback(h2d->stream, reread_file, &data, &jmp);
	for (int i = 0; i < 100000; ++i) {
		uint8_t *luma, *chroma;
		int luma_size;

		err = h264d_decode_picture(h2d);
		if (err == -1) {
			break;
		}
		h246d_get_decoded_frame(h2d, &luma, &chroma);
		luma_size = info.src_height * info.src_width;
		data.write(luma, luma_size);
		data.write(chroma, luma_size >> 1);
		if (err < 0) {
			break;
		}
	}
	delete[] second_frame;
	free_frames(mem, info.frame_num);
	delete[] mem;
	delete h2d;
	return err;
}

<commit_msg>Now prints size of context.<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "getopt.h"
#include "bitio.h"
#include "h264.h"

#ifdef __RENESAS_VERSION__

extern "C" {

#define O_RDONLY 1
#define O_WRONLY 2
#define MAX_FILESIZE 8 * 1024 * 1024
#define MAX_MD5SIZE 128 * 1024
char InputFile[MAX_FILESIZE];
char OutputFile[MAX_MD5SIZE];

void abort() {while (1);}
static int infilepos;
static int outfilepos;

static void exit(int err) {
	while (err);
}

int fseek(FILE *fp, long offset, int whence) {
	return 0;
}
int open(char *name, int mode, int flg) {
	if (mode & O_RDONLY) {
		infilepos = 0;
	} else if (mode & O_WRONLY) {
		infilepos = 0;
	}
	return 4;
}
int close(int fineno) {return 0;}
int read(int fileno, char *buf, unsigned int count) {
	if (sizeof(InputFile) < infilepos + count) {
		count = sizeof(InputFile) - infilepos;
		if ((signed)count <= 0) {
			return 0;
		}
	}
	memcpy(buf, InputFile + infilepos, count);
	infilepos += count;
	return count;
}
int lseek() {return 0;}
int write(int fileno, char *buf, unsigned int count) {return count;}
char *getenv(const char *name) {return 0;}

}

#endif

static int alloc_frames(h264d_frame **mem, int width, int height, int num_mem)
{
	h264d_frame *m;
	int luma_len = ((width + 15) & ~15) * ((height + 15) & ~15) + 15;

	if (luma_len <= 0) {
		return -1;
	}
	*mem = m = new h264d_frame[num_mem];
	for (int i = 0; i < num_mem; ++i) {
		m[i].luma_len = luma_len;
		m[i].luma = new uint8_t[luma_len];
		m[i].chroma = new uint8_t[luma_len >> 1];
	}
	return 0;
}

static void free_frames(h264d_frame *mem, int num_mem)
{
	for (int i = 0; i < num_mem; ++i) {
		delete[] mem[i].luma;
		delete[] mem[i].chroma;
	}
}

struct input_data_t {
	uint8_t *data_;
	size_t len_;
	size_t pos_;
	void *var_;
	FILE *fo_;
	input_data_t(int argc, char *argv[], void *v) : pos_(0), var_(v), fo_(0) {
		FILE *fi;
		int opt;
		while ((opt = getopt(argc, argv, "o:O:")) != -1) {
			switch (opt) {
			case 'o':
				fo_ = fopen(optarg, "wb");
				break;
			default:
				BlameUser();
				/* NOTREACHED */
			}
		}
		if ((argc <= optind) ||	!(fi = fopen(argv[optind], "rb"))) {
			BlameUser();
			/* NOTREACHED */
		}
		fseek(fi, 0, SEEK_END);
		len_ = ftell(fi);
		fseek(fi, 0, SEEK_SET);
		data_ = new uint8_t[len_];
		fread(data_, 1, len_, fi);
		fclose(fi);
	}
	~input_data_t() {
		delete[] data_;
		if (fo_) {
			fclose(fo_);
		}
	}
	size_t write(const void *data, size_t size) {
		if (fo_) {
			fwrite(data, 1, size, fo_);
			return size;
		}
		return 0;
	}
	void BlameUser() {
		fprintf(stderr,
			"Usage:\n"
			"\th264dec [-o <outfile>] <infile>\n");
		exit(-1);
	}
};

static int reread_file(void *var)
{
	input_data_t *d = (input_data_t *)var;
	if (d->pos_ < d->len_) {
		dec_bits_set_data(((h264d_context *)d->var_)->stream, d->data_ + d->pos_, d->len_);
		d->pos_ += d->len_;
		return 0;
	} else {
		return -1;
	}
}

int main(int argc, char *argv[])
{
	h264d_context *h2d;
	h264d_frame *mem;
	int err;

	h2d = new h264d_context;
	err = h264d_init(h2d);
	if (err) {
		return err;
	}
	input_data_t data(argc, argv, (void *)h2d);
	if (data.len_ <= 0) {
		return -1;
	}
	err = h264d_read_header(h2d, data.data_, data.len_);
	data.pos_ = data.len_;
	if (err) {
		return err;
	}
	h264d_info_t info;
	h264d_get_info(h2d, &info);
	fprintf(stderr,
		"length: %ld\n"
		"width x height x num: %d x %d x %d\n"
		"Context Size: %ld\n",
		data.len_, info.src_width, info.src_height, info.frame_num, sizeof(h264d_context));
	info.frame_num = info.frame_num < 3 ? 3 : info.frame_num;
	alloc_frames(&mem, info.src_width, info.src_height, info.frame_num);
	uint8_t *second_frame = new uint8_t[info.additional_size];
	err = h264d_set_frames(h2d, info.frame_num, mem, second_frame);
	if (err) {
		return err;
	}
	jmp_buf jmp;
	dec_bits_set_callback(h2d->stream, reread_file, &data, &jmp);
	for (int i = 0; i < 100000; ++i) {
		uint8_t *luma, *chroma;
		int luma_size;

		err = h264d_decode_picture(h2d);
		if (err == -1) {
			break;
		}
		h246d_get_decoded_frame(h2d, &luma, &chroma);
		luma_size = info.src_height * info.src_width;
		data.write(luma, luma_size);
		data.write(chroma, luma_size >> 1);
		if (err < 0) {
			break;
		}
	}
	delete[] second_frame;
	free_frames(mem, info.frame_num);
	delete[] mem;
	delete h2d;
	return err;
}

<|endoftext|>


<commit_before>#include "common/common.h"
#include "common/generation.h"
#include "common/parser.h"
#include "common/input_output.h"
ChVector<> lpos(0, 0, 0);
ChQuaternion<> quat(1, 0, 0, 0);

//all dimensions are in millimeters, milligrams
real container_width = 5;     //width of area with particles
real container_length = 25;     //length of area that roller will go over		1194mm maximum
real container_thickness = .25;     //thickness of container walls
real container_height = 2;     //height of the outer walls
real container_friction = 0;
real floor_friction = .2;
real spacer_width = 1;
real spacer_height = 1;

real roller_overlap = 1;     //amount that roller goes over the container area
real roller_length = 2.5 - .25;     //length of the roller
real roller_radius = 76.2 / 2.0;     //radius of roller
real roller_omega = 0;
real roller_velocity = -127;
real roller_mass = 1;
real roller_friction = .1;
real roller_cohesion = 0;
real particle_radius = .058 / 2.0;
real particle_std_dev = .015 / 2.0;
real particle_mass = .05;
real particle_density = 0.93;
real particle_layer_thickness = particle_radius * 12;
real particle_friction = .52;
real rolling_friction = .1;
real spinning_friction = .1;
real gravity = -9810;     //acceleration due to gravity
real timestep = .00001;     //step size
real time_to_run = 1;     //length of simulation
real current_time = 0;

int num_steps = time_to_run / timestep;
int max_iteration = 20;
int tolerance = 0;

string data_folder = "data/sls";
ChSharedBodyPtr ROLLER;
real ang = 0;

template<class T>
void RunTimeStep(T* mSys, const int frame) {
	ChVector<> roller_pos = ROLLER->GetPos();

	ROLLER->SetPos(ChVector<>(0, roller_radius + particle_layer_thickness + container_thickness, roller_pos.z + roller_velocity * timestep));
	ROLLER->SetPos_dt(ChVector<>(0, 0, roller_velocity));
	roller_omega = roller_velocity / roller_radius;
	ang += roller_omega * timestep;
	if (ang >= 2 * CH_C_PI) {
		ang = 0;
	}

	Quaternion q1;
	q1.Q_from_AngY(ang);
	Quaternion q2;
	q1 = Q_from_AngX(-ang);

	ChQuaternion<> roller_quat;
	roller_quat.Q_from_AngAxis(PI / 2.0, ChVector<>(0, 0, 1));

	ROLLER->SetRot(q1 % roller_quat);
	ROLLER->SetWvel_loc(Vector(0, roller_omega, 0));

	cout << ROLLER->GetPos().x << " " << ROLLER->GetPos().y << " " << ROLLER->GetPos().z << endl;
	;

}
int main(int argc, char* argv[]) {
	bool visualize = true;
	int config = 0;
	bool full_mix = true;
	if (argc > 1) {
		visualize = atoi(argv[1]);
		particle_friction = atof(argv[2]);
		rolling_friction = atof(argv[3]);
		spinning_friction = atof(argv[4]);
		roller_velocity = -atof(argv[5]);
		particle_layer_thickness = atof(argv[6]);
		full_mix = atoi(argv[7]);
		data_folder = argv[8];
	}
	//cout << "Mass, Radius, Friction_Sphere, Friction_Plate, Data Folder, create_particle_plate all_three_kinds, particle configuration" << endl;
	//=========================================================================================================
	ChSystemParallelDVI * system_gpu = new ChSystemParallelDVI;
	system_gpu->SetIntegrationType(ChSystem::INT_ANITESCU);
	//=========================================================================================================
	//system_gpu->SetMaxiter(max_iteration);

	//system_gpu->SetIterLCPmaxItersSpeed(max_iteration);
	//((ChLcpSolverParallelDVI *) (system_gpu->GetLcpSolverSpeed()))->SetMaxIteration(max_iter);
	((ChLcpSolverParallelDVI *) (system_gpu->GetLcpSolverSpeed()))->SetMaxIterationNormal(max_iteration * 2);
	((ChLcpSolverParallelDVI *) (system_gpu->GetLcpSolverSpeed()))->SetMaxIterationSliding(max_iteration);
	((ChLcpSolverParallelDVI *) (system_gpu->GetLcpSolverSpeed()))->SetMaxIterationSpinning(max_iteration);
	system_gpu->SetTol(0);
	system_gpu->SetTolSpeeds(0);
	((ChLcpSolverParallelDVI *) (system_gpu->GetLcpSolverSpeed()))->SetTolerance(0);
	((ChLcpSolverParallelDVI *) (system_gpu->GetLcpSolverSpeed()))->SetCompliance(0);
	((ChLcpSolverParallelDVI *) (system_gpu->GetLcpSolverSpeed()))->SetContactRecoverySpeed(300);
	((ChLcpSolverParallelDVI *) (system_gpu->GetLcpSolverSpeed()))->SetSolverType(APGDRS);
	((ChCollisionSystemParallel *) (system_gpu->GetCollisionSystem()))->SetCollisionEnvelope(particle_radius * .05);
	((ChCollisionSystemParallel *) (system_gpu->GetCollisionSystem()))->setBinsPerAxis(I3(40, 200, 100));
	((ChCollisionSystemParallel *) (system_gpu->GetCollisionSystem()))->setBodyPerBin(100, 50);
	((ChSystemParallelDVI*) system_gpu)->DoThreadTuning(false);
	//((ChSystemParallelDVI*) system_gpu)->SetMinThreads(32);
	system_gpu->Set_G_acc(ChVector<>(0, gravity, 0));
	system_gpu->SetStep(timestep);

	//=========================================================================================================
	((ChSystemParallel*) system_gpu)->SetAABB(R3(-6, -3, -30), R3(6, 6, 30));

	ChSharedBodyPtr PLATE = ChSharedBodyPtr(new ChBody(new ChCollisionModelParallel));

	ChSharedPtr<ChMaterialSurface> material_plate;
	material_plate = ChSharedPtr<ChMaterialSurface>(new ChMaterialSurface);
	material_plate->SetFriction(0);

	InitObject(PLATE, 100000, ChVector<>(0, 0, 0), quat, material_plate, true, true, -20, -20);

	ChSharedPtr<ChMaterialSurface> material;
	material = ChSharedPtr<ChMaterialSurface>(new ChMaterialSurface);
	material->SetFriction(container_friction);

	AddCollisionGeometry(PLATE, BOX, Vector(container_thickness, container_height, container_length), Vector(-container_width + container_thickness, container_height, 0), quat);
	AddCollisionGeometry(PLATE, BOX, Vector(container_thickness, container_height, container_length), Vector(container_width - container_thickness, container_height, 0), quat);
	AddCollisionGeometry(PLATE, BOX, Vector(container_width, container_height, container_thickness), Vector(0, container_height, -container_length + container_thickness), quat);
	AddCollisionGeometry(PLATE, BOX, Vector(container_width, container_height, container_thickness), Vector(0, container_height, container_length - container_thickness), quat);
	AddCollisionGeometry(PLATE, BOX, Vector(container_width, container_thickness, container_length), Vector(0, container_height*2,0), quat);
	FinalizeObject(PLATE, (ChSystemParallel *) system_gpu);

	ChSharedPtr<ChMaterialSurface> material_bottom;
	material_bottom = ChSharedPtr<ChMaterialSurface>(new ChMaterialSurface);
	material_bottom->SetFriction(floor_friction);

	ChSharedBodyPtr BOTTOM = ChSharedBodyPtr(new ChBody(new ChCollisionModelParallel));
	InitObject(BOTTOM, 100000, ChVector<>(0, 0, 0), quat, material_bottom, true, true, -20, -20);
	AddCollisionGeometry(BOTTOM, BOX, ChVector<>(container_width, container_thickness, container_length), lpos, quat);

	FinalizeObject(BOTTOM, (ChSystemParallel *) system_gpu);

	ROLLER = ChSharedBodyPtr(new ChBody(new ChCollisionModelParallel));
	ChQuaternion<> roller_quat;
	roller_quat.Q_from_AngAxis(PI / 2.0, ChVector<>(0, 0, 1));

	ChSharedPtr<ChMaterialSurface> material_roller;
	material_roller = ChSharedPtr<ChMaterialSurface>(new ChMaterialSurface);
	material_roller->SetFriction(roller_friction);

	InitObject(ROLLER, 1000, ChVector<>(0, roller_radius + particle_layer_thickness + container_thickness, container_length + roller_radius / 3.0), roller_quat, material_roller,
			true, false, -20, -20);
	AddCollisionGeometry(ROLLER, CYLINDER, ChVector<>(roller_radius, roller_length * 2, roller_radius), lpos, quat);
	FinalizeObject(ROLLER, (ChSystemParallel *) system_gpu);
	//68
	int3 num_per_dir = I3(1, 1, 1);
	//num_per_dir = I3(90, 16, 1);

	num_per_dir = I3(90, 17*particle_layer_thickness/.2032, 490);
	//num_per_dir = I3(90, 1, 490);
	ParticleGenerator < ChSystemParallelDVI > layer_gen(system_gpu);
	layer_gen.SetDensity(particle_density);
	layer_gen.SetRadius(R3(particle_radius));
	layer_gen.SetNormalDistribution(particle_radius, particle_std_dev);
	layer_gen.material->SetFriction(particle_friction);
	layer_gen.material->SetRollingFriction(rolling_friction);
	layer_gen.material->SetSpinningFriction(spinning_friction);

	if (full_mix) {
		layer_gen.AddMixtureType(MIX_SPHERE);
		layer_gen.AddMixtureType(MIX_TYPE1);
		layer_gen.AddMixtureType(MIX_TYPE2);
		layer_gen.AddMixtureType(MIX_TYPE3);
		layer_gen.AddMixtureType(MIX_TYPE4);
		layer_gen.AddMixtureType(MIX_ELLIPSOID);
		layer_gen.AddMixtureType(MIX_DOUBLESPHERE);
	}else{
		layer_gen.AddMixtureType(MIX_SPHERE);
	}

	//layer_gen.addPerturbedVolume(R3(0, 1.2, 0), SPHERE, num_per_dir, R3(.1, .1, .1), R3(0));

	layer_gen.addPerturbedVolumeMixture(R3(0, 1.3, 0), num_per_dir, R3(.1, .1, .1), R3(0));
	//num_per_dir = I3(90, 15, 100);
	//num_per_dir = I3(90, 15, 50);
	//num_per_dir = I3(1, 15, 100);
	//num_per_dir = I3(90, 30, 50);
	//layer_gen.addPerturbedVolumeMixture(R3(0, 3.2, 15), num_per_dir, R3(.1, .1, .1), R3(0));

	for(int i=0; i<system_gpu->Get_bodylist()->size(); i++){
		system_gpu->Get_bodylist()->at(i)->SetMaxSpeed(25);
	}
	//=========================================================================================================
	//////Rendering specific stuff:
	if (visualize) {
		ChOpenGLManager * window_manager = new ChOpenGLManager();
		ChOpenGL openGLView(window_manager, system_gpu, 800, 600, 0, 0, "Test_Solvers");
		openGLView.render_camera->camera_position = glm::vec3(-50, 0, -50);
		openGLView.render_camera->camera_look_at = glm::vec3(0, 0, 0);
		openGLView.SetCustomCallback(RunTimeStep);
		openGLView.StartSpinning(window_manager);
		window_manager->CallGlutMainLoop();
	}
	//=========================================================================================================
	stringstream ss_m;
	ss_m << data_folder << "/" << "timing.txt";
	string timing_file_name = ss_m.str();
	ofstream ofile(timing_file_name.c_str());
	ofile.close();
	int file = 0;
	for (int i = 0; i < num_steps; i++) {
		cout << "step " << i;
		cout << " Residual: " << ((ChLcpSolverParallel *) (system_gpu->GetLcpSolverSpeed()))->GetResidual();
		cout << " ITER: " << ((ChLcpSolverParallel *) (system_gpu->GetLcpSolverSpeed()))->GetTotalIterations();
		cout << " OUTPUT STEP: Time= " << current_time << " bodies= " << system_gpu->GetNbodies() << " contacts= " << system_gpu->GetNcontacts() << " step time="
				<< system_gpu->GetTimerStep() << " lcp time=" << system_gpu->GetTimerLcp() << " CDbroad time=" << system_gpu->GetTimerCollisionBroad() << " CDnarrow time="
				<< system_gpu->GetTimerCollisionNarrow() << " Iterations=" << ((ChLcpSolverParallel*) (system_gpu->GetLcpSolverSpeed()))->GetTotalIterations() << " "
				<< ROLLER->GetPos().z << "\n";
		//TimingFile(system_gpu, timing_file_name, current_time);
		system_gpu->DoStepDynamics(timestep);
		RunTimeStep(system_gpu, i);
		int save_every = 1.0 / timestep / 6000.0;     //save data every n steps
		if (i % save_every == 0) {
			stringstream ss;
			cout << "Frame: " << file << endl;
			ss << data_folder << "/" << file << ".txt";
			DumpAllObjectsWithGeometryPovray(system_gpu, ss.str());
			//output.ExportData(ss.str());
			file++;
		}
		if (ROLLER->GetPos().z < -15) {
			break;
		}
		current_time += timestep;
	}
	stringstream ss;
	return 0;
}

<commit_msg>store data in dev/shm and then move it to correct spot async<commit_after>#include "common/common.h"
#include "common/generation.h"
#include "common/parser.h"
#include "common/input_output.h"
ChVector<> lpos(0, 0, 0);
ChQuaternion<> quat(1, 0, 0, 0);

//all dimensions are in millimeters, milligrams
real container_width = 5;     //width of area with particles
real container_length = 25;     //length of area that roller will go over		1194mm maximum
real container_thickness = .25;     //thickness of container walls
real container_height = 2;     //height of the outer walls
real container_friction = 0;
real floor_friction = .2;
real spacer_width = 1;
real spacer_height = 1;

real roller_overlap = 1;     //amount that roller goes over the container area
real roller_length = 2.5 - .25;     //length of the roller
real roller_radius = 76.2 / 2.0;     //radius of roller
real roller_omega = 0;
real roller_velocity = -127;
real roller_mass = 1;
real roller_friction = .1;
real roller_cohesion = 0;
real particle_radius = .058 / 2.0;
real particle_std_dev = .015 / 2.0;
real particle_mass = .05;
real particle_density = 0.93;
real particle_layer_thickness = particle_radius * 12;
real particle_friction = .52;
real rolling_friction = .1;
real spinning_friction = .1;
real gravity = -9810;     //acceleration due to gravity
real timestep = .00001;     //step size
real time_to_run = 1;     //length of simulation
real current_time = 0;

int num_steps = time_to_run / timestep;
int max_iteration = 20;
int tolerance = 0;

string data_folder = "data/sls";
ChSharedBodyPtr ROLLER;
real ang = 0;

template<class T>
void RunTimeStep(T* mSys, const int frame) {
	ChVector<> roller_pos = ROLLER->GetPos();

	ROLLER->SetPos(ChVector<>(0, roller_radius + particle_layer_thickness + container_thickness, roller_pos.z + roller_velocity * timestep));
	ROLLER->SetPos_dt(ChVector<>(0, 0, roller_velocity));
	roller_omega = roller_velocity / roller_radius;
	ang += roller_omega * timestep;
	if (ang >= 2 * CH_C_PI) {
		ang = 0;
	}

	Quaternion q1;
	q1.Q_from_AngY(ang);
	Quaternion q2;
	q1 = Q_from_AngX(-ang);

	ChQuaternion<> roller_quat;
	roller_quat.Q_from_AngAxis(PI / 2.0, ChVector<>(0, 0, 1));

	ROLLER->SetRot(q1 % roller_quat);
	ROLLER->SetWvel_loc(Vector(0, roller_omega, 0));

	cout << ROLLER->GetPos().x << " " << ROLLER->GetPos().y << " " << ROLLER->GetPos().z << endl;
	;

}
int main(int argc, char* argv[]) {
	bool visualize = true;
	int config = 0;
	bool full_mix = true;
	if (argc > 1) {
		visualize = atoi(argv[1]);
		particle_friction = atof(argv[2]);
		rolling_friction = atof(argv[3]);
		spinning_friction = atof(argv[4]);
		roller_velocity = -atof(argv[5]);
		particle_layer_thickness = atof(argv[6]);
		full_mix = atoi(argv[7]);
		data_folder = argv[8];
	}
	//cout << "Mass, Radius, Friction_Sphere, Friction_Plate, Data Folder, create_particle_plate all_three_kinds, particle configuration" << endl;
	//=========================================================================================================
	ChSystemParallelDVI * system_gpu = new ChSystemParallelDVI;
	system_gpu->SetIntegrationType(ChSystem::INT_ANITESCU);
	//=========================================================================================================
	//system_gpu->SetMaxiter(max_iteration);

	//system_gpu->SetIterLCPmaxItersSpeed(max_iteration);
	//((ChLcpSolverParallelDVI *) (system_gpu->GetLcpSolverSpeed()))->SetMaxIteration(max_iter);
	((ChLcpSolverParallelDVI *) (system_gpu->GetLcpSolverSpeed()))->SetMaxIterationNormal(max_iteration * 2);
	((ChLcpSolverParallelDVI *) (system_gpu->GetLcpSolverSpeed()))->SetMaxIterationSliding(max_iteration);
	((ChLcpSolverParallelDVI *) (system_gpu->GetLcpSolverSpeed()))->SetMaxIterationSpinning(max_iteration);
	system_gpu->SetTol(0);
	system_gpu->SetTolSpeeds(0);
	((ChLcpSolverParallelDVI *) (system_gpu->GetLcpSolverSpeed()))->SetTolerance(0);
	((ChLcpSolverParallelDVI *) (system_gpu->GetLcpSolverSpeed()))->SetCompliance(0);
	((ChLcpSolverParallelDVI *) (system_gpu->GetLcpSolverSpeed()))->SetContactRecoverySpeed(300);
	((ChLcpSolverParallelDVI *) (system_gpu->GetLcpSolverSpeed()))->SetSolverType(APGDRS);
	((ChCollisionSystemParallel *) (system_gpu->GetCollisionSystem()))->SetCollisionEnvelope(particle_radius * .05);
	((ChCollisionSystemParallel *) (system_gpu->GetCollisionSystem()))->setBinsPerAxis(I3(40, 200, 100));
	((ChCollisionSystemParallel *) (system_gpu->GetCollisionSystem()))->setBodyPerBin(100, 50);
	((ChSystemParallelDVI*) system_gpu)->DoThreadTuning(false);
	//((ChSystemParallelDVI*) system_gpu)->SetMinThreads(32);
	system_gpu->Set_G_acc(ChVector<>(0, gravity, 0));
	system_gpu->SetStep(timestep);

	//=========================================================================================================
	((ChSystemParallel*) system_gpu)->SetAABB(R3(-6, -3, -30), R3(6, 6, 30));

	ChSharedBodyPtr PLATE = ChSharedBodyPtr(new ChBody(new ChCollisionModelParallel));

	ChSharedPtr<ChMaterialSurface> material_plate;
	material_plate = ChSharedPtr<ChMaterialSurface>(new ChMaterialSurface);
	material_plate->SetFriction(0);

	InitObject(PLATE, 100000, ChVector<>(0, 0, 0), quat, material_plate, true, true, -20, -20);

	ChSharedPtr<ChMaterialSurface> material;
	material = ChSharedPtr<ChMaterialSurface>(new ChMaterialSurface);
	material->SetFriction(container_friction);

	AddCollisionGeometry(PLATE, BOX, Vector(container_thickness, container_height, container_length), Vector(-container_width + container_thickness, container_height, 0), quat);
	AddCollisionGeometry(PLATE, BOX, Vector(container_thickness, container_height, container_length), Vector(container_width - container_thickness, container_height, 0), quat);
	AddCollisionGeometry(PLATE, BOX, Vector(container_width, container_height, container_thickness), Vector(0, container_height, -container_length + container_thickness), quat);
	AddCollisionGeometry(PLATE, BOX, Vector(container_width, container_height, container_thickness), Vector(0, container_height, container_length - container_thickness), quat);
	AddCollisionGeometry(PLATE, BOX, Vector(container_width, container_thickness, container_length), Vector(0, container_height*2,0), quat);
	FinalizeObject(PLATE, (ChSystemParallel *) system_gpu);

	ChSharedPtr<ChMaterialSurface> material_bottom;
	material_bottom = ChSharedPtr<ChMaterialSurface>(new ChMaterialSurface);
	material_bottom->SetFriction(floor_friction);

	ChSharedBodyPtr BOTTOM = ChSharedBodyPtr(new ChBody(new ChCollisionModelParallel));
	InitObject(BOTTOM, 100000, ChVector<>(0, 0, 0), quat, material_bottom, true, true, -20, -20);
	AddCollisionGeometry(BOTTOM, BOX, ChVector<>(container_width, container_thickness, container_length), lpos, quat);

	FinalizeObject(BOTTOM, (ChSystemParallel *) system_gpu);

	ROLLER = ChSharedBodyPtr(new ChBody(new ChCollisionModelParallel));
	ChQuaternion<> roller_quat;
	roller_quat.Q_from_AngAxis(PI / 2.0, ChVector<>(0, 0, 1));

	ChSharedPtr<ChMaterialSurface> material_roller;
	material_roller = ChSharedPtr<ChMaterialSurface>(new ChMaterialSurface);
	material_roller->SetFriction(roller_friction);

	InitObject(ROLLER, 1000, ChVector<>(0, roller_radius + particle_layer_thickness + container_thickness, container_length + roller_radius / 3.0), roller_quat, material_roller,
			true, false, -20, -20);
	AddCollisionGeometry(ROLLER, CYLINDER, ChVector<>(roller_radius, roller_length * 2, roller_radius), lpos, quat);
	FinalizeObject(ROLLER, (ChSystemParallel *) system_gpu);
	//68
	int3 num_per_dir = I3(1, 1, 1);
	//num_per_dir = I3(90, 16, 1);

	num_per_dir = I3(90, 17*particle_layer_thickness/.2032, 490);
	//num_per_dir = I3(90, 1, 490);
	ParticleGenerator < ChSystemParallelDVI > layer_gen(system_gpu);
	layer_gen.SetDensity(particle_density);
	layer_gen.SetRadius(R3(particle_radius));
	layer_gen.SetNormalDistribution(particle_radius, particle_std_dev);
	layer_gen.material->SetFriction(particle_friction);
	layer_gen.material->SetRollingFriction(rolling_friction);
	layer_gen.material->SetSpinningFriction(spinning_friction);

	if (full_mix) {
		layer_gen.AddMixtureType(MIX_SPHERE);
		layer_gen.AddMixtureType(MIX_TYPE1);
		layer_gen.AddMixtureType(MIX_TYPE2);
		layer_gen.AddMixtureType(MIX_TYPE3);
		layer_gen.AddMixtureType(MIX_TYPE4);
		layer_gen.AddMixtureType(MIX_ELLIPSOID);
		layer_gen.AddMixtureType(MIX_DOUBLESPHERE);
	}else{
		layer_gen.AddMixtureType(MIX_SPHERE);
	}

	//layer_gen.addPerturbedVolume(R3(0, 1.2, 0), SPHERE, num_per_dir, R3(.1, .1, .1), R3(0));

	layer_gen.addPerturbedVolumeMixture(R3(0, 1.3, 0), num_per_dir, R3(.1, .1, .1), R3(0));
	//num_per_dir = I3(90, 15, 100);
	//num_per_dir = I3(90, 15, 50);
	//num_per_dir = I3(1, 15, 100);
	//num_per_dir = I3(90, 30, 50);
	//layer_gen.addPerturbedVolumeMixture(R3(0, 3.2, 15), num_per_dir, R3(.1, .1, .1), R3(0));

	for(int i=0; i<system_gpu->Get_bodylist()->size(); i++){
		system_gpu->Get_bodylist()->at(i)->SetMaxSpeed(25);
	}
	//=========================================================================================================
	//////Rendering specific stuff:
	if (visualize) {
		ChOpenGLManager * window_manager = new ChOpenGLManager();
		ChOpenGL openGLView(window_manager, system_gpu, 800, 600, 0, 0, "Test_Solvers");
		openGLView.render_camera->camera_position = glm::vec3(-50, 0, -50);
		openGLView.render_camera->camera_look_at = glm::vec3(0, 0, 0);
		openGLView.SetCustomCallback(RunTimeStep);
		openGLView.StartSpinning(window_manager);
		window_manager->CallGlutMainLoop();
	}
	//=========================================================================================================
	stringstream ss_m;
	ss_m << data_folder << "/" << "timing.txt";
	string timing_file_name = ss_m.str();
	ofstream ofile(timing_file_name.c_str());
	ofile.close();
	int file = 0;
	for (int i = 0; i < num_steps; i++) {
		cout << "step " << i;
		cout << " Residual: " << ((ChLcpSolverParallel *) (system_gpu->GetLcpSolverSpeed()))->GetResidual();
		cout << " ITER: " << ((ChLcpSolverParallel *) (system_gpu->GetLcpSolverSpeed()))->GetTotalIterations();
		cout << " OUTPUT STEP: Time= " << current_time << " bodies= " << system_gpu->GetNbodies() << " contacts= " << system_gpu->GetNcontacts() << " step time="
				<< system_gpu->GetTimerStep() << " lcp time=" << system_gpu->GetTimerLcp() << " CDbroad time=" << system_gpu->GetTimerCollisionBroad() << " CDnarrow time="
				<< system_gpu->GetTimerCollisionNarrow() << " Iterations=" << ((ChLcpSolverParallel*) (system_gpu->GetLcpSolverSpeed()))->GetTotalIterations() << " "
				<< ROLLER->GetPos().z << "\n";
		//TimingFile(system_gpu, timing_file_name, current_time);
		system_gpu->DoStepDynamics(timestep);
		RunTimeStep(system_gpu, i);
		int save_every = 1.0 / timestep / 6000.0;     //save data every n steps
		if (i % save_every == 0) {
			stringstream ss;
			cout << "Frame: " << file << endl;
			ss << "/dev/shm/"<<data_folder << "/" << file << ".txt";
			DumpAllObjectsWithGeometryPovray(system_gpu, ss.str());
			stringstream tempmove;
			tempmove<<"mv "<<ss.str()<<" "<<data_folder << "/" << file << ".txt &";
			system(tempmove.str().c_str());
			//output.ExportData(ss.str());
			file++;
		}
		if (ROLLER->GetPos().z < -15) {
			break;
		}
		current_time += timestep;
	}
	stringstream ss;
	return 0;
}

<|endoftext|>


<commit_before>#include "options.hpp"
#include "tasks.hpp"

#include "../core.h"
#include "../io.h"
#include "../algorithms.h"

#include <include/prob/probability.hpp>
#include <include/prob/generator.hpp>
#include <include/util/iterator_ext.hpp>

#include <vector>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <unordered_map>
#include <queue>

#include <cstdlib>
#include <cmath>

#define DEBUG 1

int runTask(int argc, char** argv) {
  // parse arguments
  OPTIONS opts;
  opts.parseInputArgs(argc, argv);
#ifndef DEBUG
  opts.printOptions(std::cout);
#endif
  int task = opts.task;
  std::string taskSelectedMsg = "None";
  switch(task) {
  case 0:
    {
      taskSelectedMsg = "No operation";
      break;
    }
  case 1: // Smith Waterman alignment
    {
      taskSelectedMsg = "Smith-Waterman alignment";
      string ref = opts.genomeFile;
      string reads = opts.readsFile;
      alignFastqReadsSimpleSW(reads, ref, std::cout, 2, 8);
      break;
    }
  case 2: // k-spectrum calculation
    {
      taskSelectedMsg = "k-spectrum";
      size_t k = opts.kmerSize;
      string ref = opts.genomeFile;
      taskComputeKSpectrum(k, ref);
      break;
    }
  case 3:
    {

      // k-mer mapping
      taskSelectedMsg = "k-mapping";
      size_t k = opts.kmerSize;
      string ref = opts.genomeFile;
      string reads = opts.readsFile;
      string out = opts.alignOutputFile;
      taskMapReadsKmers(ref, reads, k, out);
      break;
    }
  case 4:
    {
      // k-mer score for reads
      taskSelectedMsg = "k-score";
      size_t k = opts.kmerSize;
      string ref = opts.genomeFile;
      string reads = opts.readsFile;
      string out = opts.alignOutputFile;
      size_t nThreads = opts.threadsNumber;
      taskKmerScoreReads(ref, reads, k, out, nThreads);
      break;
    }
  case 5:
    {
      // statistics of reads
      taskSelectedMsg = "Reads statistics";
      string reads = opts.readsFile;
      string w_dir = opts.outputDir;
      string prefix = opts.prefixFile;
      task_read_statistics(reads, w_dir, prefix);
      break;
    }
  default:
    std::cout << "Unrecognized operation" << std::endl;
    return 1;
  }
  std::cout << "[TASK]    " << taskSelectedMsg << std::endl;
  return 0;
}

void test() {
  // Test disclaimer
  std::cout << "\n********** WARNING ********** \n" <<
    "  This is a Test Release \n" <<
    "***************************** \n" <<  std::endl;
  std::map<char,double> bases_map =
    {
      {'A',0.25},
      {'C',0.25},
      {'G',0.25},
      {'T',0.25}
    };
  lbio::DiscreteProbability<char>
    base_prob_space(bases_map.cbegin(), bases_map.cend());

  for (auto b : bases_map) {
    std::cout << b.first << "\t" <<
      base_prob_space.probability_of(b.first) << "\n";
  }
  std::vector<char> acg = {'A','C','G'};
  std::cout << base_prob_space.probability_of(acg.cbegin(), acg.cend()) << "\n";

  std::cout << base_prob_space.probability_if([](char c)
					      { return (c <='C');
					      }) << "\n";
  lbio::IIDSampler<lbio::DiscreteProbability<char>> sampler(base_prob_space);
  std::map<int,int> mmap;
  mmap[1] = 1;
  mmap[2] = 22;
  mmap[3] = 333;
  lbio::map_key_iterator<std::map<int,int>> ii_iter(mmap);
  lbio::map_value_iterator<std::map<int,int>> iv_iter(mmap);
  while(ii_iter != mmap.end()) {
    std::cout << *ii_iter << "\n";
    ++ii_iter;
  }
  while(iv_iter != mmap.end()) {
    std::cout << *iv_iter << "\n";
    ++iv_iter;
  }
}

#include "../core/DNAAlphabet2Bits.hpp"

int main(int argc, char** argv) {
  runTask(argc, argv);
  test();
  return 0;
}
<commit_msg>More on map iterators extension<commit_after>#include "options.hpp"
#include "tasks.hpp"

#include "../core.h"
#include "../io.h"
#include "../algorithms.h"

#include <include/prob/probability.hpp>
#include <include/prob/generator.hpp>
#include <include/util/iterator_ext.hpp>

#include <vector>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <unordered_map>
#include <queue>

#include <cstdlib>
#include <cmath>

#define DEBUG 1

int runTask(int argc, char** argv) {
  // parse arguments
  OPTIONS opts;
  opts.parseInputArgs(argc, argv);
#ifndef DEBUG
  opts.printOptions(std::cout);
#endif
  int task = opts.task;
  std::string taskSelectedMsg = "None";
  switch(task) {
  case 0:
    {
      taskSelectedMsg = "No operation";
      break;
    }
  case 1: // Smith Waterman alignment
    {
      taskSelectedMsg = "Smith-Waterman alignment";
      string ref = opts.genomeFile;
      string reads = opts.readsFile;
      alignFastqReadsSimpleSW(reads, ref, std::cout, 2, 8);
      break;
    }
  case 2: // k-spectrum calculation
    {
      taskSelectedMsg = "k-spectrum";
      size_t k = opts.kmerSize;
      string ref = opts.genomeFile;
      taskComputeKSpectrum(k, ref);
      break;
    }
  case 3:
    {

      // k-mer mapping
      taskSelectedMsg = "k-mapping";
      size_t k = opts.kmerSize;
      string ref = opts.genomeFile;
      string reads = opts.readsFile;
      string out = opts.alignOutputFile;
      taskMapReadsKmers(ref, reads, k, out);
      break;
    }
  case 4:
    {
      // k-mer score for reads
      taskSelectedMsg = "k-score";
      size_t k = opts.kmerSize;
      string ref = opts.genomeFile;
      string reads = opts.readsFile;
      string out = opts.alignOutputFile;
      size_t nThreads = opts.threadsNumber;
      taskKmerScoreReads(ref, reads, k, out, nThreads);
      break;
    }
  case 5:
    {
      // statistics of reads
      taskSelectedMsg = "Reads statistics";
      string reads = opts.readsFile;
      string w_dir = opts.outputDir;
      string prefix = opts.prefixFile;
      task_read_statistics(reads, w_dir, prefix);
      break;
    }
  default:
    std::cout << "Unrecognized operation" << std::endl;
    return 1;
  }
  std::cout << "[TASK]    " << taskSelectedMsg << std::endl;
  return 0;
}

void test() {
  // Test disclaimer
  std::cout << "\n********** WARNING ********** \n" <<
    "  This is a Test Release \n" <<
    "***************************** \n" <<  std::endl;
  std::map<char,double> bases_map =
    {
      {'A',0.25},
      {'C',0.25},
      {'G',0.25},
      {'T',0.25}
    };
  lbio::DiscreteProbability<char>
    base_prob_space(bases_map.cbegin(), bases_map.cend());

  for (auto b : bases_map) {
    std::cout << b.first << "\t" <<
      base_prob_space.probability_of(b.first) << "\n";
  }
  std::vector<char> acg = {'A','C','G'};
  std::cout << base_prob_space.probability_of(acg.cbegin(), acg.cend()) << "\n";

  std::cout << base_prob_space.probability_if([](char c)
					      { return (c <='C');
					      }) << "\n";
  lbio::IIDSampler<lbio::DiscreteProbability<char>> sampler(base_prob_space);
  std::map<int,int> mmap;
  mmap[1] = 1;
  mmap[2] = 22;
  mmap[3] = 333;
  lbio::map_key_iterator<std::map<int,int>> ii_iter(mmap);
  lbio::map_value_iterator<std::map<int,int>> iv_iter(mmap.begin());
  while(ii_iter != mmap.end()) {
    std::cout << *ii_iter << "\n";
    ++ii_iter;
  }
  while(iv_iter != mmap.end()) {
    std::cout << *iv_iter << "\n";
    ++iv_iter;
  }
}

#include "../core/DNAAlphabet2Bits.hpp"

int main(int argc, char** argv) {
  runTask(argc, argv);
  test();
  return 0;
}
<|endoftext|>


<commit_before>// Fill out your copyright notice in the Description page of Project Settings.

#include "coopgame.h"
#include "NativeProjectileBase.h"
#include "NativeBaseCharacter.h"

ANativeProjectileBase::ANativeProjectileBase(const FObjectInitializer& objectInitializer)
	: Super(objectInitializer)
{
	// collision
	m_collisionComponent = objectInitializer.CreateDefaultSubobject<USphereComponent>(this, TEXT("SphereComponent"));
	m_collisionComponent->InitSphereRadius(5.0f); // ??
	m_collisionComponent->AlwaysLoadOnClient = true;
	m_collisionComponent->AlwaysLoadOnServer = true;
	m_collisionComponent->bTraceComplexOnMove = true;
	m_collisionComponent->SetCollisionEnabled(ECollisionEnabled::QueryOnly);
	m_collisionComponent->SetCollisionObjectType(COLLISION_PROJECTILE);
	m_collisionComponent->SetCollisionResponseToAllChannels(ECR_Ignore);
	m_collisionComponent->SetCollisionResponseToChannel(ECC_WorldStatic, ECR_Block);
	m_collisionComponent->SetCollisionResponseToChannel(ECC_WorldDynamic, ECR_Block);
	m_collisionComponent->SetCollisionResponseToChannel(ECC_Pawn, ECR_Block);
	RootComponent = m_collisionComponent;

	// movement
	m_movementComponent = objectInitializer.CreateDefaultSubobject<UProjectileMovementComponent>(this, TEXT("ProjectileMovementComponent"));
	m_movementComponent->UpdatedComponent = m_collisionComponent;
	m_movementComponent->InitialSpeed = 2000.0f;
	m_movementComponent->MaxSpeed = 2000.0f;
	m_movementComponent->bRotationFollowsVelocity = true;
	m_movementComponent->ProjectileGravityScale = 0.f;

	// ticking
	PrimaryActorTick.bCanEverTick = true;
	PrimaryActorTick.TickGroup = TG_PrePhysics;

	// network
	SetRemoteRoleForBackwardsCompat(ROLE_SimulatedProxy);
	bReplicates = true;
	bReplicateMovement = true;
}

void ANativeProjectileBase::PostInitializeComponents()
{
	Super::PostInitializeComponents();
	m_movementComponent->OnProjectileStop.AddDynamic(this, &ANativeProjectileBase::OnImpact);
	m_collisionComponent->MoveIgnoreActors.Add(Instigator);

	//AShooterWeapon_Projectile* OwnerWeapon = Cast<AShooterWeapon_Projectile>(GetOwner());
	//if (OwnerWeapon)
	//{
	//	OwnerWeapon->ApplyWeaponConfig(WeaponConfig);
	//}

	//SetLifeSpan(WeaponConfig.ProjectileLife);
	//MyController = GetInstigatorController();
}

void ANativeProjectileBase::OnImpact(const FHitResult& hitResult)
{
	if (Role == ROLE_Authority/* && !bExploded*/)
	{
		//Explode(HitResult);
		if (hitResult.Actor != nullptr)
		{
			auto actor = hitResult.Actor.Get();
			UE_LOG(LogCoopGameWeapon, Log, TEXT("Hit an actor!"));
			auto asCharacter = Cast<ANativeBaseCharacter>(actor);
			if (asCharacter != nullptr)
			{
				UE_LOG(LogCoopGameWeapon, Log, TEXT("Hit a coop character"));

				UGameplayStatics::ApplyDamage(asCharacter, 25.0f, Instigator->Controller, this, TSubclassOf<UDamageType>(UDamageType::StaticClass()));
			}
		}
		else
		{
			UE_LOG(LogCoopGameWeapon, Log, TEXT("Hit something else"));
		}
		DisableAndDestroy();
	}

	UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), m_impactEffects, GetActorLocation(), GetActorRotation().GetInverse());

	OnProjectileImpacted();
}

void ANativeProjectileBase::DisableAndDestroy()
{
	/*UAudioComponent* ProjAudioComp = FindComponentByClass<UAudioComponent>();
	if (ProjAudioComp && ProjAudioComp->IsPlaying())
	{
		ProjAudioComp->FadeOut(0.1f, 0.f);
	}*/

	m_movementComponent->StopMovementImmediately();
	SetActorEnableCollision(false);

	// give clients some time to show explosion
	SetLifeSpan(2.0f);
}

void ANativeProjectileBase::OnProjectileImpacted_Implementation()
{
	// default impl does nothing
}
<commit_msg>super hack to lessen damage from enemies temporarily<commit_after>// Fill out your copyright notice in the Description page of Project Settings.

#include "coopgame.h"
#include "NativeProjectileBase.h"
#include "NativeBaseCharacter.h"

ANativeProjectileBase::ANativeProjectileBase(const FObjectInitializer& objectInitializer)
	: Super(objectInitializer)
{
	// collision
	m_collisionComponent = objectInitializer.CreateDefaultSubobject<USphereComponent>(this, TEXT("SphereComponent"));
	m_collisionComponent->InitSphereRadius(5.0f); // ??
	m_collisionComponent->AlwaysLoadOnClient = true;
	m_collisionComponent->AlwaysLoadOnServer = true;
	m_collisionComponent->bTraceComplexOnMove = true;
	m_collisionComponent->SetCollisionEnabled(ECollisionEnabled::QueryOnly);
	m_collisionComponent->SetCollisionObjectType(COLLISION_PROJECTILE);
	m_collisionComponent->SetCollisionResponseToAllChannels(ECR_Ignore);
	m_collisionComponent->SetCollisionResponseToChannel(ECC_WorldStatic, ECR_Block);
	m_collisionComponent->SetCollisionResponseToChannel(ECC_WorldDynamic, ECR_Block);
	m_collisionComponent->SetCollisionResponseToChannel(ECC_Pawn, ECR_Block);
	RootComponent = m_collisionComponent;

	// movement
	m_movementComponent = objectInitializer.CreateDefaultSubobject<UProjectileMovementComponent>(this, TEXT("ProjectileMovementComponent"));
	m_movementComponent->UpdatedComponent = m_collisionComponent;
	m_movementComponent->InitialSpeed = 2000.0f;
	m_movementComponent->MaxSpeed = 2000.0f;
	m_movementComponent->bRotationFollowsVelocity = true;
	m_movementComponent->ProjectileGravityScale = 0.f;

	// ticking
	PrimaryActorTick.bCanEverTick = true;
	PrimaryActorTick.TickGroup = TG_PrePhysics;

	// network
	SetRemoteRoleForBackwardsCompat(ROLE_SimulatedProxy);
	bReplicates = true;
	bReplicateMovement = true;
}

void ANativeProjectileBase::PostInitializeComponents()
{
	Super::PostInitializeComponents();
	m_movementComponent->OnProjectileStop.AddDynamic(this, &ANativeProjectileBase::OnImpact);
	m_collisionComponent->MoveIgnoreActors.Add(Instigator);

	//AShooterWeapon_Projectile* OwnerWeapon = Cast<AShooterWeapon_Projectile>(GetOwner());
	//if (OwnerWeapon)
	//{
	//	OwnerWeapon->ApplyWeaponConfig(WeaponConfig);
	//}

	//SetLifeSpan(WeaponConfig.ProjectileLife);
	//MyController = GetInstigatorController();
}

void ANativeProjectileBase::OnImpact(const FHitResult& hitResult)
{
	if (Role == ROLE_Authority/* && !bExploded*/)
	{
		//Explode(HitResult);
		if (hitResult.Actor != nullptr)
		{
			auto actor = hitResult.Actor.Get();
			UE_LOG(LogCoopGameWeapon, Log, TEXT("Hit an actor!"));
			auto asCoopCharacter = Cast<ANativeCoopCharacter>(actor);
			if (asCoopCharacter != nullptr)
			{
				UE_LOG(LogCoopGameWeapon, Log, TEXT("Hit a coop character"));

				UGameplayStatics::ApplyDamage(asCoopCharacter, 8.0f, Instigator->Controller, this, TSubclassOf<UDamageType>(UDamageType::StaticClass()));
			}
			else if (auto asCharacter = Cast<ANativeBaseCharacter>(actor))
			{
				UE_LOG(LogCoopGameWeapon, Log, TEXT("Hit a character"));
				UGameplayStatics::ApplyDamage(asCharacter, 34.0f, Instigator->Controller, this, TSubclassOf<UDamageType>(UDamageType::StaticClass()));
			}
		}
		else
		{
			UE_LOG(LogCoopGameWeapon, Log, TEXT("Hit something else"));
		}
		DisableAndDestroy();
	}

	UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), m_impactEffects, GetActorLocation(), GetActorRotation().GetInverse());

	OnProjectileImpacted();
}

void ANativeProjectileBase::DisableAndDestroy()
{
	/*UAudioComponent* ProjAudioComp = FindComponentByClass<UAudioComponent>();
	if (ProjAudioComp && ProjAudioComp->IsPlaying())
	{
		ProjAudioComp->FadeOut(0.1f, 0.f);
	}*/

	m_movementComponent->StopMovementImmediately();
	SetActorEnableCollision(false);

	// give clients some time to show explosion
	SetLifeSpan(2.0f);
}

void ANativeProjectileBase::OnProjectileImpacted_Implementation()
{
	// default impl does nothing
}
<|endoftext|>


<commit_before>/** @file
 *  @brief Implementation of interface to the core framework
 *  @copyright MIT License
 */

#include "Allpix.hpp"

#include <chrono>
#include <climits>
#include <fstream>
#include <memory>
#include <stdexcept>
#include <thread>
#include <utility>

#include <TROOT.h>
#include <TRandom.h>
#include <TStyle.h>
#include <TSystem.h>

#include "core/config/exceptions.h"
#include "core/utils/file.h"
#include "core/utils/log.h"
#include "core/utils/unit.h"

using namespace allpix;

/**
 * This class will own the managers for the lifetime of the simulation. Will do early initialization:
 * - Configure the special header sections.
 * - Set the log level and log format as requested.
 * - Load the detector configuration and parse it
 */
Allpix::Allpix(std::string config_file_name)
    : terminate_(false), has_run_(false), msg_(std::make_unique<Messenger>()), mod_mgr_(std::make_unique<ModuleManager>()),
      geo_mgr_(std::make_unique<GeometryManager>()) {
    // Load the global configuration
    conf_mgr_ = std::make_unique<ConfigManager>(std::move(config_file_name));

    // Configure the standard special sections
    conf_mgr_->setGlobalHeaderName("Allpix");
    conf_mgr_->addGlobalHeaderName("");
    conf_mgr_->addIgnoreHeaderName("Ignore");

    // Fetch the global configuration
    Configuration global_config = conf_mgr_->getGlobalConfiguration();

    // Set the log level from config if not specified earlier
    std::string log_level_string;
    if(Log::getReportingLevel() == LogLevel::NONE) {
        log_level_string = global_config.get<std::string>("log_level", "INFO");
        std::transform(log_level_string.begin(), log_level_string.end(), log_level_string.begin(), ::toupper);
        try {
            LogLevel log_level = Log::getLevelFromString(log_level_string);
            Log::setReportingLevel(log_level);
        } catch(std::invalid_argument& e) {
            LOG(ERROR) << "Log level \"" << log_level_string
                       << "\" specified in the configuration is invalid, defaulting to INFO instead";
            Log::setReportingLevel(LogLevel::INFO);
        }
    } else {
        log_level_string = Log::getStringFromLevel(Log::getReportingLevel());
    }

    // Set the log format from config
    std::string log_format_string = global_config.get<std::string>("log_format", "DEFAULT");
    std::transform(log_format_string.begin(), log_format_string.end(), log_format_string.begin(), ::toupper);
    try {
        LogFormat log_format = Log::getFormatFromString(log_format_string);
        Log::setFormat(log_format);
    } catch(std::invalid_argument& e) {
        LOG(ERROR) << "Log format \"" << log_format_string
                   << "\" specified in the configuration is invalid, using DEFAULT instead";
        Log::setFormat(LogFormat::DEFAULT);
    }

    // Open log file to write output to
    if(global_config.has("log_file")) {
        // NOTE: this stream should be available for the duration of the logging
        log_file_.open(global_config.getPath("log_file"), std::ios_base::out | std::ios_base::trunc);
        Log::addStream(log_file_);
    }

    // Wait for the first detailed messages until level and format are properly set
    LOG(TRACE) << "Global log level is set to " << log_level_string;
    LOG(TRACE) << "Global log format is set to " << log_format_string;
}

/**
 * Performs the initialization, including:
 * - Initialize the random seeder
 * - Determine and create the output directory
 * - Include all the defined units
 * - Load the modules from the configuration
 */
void Allpix::load() {
    LOG(TRACE) << "Loading Allpix";

    // Put welcome message
    LOG(STATUS) << "Welcome to Allpix^2 " << ALLPIX_PROJECT_VERSION;

    // Fetch the global configuration
    Configuration global_config = conf_mgr_->getGlobalConfiguration();

    // Initialize the random seeder
    std::mt19937_64 seeder;
    uint64_t seed = 0;
    if(global_config.has("random_seed")) {
        // Use provided random seed
        seed = global_config.get<uint64_t>("random_seed");
        seeder.seed(seed);
        LOG(STATUS) << "Initialized PRNG with configured seed " << seed;
    } else {
        // Compute random entropy seed
        // Use the clock
        auto clock_seed = static_cast<uint64_t>(std::chrono::high_resolution_clock::now().time_since_epoch().count());
        // Use memory location local variable
        auto mem_seed = reinterpret_cast<uint64_t>(&seed); // NOLINT
        // Use thread id
        std::hash<std::thread::id> thrd_hasher;
        auto thread_seed = thrd_hasher(std::this_thread::get_id());
        seed = (clock_seed ^ mem_seed ^ thread_seed);
        seeder.seed(seed);
        LOG(STATUS) << "Initialized PRNG with system entropy seed " << seed;
    }

    // Initialize ROOT random generator
    gRandom->SetSeed(seeder());

    // Get output directory
    std::string directory = gSystem->pwd();
    directory += "/output";
    if(global_config.has("output_directory")) {
        // Use config specified one if available
        directory = global_config.getPath("output_directory");
    }
    // Delete previous output directory if it exists
    if(allpix::path_is_directory(directory.c_str())) {
        LOG(DEBUG) << "Deleting previous output directory";
        allpix::remove_path(directory.c_str());
    }
    // Create the output directory
    try {
        allpix::create_directories(directory);
        gSystem->ChangeDirectory(directory.c_str());
    } catch(std::invalid_argument& e) {
        LOG(ERROR) << "Cannot create output directory " << directory << ": " << e.what()
                   << ". Using current directory instead!";
    }

    // Enable relevant multithreading if needed (disabled by default)
    if(global_config.get<bool>("experimental_multithreading", false)) {
        // Enable thread safety for ROOT
        ROOT::EnableThreadSafety();
    }

    // Set the default units to use
    add_units();

    // Set the ROOT style
    set_style();

    // Load the geometry
    geo_mgr_->load(global_config);

    // Load the modules from the configuration
    if(!terminate_) {
        mod_mgr_->load(msg_.get(), conf_mgr_.get(), geo_mgr_.get(), seeder);
    } else {
        LOG(INFO) << "Skip loading modules because termination is requested";
    }
}

/**
 * Runs the Module::init() method linearly for every module
 */
void Allpix::init() {
    if(!terminate_) {
        LOG(TRACE) << "Initializing Allpix";
        mod_mgr_->init();
    } else {
        LOG(INFO) << "Skip initializing modules because termination is requested";
    }
}
/**
 * Runs every modules Module::run() method linearly for the number of events
 */
void Allpix::run() {
    if(!terminate_) {
        LOG(TRACE) << "Running Allpix";
        mod_mgr_->run();

        // Set that we have run and want to finalize as well
        has_run_ = true;
    } else {
        LOG(INFO) << "Skip running modules because termination is requested";
    }
}
/**
 * Runs all modules Module::finalize() method linearly for every module
 */
void Allpix::finalize() {
    if(has_run_) {
        LOG(TRACE) << "Finalizing Allpix";
        mod_mgr_->finalize();
    } else {
        LOG(INFO) << "Skip finalizing modules because no module did run";
    }
}

/*
 * This function can be called safely from any signal handler. Time between the request to terminate
 * and the actual termination is not always negigible.
 */
void Allpix::terminate() {
    terminate_ = true;
    mod_mgr_->terminate();
}

void Allpix::add_units() {
    LOG(TRACE) << "Adding physical units";

    // LENGTH
    Units::add("nm", 1e-6);
    Units::add("um", 1e-3);
    Units::add("mm", 1);
    Units::add("cm", 1e1);
    Units::add("dm", 1e2);
    Units::add("m", 1e3);
    Units::add("km", 1e6);

    // TIME
    Units::add("ps", 1e-3);
    Units::add("ns", 1);
    Units::add("us", 1e3);
    Units::add("ms", 1e6);
    Units::add("s", 1e9);

    // TEMPERATURE
    Units::add("K", 1);

    // ENERGY
    Units::add("eV", 1e-6);
    Units::add("keV", 1e-3);
    Units::add("MeV", 1);
    Units::add("GeV", 1e3);

    // CHARGE
    Units::add("e", 1);
    Units::add("C", 1.6021766208e-19);

    // VOLTAGE
    // NOTE: fixed by above
    Units::add("V", 1e-6);
    Units::add("kV", 1e-3);

    // ANGLES
    // NOTE: these are fake units
    Units::add("deg", 0.01745329252);
    Units::add("rad", 1);
    Units::add("mrad", 1e-3);
}

/**
 * This style is inspired by the CLICdp plot style
 */
void Allpix::set_style() {
    LOG(TRACE) << "Setting ROOT plotting style";

    // use plain style as base
    gROOT->SetStyle("Plain");
    TStyle* style = gROOT->GetStyle("Plain");

    // Prefer OpenGL if available
    style->SetCanvasPreferGL(kTRUE);

    // Set backgrounds
    style->SetCanvasColor(kWhite);
    style->SetFrameFillColor(kWhite);
    style->SetStatColor(kWhite);
    style->SetPadColor(kWhite);
    style->SetFillColor(10);
    style->SetTitleFillColor(kWhite);

    // SetPaperSize wants width & height in cm: A4 is 20,26
    style->SetPaperSize(20, 26);
    // No yellow border around histogram
    style->SetDrawBorder(0);
    // Remove border of canvas*
    style->SetCanvasBorderMode(0);
    // Remove border of pads
    style->SetPadBorderMode(0);
    style->SetFrameBorderMode(0);
    style->SetLegendBorderSize(0);

    // Default text size
    style->SetTextSize(0.04f);
    style->SetTitleSize(0.04f, "xyz");
    style->SetLabelSize(0.03f, "xyz");

    // Title offset: distance between given text and axis
    style->SetLabelOffset(0.01f, "xyz");
    style->SetTitleOffset(1.6f, "yz");
    style->SetTitleOffset(1.4f, "x");

    // Set font settings
    short font = 42; // Use a clear font
    style->SetTitleFont(font);
    style->SetTitleFontSize(0.06f);
    style->SetStatFont(font);
    style->SetStatFontSize(0.07f);
    style->SetTextFont(font);
    style->SetLabelFont(font, "xyz");
    style->SetTitleFont(font, "xyz");
    style->SetTitleBorderSize(0);
    style->SetStatBorderSize(1);

    // Set style for markers
    style->SetMarkerStyle(1);
    style->SetLineWidth(2);
    style->SetMarkerSize(1.2f);

    // Set palette in 2d histogram to nice and colorful one
    style->SetPalette(1, nullptr);

    // Disable title by default for histograms
    style->SetOptTitle(0);

    // Set statistics
    style->SetOptStat(0);
    style->SetOptFit(0);

    // Number of decimals used for errors
    style->SetEndErrorSize(5);

    // Set line width to 2 by default so that histograms are visible when printed small
    // Idea: emphasize the data, not the frame around
    style->SetHistLineWidth(2);
    style->SetFrameLineWidth(2);
    style->SetFuncWidth(2);
    style->SetHistLineColor(kBlack);
    style->SetFuncColor(kRed);
    style->SetLabelColor(kBlack, "xyz");

    // Set the margins
    style->SetPadBottomMargin(0.18f);
    style->SetPadTopMargin(0.08f);
    style->SetPadRightMargin(0.18f);
    style->SetPadLeftMargin(0.17f);

    // Set the default number of divisions to show
    style->SetNdivisions(506, "xy");

    // Turn off xy grids
    style->SetPadGridX(false);
    style->SetPadGridY(false);

    // Set the tick mark style
    style->SetPadTickX(1);
    style->SetPadTickY(1);
    style->SetCanvasDefW(800);
    style->SetCanvasDefH(700);

    // Force the style
    gROOT->ForceStyle();
}
<commit_msg>fix redundant calls to c_str()<commit_after>/** @file
 *  @brief Implementation of interface to the core framework
 *  @copyright MIT License
 */

#include "Allpix.hpp"

#include <chrono>
#include <climits>
#include <fstream>
#include <memory>
#include <stdexcept>
#include <thread>
#include <utility>

#include <TROOT.h>
#include <TRandom.h>
#include <TStyle.h>
#include <TSystem.h>

#include "core/config/exceptions.h"
#include "core/utils/file.h"
#include "core/utils/log.h"
#include "core/utils/unit.h"

using namespace allpix;

/**
 * This class will own the managers for the lifetime of the simulation. Will do early initialization:
 * - Configure the special header sections.
 * - Set the log level and log format as requested.
 * - Load the detector configuration and parse it
 */
Allpix::Allpix(std::string config_file_name)
    : terminate_(false), has_run_(false), msg_(std::make_unique<Messenger>()), mod_mgr_(std::make_unique<ModuleManager>()),
      geo_mgr_(std::make_unique<GeometryManager>()) {
    // Load the global configuration
    conf_mgr_ = std::make_unique<ConfigManager>(std::move(config_file_name));

    // Configure the standard special sections
    conf_mgr_->setGlobalHeaderName("Allpix");
    conf_mgr_->addGlobalHeaderName("");
    conf_mgr_->addIgnoreHeaderName("Ignore");

    // Fetch the global configuration
    Configuration global_config = conf_mgr_->getGlobalConfiguration();

    // Set the log level from config if not specified earlier
    std::string log_level_string;
    if(Log::getReportingLevel() == LogLevel::NONE) {
        log_level_string = global_config.get<std::string>("log_level", "INFO");
        std::transform(log_level_string.begin(), log_level_string.end(), log_level_string.begin(), ::toupper);
        try {
            LogLevel log_level = Log::getLevelFromString(log_level_string);
            Log::setReportingLevel(log_level);
        } catch(std::invalid_argument& e) {
            LOG(ERROR) << "Log level \"" << log_level_string
                       << "\" specified in the configuration is invalid, defaulting to INFO instead";
            Log::setReportingLevel(LogLevel::INFO);
        }
    } else {
        log_level_string = Log::getStringFromLevel(Log::getReportingLevel());
    }

    // Set the log format from config
    std::string log_format_string = global_config.get<std::string>("log_format", "DEFAULT");
    std::transform(log_format_string.begin(), log_format_string.end(), log_format_string.begin(), ::toupper);
    try {
        LogFormat log_format = Log::getFormatFromString(log_format_string);
        Log::setFormat(log_format);
    } catch(std::invalid_argument& e) {
        LOG(ERROR) << "Log format \"" << log_format_string
                   << "\" specified in the configuration is invalid, using DEFAULT instead";
        Log::setFormat(LogFormat::DEFAULT);
    }

    // Open log file to write output to
    if(global_config.has("log_file")) {
        // NOTE: this stream should be available for the duration of the logging
        log_file_.open(global_config.getPath("log_file"), std::ios_base::out | std::ios_base::trunc);
        Log::addStream(log_file_);
    }

    // Wait for the first detailed messages until level and format are properly set
    LOG(TRACE) << "Global log level is set to " << log_level_string;
    LOG(TRACE) << "Global log format is set to " << log_format_string;
}

/**
 * Performs the initialization, including:
 * - Initialize the random seeder
 * - Determine and create the output directory
 * - Include all the defined units
 * - Load the modules from the configuration
 */
void Allpix::load() {
    LOG(TRACE) << "Loading Allpix";

    // Put welcome message
    LOG(STATUS) << "Welcome to Allpix^2 " << ALLPIX_PROJECT_VERSION;

    // Fetch the global configuration
    Configuration global_config = conf_mgr_->getGlobalConfiguration();

    // Initialize the random seeder
    std::mt19937_64 seeder;
    uint64_t seed = 0;
    if(global_config.has("random_seed")) {
        // Use provided random seed
        seed = global_config.get<uint64_t>("random_seed");
        seeder.seed(seed);
        LOG(STATUS) << "Initialized PRNG with configured seed " << seed;
    } else {
        // Compute random entropy seed
        // Use the clock
        auto clock_seed = static_cast<uint64_t>(std::chrono::high_resolution_clock::now().time_since_epoch().count());
        // Use memory location local variable
        auto mem_seed = reinterpret_cast<uint64_t>(&seed); // NOLINT
        // Use thread id
        std::hash<std::thread::id> thrd_hasher;
        auto thread_seed = thrd_hasher(std::this_thread::get_id());
        seed = (clock_seed ^ mem_seed ^ thread_seed);
        seeder.seed(seed);
        LOG(STATUS) << "Initialized PRNG with system entropy seed " << seed;
    }

    // Initialize ROOT random generator
    gRandom->SetSeed(seeder());

    // Get output directory
    std::string directory = gSystem->pwd();
    directory += "/output";
    if(global_config.has("output_directory")) {
        // Use config specified one if available
        directory = global_config.getPath("output_directory");
    }
    // Delete previous output directory if it exists
    if(allpix::path_is_directory(directory)) {
        LOG(DEBUG) << "Deleting previous output directory";
        allpix::remove_path(directory);
    }
    // Create the output directory
    try {
        allpix::create_directories(directory);
        gSystem->ChangeDirectory(directory.c_str());
    } catch(std::invalid_argument& e) {
        LOG(ERROR) << "Cannot create output directory " << directory << ": " << e.what()
                   << ". Using current directory instead!";
    }

    // Enable relevant multithreading if needed (disabled by default)
    if(global_config.get<bool>("experimental_multithreading", false)) {
        // Enable thread safety for ROOT
        ROOT::EnableThreadSafety();
    }

    // Set the default units to use
    add_units();

    // Set the ROOT style
    set_style();

    // Load the geometry
    geo_mgr_->load(global_config);

    // Load the modules from the configuration
    if(!terminate_) {
        mod_mgr_->load(msg_.get(), conf_mgr_.get(), geo_mgr_.get(), seeder);
    } else {
        LOG(INFO) << "Skip loading modules because termination is requested";
    }
}

/**
 * Runs the Module::init() method linearly for every module
 */
void Allpix::init() {
    if(!terminate_) {
        LOG(TRACE) << "Initializing Allpix";
        mod_mgr_->init();
    } else {
        LOG(INFO) << "Skip initializing modules because termination is requested";
    }
}
/**
 * Runs every modules Module::run() method linearly for the number of events
 */
void Allpix::run() {
    if(!terminate_) {
        LOG(TRACE) << "Running Allpix";
        mod_mgr_->run();

        // Set that we have run and want to finalize as well
        has_run_ = true;
    } else {
        LOG(INFO) << "Skip running modules because termination is requested";
    }
}
/**
 * Runs all modules Module::finalize() method linearly for every module
 */
void Allpix::finalize() {
    if(has_run_) {
        LOG(TRACE) << "Finalizing Allpix";
        mod_mgr_->finalize();
    } else {
        LOG(INFO) << "Skip finalizing modules because no module did run";
    }
}

/*
 * This function can be called safely from any signal handler. Time between the request to terminate
 * and the actual termination is not always negigible.
 */
void Allpix::terminate() {
    terminate_ = true;
    mod_mgr_->terminate();
}

void Allpix::add_units() {
    LOG(TRACE) << "Adding physical units";

    // LENGTH
    Units::add("nm", 1e-6);
    Units::add("um", 1e-3);
    Units::add("mm", 1);
    Units::add("cm", 1e1);
    Units::add("dm", 1e2);
    Units::add("m", 1e3);
    Units::add("km", 1e6);

    // TIME
    Units::add("ps", 1e-3);
    Units::add("ns", 1);
    Units::add("us", 1e3);
    Units::add("ms", 1e6);
    Units::add("s", 1e9);

    // TEMPERATURE
    Units::add("K", 1);

    // ENERGY
    Units::add("eV", 1e-6);
    Units::add("keV", 1e-3);
    Units::add("MeV", 1);
    Units::add("GeV", 1e3);

    // CHARGE
    Units::add("e", 1);
    Units::add("C", 1.6021766208e-19);

    // VOLTAGE
    // NOTE: fixed by above
    Units::add("V", 1e-6);
    Units::add("kV", 1e-3);

    // ANGLES
    // NOTE: these are fake units
    Units::add("deg", 0.01745329252);
    Units::add("rad", 1);
    Units::add("mrad", 1e-3);
}

/**
 * This style is inspired by the CLICdp plot style
 */
void Allpix::set_style() {
    LOG(TRACE) << "Setting ROOT plotting style";

    // use plain style as base
    gROOT->SetStyle("Plain");
    TStyle* style = gROOT->GetStyle("Plain");

    // Prefer OpenGL if available
    style->SetCanvasPreferGL(kTRUE);

    // Set backgrounds
    style->SetCanvasColor(kWhite);
    style->SetFrameFillColor(kWhite);
    style->SetStatColor(kWhite);
    style->SetPadColor(kWhite);
    style->SetFillColor(10);
    style->SetTitleFillColor(kWhite);

    // SetPaperSize wants width & height in cm: A4 is 20,26
    style->SetPaperSize(20, 26);
    // No yellow border around histogram
    style->SetDrawBorder(0);
    // Remove border of canvas*
    style->SetCanvasBorderMode(0);
    // Remove border of pads
    style->SetPadBorderMode(0);
    style->SetFrameBorderMode(0);
    style->SetLegendBorderSize(0);

    // Default text size
    style->SetTextSize(0.04f);
    style->SetTitleSize(0.04f, "xyz");
    style->SetLabelSize(0.03f, "xyz");

    // Title offset: distance between given text and axis
    style->SetLabelOffset(0.01f, "xyz");
    style->SetTitleOffset(1.6f, "yz");
    style->SetTitleOffset(1.4f, "x");

    // Set font settings
    short font = 42; // Use a clear font
    style->SetTitleFont(font);
    style->SetTitleFontSize(0.06f);
    style->SetStatFont(font);
    style->SetStatFontSize(0.07f);
    style->SetTextFont(font);
    style->SetLabelFont(font, "xyz");
    style->SetTitleFont(font, "xyz");
    style->SetTitleBorderSize(0);
    style->SetStatBorderSize(1);

    // Set style for markers
    style->SetMarkerStyle(1);
    style->SetLineWidth(2);
    style->SetMarkerSize(1.2f);

    // Set palette in 2d histogram to nice and colorful one
    style->SetPalette(1, nullptr);

    // Disable title by default for histograms
    style->SetOptTitle(0);

    // Set statistics
    style->SetOptStat(0);
    style->SetOptFit(0);

    // Number of decimals used for errors
    style->SetEndErrorSize(5);

    // Set line width to 2 by default so that histograms are visible when printed small
    // Idea: emphasize the data, not the frame around
    style->SetHistLineWidth(2);
    style->SetFrameLineWidth(2);
    style->SetFuncWidth(2);
    style->SetHistLineColor(kBlack);
    style->SetFuncColor(kRed);
    style->SetLabelColor(kBlack, "xyz");

    // Set the margins
    style->SetPadBottomMargin(0.18f);
    style->SetPadTopMargin(0.08f);
    style->SetPadRightMargin(0.18f);
    style->SetPadLeftMargin(0.17f);

    // Set the default number of divisions to show
    style->SetNdivisions(506, "xy");

    // Turn off xy grids
    style->SetPadGridX(false);
    style->SetPadGridY(false);

    // Set the tick mark style
    style->SetPadTickX(1);
    style->SetPadTickY(1);
    style->SetCanvasDefW(800);
    style->SetCanvasDefH(700);

    // Force the style
    gROOT->ForceStyle();
}
<|endoftext|>


<commit_before>/**
 * This file is part of the CernVM File System.
 */
#include "cvmfs_config.h"
#include "cache_ram.h"

#include <errno.h>
#include <algorithm>
#include <cassert>
#include <cstring>
#include <new>

#include "kvstore.h"
#include "logging.h"
#include "util/posix.h"
#include "util_concurrency.h"

using namespace std;  // NOLINT

namespace cache {

int RamCacheManager::AddFd(const ReadOnlyFd &fd) {
  if (fd_pivot_ >= fd_index_.size()) {
    LogCvmfs(kLogCache, kLogDebug, "too many open files (%u)", fd_pivot_);
    perf::Inc(counters_.n_enfile);
    return -ENFILE;
  }
  size_t next_fd = fd_index_[fd_pivot_];
  assert(next_fd < open_fds_.size());
  assert(open_fds_[next_fd].handle == kInvalidHandle);
  open_fds_[next_fd] = fd;
  open_fds_[next_fd].index = fd_pivot_;
  ++fd_pivot_;
  return next_fd;
}

bool RamCacheManager::AcquireQuotaManager(QuotaManager *quota_mgr) {
  assert(quota_mgr != NULL);
  quota_mgr_ = quota_mgr;
  LogCvmfs(kLogCache, kLogDebug, "set quota manager");
  return true;
}

int RamCacheManager::Open(const shash::Any &id) {
  WriteLockGuard guard(rwlock_);
  return DoOpen(id);
}

int RamCacheManager::DoOpen(const shash::Any &id) {
  bool ok;
  bool is_volatile;
  MemoryBuffer buf;

  if (regular_entries_.GetBuffer(id, &buf)) {
    is_volatile = false;
  } else if (volatile_entries_.GetBuffer(id, &buf)) {
    is_volatile = true;
  } else {
    LogCvmfs(kLogCache, kLogDebug, "miss for %s",
             id.ToString().c_str());
    perf::Inc(counters_.n_openmiss);
    return -ENOENT;
  }
  int fd = AddFd(ReadOnlyFd(id));
  if (fd < 0) {
    LogCvmfs(kLogCache, kLogDebug, "error while opening %s: %s",
             id.ToString().c_str(), strerror(-fd));
    return fd;
  }
  open_fds_[fd].is_volatile = is_volatile;
  if (is_volatile) {
    LogCvmfs(kLogCache, kLogDebug, "hit in volatile entries for %s",
             id.ToString().c_str());
    perf::Inc(counters_.n_openvolatile);
  } else {
    LogCvmfs(kLogCache, kLogDebug, "hit in regular entries for %s",
             id.ToString().c_str());
    perf::Inc(counters_.n_openregular);
  }
  ok = GetStore(open_fds_[fd])->IncRef(id);
  assert(ok);
  return fd;
}

int64_t RamCacheManager::GetSize(int fd) {
  ReadLockGuard guard(rwlock_);
  if (!IsValid(fd)) {
    LogCvmfs(kLogCache, kLogDebug, "bad fd %d on GetSize", fd);
    return -EBADF;
  }
  perf::Inc(counters_.n_getsize);
  return GetStore(open_fds_[fd])->GetSize(open_fds_[fd].handle);
}

int RamCacheManager::Close(int fd) {
  bool rc;

  WriteLockGuard guard(rwlock_);
  if (!IsValid(fd)) {
    LogCvmfs(kLogCache, kLogDebug, "bad fd %d on Close", fd);
    return -EBADF;
  }
  rc = GetStore(open_fds_[fd])->Unref(open_fds_[fd].handle);
  assert(rc);
  open_fds_[fd].handle = kInvalidHandle;

  size_t index = open_fds_[fd].index;
  assert(index < fd_index_.size());
  assert(fd_pivot_ <= fd_index_.size());
  assert(fd_pivot_ > 0);
  --fd_pivot_;
  if (index < fd_pivot_) {
    size_t other = fd_index_[fd_pivot_];
    assert(other < open_fds_.size());
    assert(open_fds_[other].handle != kInvalidHandle);
    open_fds_[other].index = index;
    fd_index_[index] = other;
    fd_index_[fd_pivot_] = fd;
  }
  LogCvmfs(kLogCache, kLogDebug, "closed fd %d", fd);
  perf::Inc(counters_.n_close);
  return 0;
}

int64_t RamCacheManager::Pread(
  int fd,
  void *buf,
  uint64_t size,
  uint64_t offset)
{
  ReadLockGuard guard(rwlock_);
  if (!IsValid(fd)) {
    LogCvmfs(kLogCache, kLogDebug, "bad fd %d on Pread", fd);
    return -EBADF;
  }
  perf::Inc(counters_.n_pread);
  return GetStore(open_fds_[fd])->Read(open_fds_[fd].handle, buf, size, offset);
}

int RamCacheManager::Dup(int fd) {
  bool ok;
  int rc;
  WriteLockGuard guard(rwlock_);
  if (!IsValid(fd)) {
    LogCvmfs(kLogCache, kLogDebug, "bad fd %d on Dup", fd);
    return -EBADF;
  }
  rc = AddFd(open_fds_[fd]);
  if (rc < 0) return rc;
  ok = GetStore(open_fds_[fd])->IncRef(open_fds_[fd].handle);
  assert(ok);
  LogCvmfs(kLogCache, kLogDebug, "dup fd %d", fd);
  perf::Inc(counters_.n_dup);
  return rc;
}

/**
 * For a RAM cache, read-ahead is a no-op.
 */
int RamCacheManager::Readahead(int fd) {
  ReadLockGuard guard(rwlock_);
  if (!IsValid(fd)) {
    LogCvmfs(kLogCache, kLogDebug, "bad fd %d on Readahead", fd);
    return -EBADF;
  }
  LogCvmfs(kLogCache, kLogDebug, "readahead (no-op) on %d", fd);
  perf::Inc(counters_.n_readahead);
  return 0;
}

int RamCacheManager::StartTxn(const shash::Any &id, uint64_t size, void *txn) {
  LogCvmfs(kLogCache, kLogDebug, "new transaction with id %s",
           id.ToString().c_str());
  Transaction *transaction = new (txn) Transaction();
  transaction->id = id;
  transaction->pos = 0;
  transaction->expected_size = size;
  transaction->size = (size == kSizeUnknown) ? kPageSize : size;
  perf::Inc(counters_.n_starttxn);
  return 0;
}

void RamCacheManager::CtrlTxn(
  const string &description,
  const ObjectType type,
  const int flags,
  void *txn)
{
  Transaction *transaction = reinterpret_cast<Transaction *>(txn);
  transaction->description = description;
  if (!transaction->allocated) transaction->object_type = type;
  LogCvmfs(kLogCache, kLogDebug, "modified transaction %s",
           transaction->id.ToString().c_str());
}

int64_t RamCacheManager::Write(const void *buf, uint64_t size, void *txn) {
  Transaction *transaction = reinterpret_cast<Transaction *>(txn);

  /*
   * The initial buffer for the transaction must be allocated on the first
   * write so the caller has time to use CtrlTxn to set regular/volatile.
   * Transactions of unknown size will often be immediately reallocated,
   * but this is no worse than allocate on start.
   */
  if (!transaction->allocated) {
    transaction->buffer = GetTransactionStore(transaction)->MallocBuffer(
      transaction->size);
    assert(!size || transaction->buffer);
    transaction->allocated = true;
  }

  if (transaction->pos + size > transaction->size) {
    if (transaction->expected_size == kSizeUnknown) {
      perf::Inc(counters_.n_realloc);
      transaction->size = max(2*transaction->size, size + transaction->pos);
      LogCvmfs(kLogCache, kLogDebug, "reallocate transaction for %s to %u B",
               transaction->id.ToString().c_str(), transaction->size);
      transaction->buffer = GetTransactionStore(transaction)->ReallocBuffer(
        transaction->buffer, transaction->size);
      assert(transaction->buffer);
    } else {
      LogCvmfs(kLogCache, kLogDebug,
               "attempted to write more than requested (%u>%u)",
               size, transaction->size);
      return -EIO;
    }
  }

  if (transaction->buffer && buf) {
    // LogCvmfs(kLogCache, kLogDebug, "copy %u bytes of transaction %s",
    //          size, transaction->id.ToString().c_str());
    memcpy(static_cast<char *>(transaction->buffer) + transaction->pos,
           buf, size);
  }
  transaction->pos += size;
  perf::Inc(counters_.n_write);
  return size;
}

int RamCacheManager::Reset(void *txn) {
  Transaction *transaction = reinterpret_cast<Transaction *>(txn);
  transaction->pos = 0;
  LogCvmfs(kLogCache, kLogDebug, "reset transaction %s",
           transaction->id.ToString().c_str());
  perf::Inc(counters_.n_reset);
  return 0;
}

int RamCacheManager::OpenFromTxn(void *txn) {
  WriteLockGuard guard(rwlock_);
  Transaction *transaction = reinterpret_cast<Transaction *>(txn);
  int64_t retval = CommitToKvStore(transaction);
  if (retval < 0) {
    LogCvmfs(kLogCache, kLogDebug,
             "error while commiting transaction on %s: %s",
             transaction->id.ToString().c_str(), strerror(-retval));
    return retval;
  }
  LogCvmfs(kLogCache, kLogDebug, "open pending transaction for %s",
           transaction->id.ToString().c_str());
  perf::Inc(counters_.n_committxn);
  return DoOpen(transaction->id);
}

int RamCacheManager::AbortTxn(void *txn) {
  Transaction *transaction = reinterpret_cast<Transaction *>(txn);
  if (transaction->buffer) {
    GetTransactionStore(transaction)->FreeBuffer(transaction->buffer);
  }
  LogCvmfs(kLogCache, kLogDebug, "abort transaction %s",
           transaction->id.ToString().c_str());
  perf::Inc(counters_.n_aborttxn);
  return 0;
}

int RamCacheManager::CommitTxn(void *txn) {
  WriteLockGuard guard(rwlock_);
  Transaction *transaction = reinterpret_cast<Transaction *>(txn);
  perf::Inc(counters_.n_committxn);
  return CommitToKvStore(transaction);
}

int64_t RamCacheManager::CommitToKvStore(Transaction *transaction) {
  MemoryBuffer buf;
  buf.address = transaction->buffer;
  MemoryKvStore *store;
  if (transaction->expected_size == kSizeUnknown) {
    buf.size = transaction->pos;
    if (buf.size > 0) {
      buf.address = GetTransactionStore(transaction)->ReallocBuffer(
        buf.address, buf.size);
      assert(!buf.size || buf.address);
      LogCvmfs(kLogCache, kLogDebug, "reallocating transaction on %s to %u B",
               transaction->id.ToString().c_str(), buf.size);
    }
  } else {
    buf.size = transaction->size;
  }
  buf.object_type = transaction->object_type;

  if (buf.object_type == cache::CacheManager::kTypeVolatile) {
    store = &volatile_entries_;
  } else {
    store = &regular_entries_;
  }
  if (buf.object_type == cache::CacheManager::kTypePinned ||
      buf.object_type == cache::CacheManager::kTypePinned) {
    buf.refcount = 1;
  } else {
    buf.refcount = 0;
  }

  int64_t regular_size = regular_entries_.GetUsed();
  int64_t volatile_size = volatile_entries_.GetUsed();
  int64_t overrun = regular_size + volatile_size + buf.size - max_size_;

  if (overrun > 0) {
    // if we're going to clean the cache, remove at least 25%
    overrun = max(overrun, (int64_t) (max_size_>>2));
    perf::Inc(counters_.n_overrun);
    volatile_entries_.ShrinkTo(max((int64_t) 0, volatile_size - overrun));
  }
  overrun -= volatile_size - volatile_entries_.GetUsed();
  if (overrun > 0) {
    regular_entries_.ShrinkTo(max((int64_t) 0, regular_size - overrun));
  }
  overrun -= regular_size - regular_entries_.GetUsed();
  if (overrun > 0) {
    LogCvmfs(kLogCache, kLogDebug,
             "transaction for %s would overrun the cache limit by %d",
             transaction->id.ToString().c_str(), -overrun);
    perf::Inc(counters_.n_full);
    return -ENOSPC;
  }

  if (store->Commit(transaction->id, buf)) {
    LogCvmfs(kLogCache, kLogDebug, "committed %s to cache",
             transaction->id.ToString().c_str());
    return 0;
  } else {
    LogCvmfs(kLogCache, kLogDebug,
             "commit on %s failed, kvstore has too many entries",
             transaction->id.ToString().c_str());
    return -ENFILE;
  }
}

}  // namespace cache
<commit_msg>Fix ram cache cleanup<commit_after>/**
 * This file is part of the CernVM File System.
 */
#include "cvmfs_config.h"
#include "cache_ram.h"

#include <errno.h>
#include <algorithm>
#include <cassert>
#include <cstring>
#include <new>

#include "kvstore.h"
#include "logging.h"
#include "util/posix.h"
#include "util_concurrency.h"

using namespace std;  // NOLINT

namespace cache {

int RamCacheManager::AddFd(const ReadOnlyFd &fd) {
  if (fd_pivot_ >= fd_index_.size()) {
    LogCvmfs(kLogCache, kLogDebug, "too many open files (%u)", fd_pivot_);
    perf::Inc(counters_.n_enfile);
    return -ENFILE;
  }
  size_t next_fd = fd_index_[fd_pivot_];
  assert(next_fd < open_fds_.size());
  assert(open_fds_[next_fd].handle == kInvalidHandle);
  open_fds_[next_fd] = fd;
  open_fds_[next_fd].index = fd_pivot_;
  ++fd_pivot_;
  return next_fd;
}

bool RamCacheManager::AcquireQuotaManager(QuotaManager *quota_mgr) {
  assert(quota_mgr != NULL);
  quota_mgr_ = quota_mgr;
  LogCvmfs(kLogCache, kLogDebug, "set quota manager");
  return true;
}

int RamCacheManager::Open(const shash::Any &id) {
  WriteLockGuard guard(rwlock_);
  return DoOpen(id);
}

int RamCacheManager::DoOpen(const shash::Any &id) {
  bool ok;
  bool is_volatile;
  MemoryBuffer buf;

  if (regular_entries_.GetBuffer(id, &buf)) {
    is_volatile = false;
  } else if (volatile_entries_.GetBuffer(id, &buf)) {
    is_volatile = true;
  } else {
    LogCvmfs(kLogCache, kLogDebug, "miss for %s",
             id.ToString().c_str());
    perf::Inc(counters_.n_openmiss);
    return -ENOENT;
  }
  int fd = AddFd(ReadOnlyFd(id));
  if (fd < 0) {
    LogCvmfs(kLogCache, kLogDebug, "error while opening %s: %s",
             id.ToString().c_str(), strerror(-fd));
    return fd;
  }
  open_fds_[fd].is_volatile = is_volatile;
  if (is_volatile) {
    LogCvmfs(kLogCache, kLogDebug, "hit in volatile entries for %s",
             id.ToString().c_str());
    perf::Inc(counters_.n_openvolatile);
  } else {
    LogCvmfs(kLogCache, kLogDebug, "hit in regular entries for %s",
             id.ToString().c_str());
    perf::Inc(counters_.n_openregular);
  }
  ok = GetStore(open_fds_[fd])->IncRef(id);
  assert(ok);
  return fd;
}

int64_t RamCacheManager::GetSize(int fd) {
  ReadLockGuard guard(rwlock_);
  if (!IsValid(fd)) {
    LogCvmfs(kLogCache, kLogDebug, "bad fd %d on GetSize", fd);
    return -EBADF;
  }
  perf::Inc(counters_.n_getsize);
  return GetStore(open_fds_[fd])->GetSize(open_fds_[fd].handle);
}

int RamCacheManager::Close(int fd) {
  bool rc;

  WriteLockGuard guard(rwlock_);
  if (!IsValid(fd)) {
    LogCvmfs(kLogCache, kLogDebug, "bad fd %d on Close", fd);
    return -EBADF;
  }
  rc = GetStore(open_fds_[fd])->Unref(open_fds_[fd].handle);
  assert(rc);
  open_fds_[fd].handle = kInvalidHandle;

  size_t index = open_fds_[fd].index;
  assert(index < fd_index_.size());
  assert(fd_pivot_ <= fd_index_.size());
  assert(fd_pivot_ > 0);
  --fd_pivot_;
  if (index < fd_pivot_) {
    size_t other = fd_index_[fd_pivot_];
    assert(other < open_fds_.size());
    assert(open_fds_[other].handle != kInvalidHandle);
    open_fds_[other].index = index;
    fd_index_[index] = other;
    fd_index_[fd_pivot_] = fd;
  }
  LogCvmfs(kLogCache, kLogDebug, "closed fd %d", fd);
  perf::Inc(counters_.n_close);
  return 0;
}

int64_t RamCacheManager::Pread(
  int fd,
  void *buf,
  uint64_t size,
  uint64_t offset)
{
  ReadLockGuard guard(rwlock_);
  if (!IsValid(fd)) {
    LogCvmfs(kLogCache, kLogDebug, "bad fd %d on Pread", fd);
    return -EBADF;
  }
  perf::Inc(counters_.n_pread);
  return GetStore(open_fds_[fd])->Read(open_fds_[fd].handle, buf, size, offset);
}

int RamCacheManager::Dup(int fd) {
  bool ok;
  int rc;
  WriteLockGuard guard(rwlock_);
  if (!IsValid(fd)) {
    LogCvmfs(kLogCache, kLogDebug, "bad fd %d on Dup", fd);
    return -EBADF;
  }
  rc = AddFd(open_fds_[fd]);
  if (rc < 0) return rc;
  ok = GetStore(open_fds_[fd])->IncRef(open_fds_[fd].handle);
  assert(ok);
  LogCvmfs(kLogCache, kLogDebug, "dup fd %d", fd);
  perf::Inc(counters_.n_dup);
  return rc;
}

/**
 * For a RAM cache, read-ahead is a no-op.
 */
int RamCacheManager::Readahead(int fd) {
  ReadLockGuard guard(rwlock_);
  if (!IsValid(fd)) {
    LogCvmfs(kLogCache, kLogDebug, "bad fd %d on Readahead", fd);
    return -EBADF;
  }
  LogCvmfs(kLogCache, kLogDebug, "readahead (no-op) on %d", fd);
  perf::Inc(counters_.n_readahead);
  return 0;
}

int RamCacheManager::StartTxn(const shash::Any &id, uint64_t size, void *txn) {
  LogCvmfs(kLogCache, kLogDebug, "new transaction with id %s",
           id.ToString().c_str());
  Transaction *transaction = new (txn) Transaction();
  transaction->id = id;
  transaction->pos = 0;
  transaction->expected_size = size;
  transaction->size = (size == kSizeUnknown) ? kPageSize : size;
  perf::Inc(counters_.n_starttxn);
  return 0;
}

void RamCacheManager::CtrlTxn(
  const string &description,
  const ObjectType type,
  const int flags,
  void *txn)
{
  Transaction *transaction = reinterpret_cast<Transaction *>(txn);
  transaction->description = description;
  if (!transaction->allocated) transaction->object_type = type;
  LogCvmfs(kLogCache, kLogDebug, "modified transaction %s",
           transaction->id.ToString().c_str());
}

int64_t RamCacheManager::Write(const void *buf, uint64_t size, void *txn) {
  Transaction *transaction = reinterpret_cast<Transaction *>(txn);

  /*
   * The initial buffer for the transaction must be allocated on the first
   * write so the caller has time to use CtrlTxn to set regular/volatile.
   * Transactions of unknown size will often be immediately reallocated,
   * but this is no worse than allocate on start.
   */
  if (!transaction->allocated) {
    transaction->buffer = GetTransactionStore(transaction)->MallocBuffer(
      transaction->size);
    assert(!size || transaction->buffer);
    transaction->allocated = true;
  }

  if (transaction->pos + size > transaction->size) {
    if (transaction->expected_size == kSizeUnknown) {
      perf::Inc(counters_.n_realloc);
      transaction->size = max(2*transaction->size, size + transaction->pos);
      LogCvmfs(kLogCache, kLogDebug, "reallocate transaction for %s to %u B",
               transaction->id.ToString().c_str(), transaction->size);
      transaction->buffer = GetTransactionStore(transaction)->ReallocBuffer(
        transaction->buffer, transaction->size);
      assert(transaction->buffer);
    } else {
      LogCvmfs(kLogCache, kLogDebug,
               "attempted to write more than requested (%u>%u)",
               size, transaction->size);
      return -EIO;
    }
  }

  if (transaction->buffer && buf) {
    // LogCvmfs(kLogCache, kLogDebug, "copy %u bytes of transaction %s",
    //          size, transaction->id.ToString().c_str());
    memcpy(static_cast<char *>(transaction->buffer) + transaction->pos,
           buf, size);
  }
  transaction->pos += size;
  perf::Inc(counters_.n_write);
  return size;
}

int RamCacheManager::Reset(void *txn) {
  Transaction *transaction = reinterpret_cast<Transaction *>(txn);
  transaction->pos = 0;
  LogCvmfs(kLogCache, kLogDebug, "reset transaction %s",
           transaction->id.ToString().c_str());
  perf::Inc(counters_.n_reset);
  return 0;
}

int RamCacheManager::OpenFromTxn(void *txn) {
  WriteLockGuard guard(rwlock_);
  Transaction *transaction = reinterpret_cast<Transaction *>(txn);
  int64_t retval = CommitToKvStore(transaction);
  if (retval < 0) {
    LogCvmfs(kLogCache, kLogDebug,
             "error while commiting transaction on %s: %s",
             transaction->id.ToString().c_str(), strerror(-retval));
    return retval;
  }
  LogCvmfs(kLogCache, kLogDebug, "open pending transaction for %s",
           transaction->id.ToString().c_str());
  perf::Inc(counters_.n_committxn);
  return DoOpen(transaction->id);
}

int RamCacheManager::AbortTxn(void *txn) {
  Transaction *transaction = reinterpret_cast<Transaction *>(txn);
  if (transaction->buffer) {
    GetTransactionStore(transaction)->FreeBuffer(transaction->buffer);
  }
  LogCvmfs(kLogCache, kLogDebug, "abort transaction %s",
           transaction->id.ToString().c_str());
  perf::Inc(counters_.n_aborttxn);
  return 0;
}

int RamCacheManager::CommitTxn(void *txn) {
  WriteLockGuard guard(rwlock_);
  Transaction *transaction = reinterpret_cast<Transaction *>(txn);
  perf::Inc(counters_.n_committxn);
  return CommitToKvStore(transaction);
}

int64_t RamCacheManager::CommitToKvStore(Transaction *transaction) {
  MemoryBuffer buf;
  buf.address = transaction->buffer;
  MemoryKvStore *store;
  if (transaction->expected_size == kSizeUnknown) {
    buf.size = transaction->pos;
    if (buf.size > 0) {
      buf.address = GetTransactionStore(transaction)->ReallocBuffer(
        buf.address, buf.size);
      assert(!buf.size || buf.address);
      LogCvmfs(kLogCache, kLogDebug, "reallocating transaction on %s to %u B",
               transaction->id.ToString().c_str(), buf.size);
    }
  } else {
    buf.size = transaction->size;
  }
  buf.object_type = transaction->object_type;

  if (buf.object_type == cache::CacheManager::kTypeVolatile) {
    store = &volatile_entries_;
  } else {
    store = &regular_entries_;
  }
  if (buf.object_type == cache::CacheManager::kTypePinned ||
      buf.object_type == cache::CacheManager::kTypePinned) {
    buf.refcount = 1;
  } else {
    buf.refcount = 0;
  }

  int64_t regular_size = regular_entries_.GetUsed();
  int64_t volatile_size = volatile_entries_.GetUsed();
  int64_t overrun = regular_size + volatile_size + buf.size - max_size_;

  if (overrun > 0) {
    // if we're going to clean the cache, try to remove at least 25%
    overrun = max(overrun, (int64_t) max_size_*3/4);
    perf::Inc(counters_.n_overrun);
    volatile_entries_.ShrinkTo(max((int64_t) 0, volatile_size - overrun));
  }
  overrun -= volatile_size - volatile_entries_.GetUsed();
  if (overrun > 0) {
    regular_entries_.ShrinkTo(max((int64_t) 0, regular_size - overrun));
  }
  if (regular_entries_.GetUsed() + volatile_entries_.GetUsed() > max_size_) {
    LogCvmfs(kLogCache, kLogDebug,
             "transaction for %s would overrun the cache limit",
             transaction->id.ToString().c_str());
    perf::Inc(counters_.n_full);
    return -ENOSPC;
  }

  if (store->Commit(transaction->id, buf)) {
    LogCvmfs(kLogCache, kLogDebug, "committed %s to cache",
             transaction->id.ToString().c_str());
    return 0;
  } else {
    LogCvmfs(kLogCache, kLogDebug,
             "commit on %s failed, kvstore has too many entries",
             transaction->id.ToString().c_str());
    return -ENFILE;
  }
}

}  // namespace cache
<|endoftext|>


<commit_before>#ifndef CONTEXT_HPP_
#define CONTEXT_HPP_

#include <string>
#include <atomic>
#include <memory>

class Context: std::enable_shared_from_this<Context> {
	std::atomic_bool isRunning;
	std::string cwd;

public:

	Context() {
		isRunning.store(false);
	}

	void setCwd(std::string c) { cwd = std::move(c); }
	const std::string& getCwd() const { return cwd; }

	void run() {
		isRunning = true;
	}

	void stop() {
		isRunning = false;
	}

};

#endif /* CONTEXT_HPP_ */
<commit_msg>Add dummy task execution in Context<commit_after>#ifndef CONTEXT_HPP_
#define CONTEXT_HPP_

#include <string>
#include <atomic>
#include <memory>
#include <thread>

class Context: std::enable_shared_from_this<Context> {
	std::atomic_bool isRunning;
	std::string cwd;

public:

	Context() {
		isRunning.store(false);
	}

	void setCwd(std::string c) { cwd = std::move(c); }
	const std::string& getCwd() const { return cwd; }

	void run() {
		isRunning = true;
		std::thread t(
				[&](){
				std::system("ls -la");
				}
		);
	}

	void stop() {
		isRunning = false;
	}

};

#endif /* CONTEXT_HPP_ */
<|endoftext|>


<commit_before>//****************************************************************************//
// bone.cpp                                                                   //
// Copyright (C) 2001, 2002 Bruno 'Beosil' Heidelberger                       //
//****************************************************************************//
// This library is free software; you can redistribute it and/or modify it    //
// under the terms of the GNU Lesser General Public License as published by   //
// the Free Software Foundation; either version 2.1 of the License, or (at    //
// your option) any later version.                                            //
//****************************************************************************//

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "cal3d/error.h"
#include "cal3d/bone.h"
#include "cal3d/coremesh.h"
#include "cal3d/coresubmesh.h"
#include "cal3d/corebone.h"
#include "cal3d/matrix.h"
#include "cal3d/skeleton.h"
#include "cal3d/coreskeleton.h"

cal3d::TransformAccumulator::TransformAccumulator() {
    totalWeight = 0;
}

void cal3d::TransformAccumulator::reset(const RotateTranslate& defaultPose) {
    totalWeight = 0;
    currentTransform = defaultPose;
}

void cal3d::TransformAccumulator::addTransform(float weight, const RotateTranslate& transform) {
    if (weight) {
        totalWeight += weight;
        float factor = weight / totalWeight;
        // I'm not comfortable asserting these, given floating point
        // math.  For example, imagine that totalWeight is HUGE and
        // weight is small.  Would dividing produce a zero factor?
        // cal3d::verify(factor > 0.0f, "factor must be positive");
        // cal3d::verify(factor <= 1.0f, "factor cannot exceed 1.0f");
        currentTransform = blend(factor, currentTransform, transform);
    }
}

CalBone::CalBone(const CalCoreBone& coreBone)
    : parentId(coreBone.parentId)
    , coreRelativeTransform(coreBone.relativeTransform)
    , coreInverseBindPoseTransform(coreBone.inverseBindPoseTransform)
{
    resetPose();
}

void CalBone::resetPose() {
    transformAccumulator.reset(coreRelativeTransform); // if no animations are applied, use this
    m_accumulatedReplacementAttenuation = 1.0f;
    m_meshScaleAbsolute.set(1, 1, 1);
}

/*****************************************************************************/
/** Interpolates the current state to another state.
  *
  * This function interpolates the current state (relative translation and
  * rotation) of the bone instance to another state of a given weight.
  *
  * @param unrampedWeight The blending weight, not incorporating ramp value
  * @param translation The relative translation to be interpolated to.
  * @param rotation The relative rotation to be interpolated to.
  * @param scale Optional scale from 0-1 applies to transformation directly without affecting weights.
  * @param replace If true, subsequent animations will have their weight attenuated by 1 - rampValue.
  * @param rampValue Amount to attenuate weight when ramping in/out the animation.
  *****************************************************************************/

void CalBone::blendPose(
    float unrampedWeight,
    const cal3d::RotateTranslate& transform,
    bool replace,
    float rampValue
) {
    const float attenuatedWeight = rampValue * unrampedWeight * m_accumulatedReplacementAttenuation;
    if (attenuatedWeight) {
        if (replace) {
            m_accumulatedReplacementAttenuation *= (1.0f - rampValue);
        }

        transformAccumulator.addTransform(attenuatedWeight, transform);
    }
}

BoneTransform CalBone::calculateAbsolutePose(const CalBone* bones, bool includeRootTransform) {
    if (parentId == -1) {
        if (includeRootTransform) {
            // no parent, this means absolute state == relative state
            absoluteTransform = getRelativeTransform();
        } else {
            absoluteTransform = cal3d::RotateTranslate();
        }
    } else {
        absoluteTransform = bones[parentId].absoluteTransform * getRelativeTransform();
    }

    if (m_meshScaleAbsolute.x != 1 || m_meshScaleAbsolute.y != 1 || m_meshScaleAbsolute.z != 1) {
        absoluteTransform = absoluteTransform * cal3d::Scale(m_meshScaleAbsolute);
    }

    return absoluteTransform * coreInverseBindPoseTransform;
}
<commit_msg>This multiplication should be closer to weighted addTransform.  I think I can simplify attenuatedWeight next...<commit_after>//****************************************************************************//
// bone.cpp                                                                   //
// Copyright (C) 2001, 2002 Bruno 'Beosil' Heidelberger                       //
//****************************************************************************//
// This library is free software; you can redistribute it and/or modify it    //
// under the terms of the GNU Lesser General Public License as published by   //
// the Free Software Foundation; either version 2.1 of the License, or (at    //
// your option) any later version.                                            //
//****************************************************************************//

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "cal3d/error.h"
#include "cal3d/bone.h"
#include "cal3d/coremesh.h"
#include "cal3d/coresubmesh.h"
#include "cal3d/corebone.h"
#include "cal3d/matrix.h"
#include "cal3d/skeleton.h"
#include "cal3d/coreskeleton.h"

cal3d::TransformAccumulator::TransformAccumulator() {
    totalWeight = 0;
}

void cal3d::TransformAccumulator::reset(const RotateTranslate& defaultPose) {
    totalWeight = 0;
    currentTransform = defaultPose;
}

void cal3d::TransformAccumulator::addTransform(float weight, const RotateTranslate& transform) {
    if (weight) {
        totalWeight += weight;
        float factor = weight / totalWeight;
        // I'm not comfortable asserting these, given floating point
        // math.  For example, imagine that totalWeight is HUGE and
        // weight is small.  Would dividing produce a zero factor?
        // cal3d::verify(factor > 0.0f, "factor must be positive");
        // cal3d::verify(factor <= 1.0f, "factor cannot exceed 1.0f");
        currentTransform = blend(factor, currentTransform, transform);
    }
}

CalBone::CalBone(const CalCoreBone& coreBone)
    : parentId(coreBone.parentId)
    , coreRelativeTransform(coreBone.relativeTransform)
    , coreInverseBindPoseTransform(coreBone.inverseBindPoseTransform)
{
    resetPose();
}

void CalBone::resetPose() {
    transformAccumulator.reset(coreRelativeTransform); // if no animations are applied, use this
    m_accumulatedReplacementAttenuation = 1.0f;
    m_meshScaleAbsolute.set(1, 1, 1);
}

/*****************************************************************************/
/** Interpolates the current state to another state.
  *
  * This function interpolates the current state (relative translation and
  * rotation) of the bone instance to another state of a given weight.
  *
  * @param unrampedWeight The blending weight, not incorporating ramp value
  * @param translation The relative translation to be interpolated to.
  * @param rotation The relative rotation to be interpolated to.
  * @param scale Optional scale from 0-1 applies to transformation directly without affecting weights.
  * @param replace If true, subsequent animations will have their weight attenuated by 1 - rampValue.
  * @param rampValue Amount to attenuate weight when ramping in/out the animation.
  *****************************************************************************/

void CalBone::blendPose(
    float unrampedWeight,
    const cal3d::RotateTranslate& transform,
    bool replace,
    float rampValue
) {
    const float attenuatedWeight = rampValue * m_accumulatedReplacementAttenuation;
    if (attenuatedWeight) {
        if (replace) {
            m_accumulatedReplacementAttenuation *= (1.0f - rampValue);
        }

        transformAccumulator.addTransform(unrampedWeight * attenuatedWeight, transform);
    }
}

BoneTransform CalBone::calculateAbsolutePose(const CalBone* bones, bool includeRootTransform) {
    if (parentId == -1) {
        if (includeRootTransform) {
            // no parent, this means absolute state == relative state
            absoluteTransform = getRelativeTransform();
        } else {
            absoluteTransform = cal3d::RotateTranslate();
        }
    } else {
        absoluteTransform = bones[parentId].absoluteTransform * getRelativeTransform();
    }

    if (m_meshScaleAbsolute.x != 1 || m_meshScaleAbsolute.y != 1 || m_meshScaleAbsolute.z != 1) {
        absoluteTransform = absoluteTransform * cal3d::Scale(m_meshScaleAbsolute);
    }

    return absoluteTransform * coreInverseBindPoseTransform;
}
<|endoftext|>