<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, 16*particle_layer_thickness/.2032, 540);
	//num_per_dir = I3(90, 1, 100);
	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));

	//=========================================================================================================
	//////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>Does setting min threads help, not sure<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, 16*particle_layer_thickness/.2032, 540);
	//num_per_dir = I3(90, 1, 100);
	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));

	//=========================================================================================================
	//////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;
}

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2012 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"

#include "ScrollingCoordinator.h"

#include "FrameTestHelpers.h"
#include "GraphicsLayerChromium.h"
#include "RenderLayerBacking.h"
#include "RenderLayerCompositor.h"
#include "RenderView.h"
#include "URLTestHelpers.h"
#include "WebCompositorInitializer.h"
#include "WebFrameClient.h"
#include "WebFrameImpl.h"
#include "WebSettings.h"
#include "WebViewClient.h"
#include "WebViewImpl.h"
#include <gtest/gtest.h>
#include <public/Platform.h>
#include <public/WebLayer.h>
#include <public/WebLayerTreeView.h>
#include <public/WebUnitTestSupport.h>

using namespace WebCore;
using namespace WebKit;

namespace {

class FakeWebViewClient : public WebViewClient {
public:
    virtual void initializeLayerTreeView()
    {
        m_layerTreeView = adoptPtr(Platform::current()->unitTestSupport()->createLayerTreeViewForTesting(WebUnitTestSupport::TestViewTypeUnitTest));
        ASSERT(m_layerTreeView);
    }

    virtual WebLayerTreeView* layerTreeView()
    {
        return m_layerTreeView.get();
    }

private:
    OwnPtr<WebLayerTreeView> m_layerTreeView;
};

class MockWebFrameClient : public WebFrameClient {
};

class ScrollingCoordinatorChromiumTest : public testing::Test {
public:
    ScrollingCoordinatorChromiumTest()
        : m_baseURL("http://www.test.com/")
        , m_compositorInitializer(0)
    {
        // We cannot reuse FrameTestHelpers::createWebViewAndLoad here because the compositing
        // settings need to be set before the page is loaded.
        m_webViewImpl = static_cast<WebViewImpl*>(WebView::create(&m_mockWebViewClient));
        m_webViewImpl->settings()->setJavaScriptEnabled(true);
        m_webViewImpl->settings()->setForceCompositingMode(true);
        m_webViewImpl->settings()->setAcceleratedCompositingEnabled(true);
        m_webViewImpl->settings()->setAcceleratedCompositingForFixedPositionEnabled(true);
        m_webViewImpl->settings()->setAcceleratedCompositingForOverflowScrollEnabled(true);
        m_webViewImpl->settings()->setAcceleratedCompositingForScrollableFramesEnabled(true);
        m_webViewImpl->settings()->setCompositedScrollingForFramesEnabled(true);
        m_webViewImpl->settings()->setFixedPositionCreatesStackingContext(true);
        m_webViewImpl->initializeMainFrame(&m_mockWebFrameClient);
        m_webViewImpl->resize(IntSize(320, 240));
    }

    virtual ~ScrollingCoordinatorChromiumTest()
    {
        Platform::current()->unitTestSupport()->unregisterAllMockedURLs();
        m_webViewImpl->close();
    }

    void navigateTo(const std::string& url)
    {
        FrameTestHelpers::loadFrame(m_webViewImpl->mainFrame(), url);
        Platform::current()->unitTestSupport()->serveAsynchronousMockedRequests();
    }

    void registerMockedHttpURLLoad(const std::string& fileName)
    {
        URLTestHelpers::registerMockedURLFromBaseURL(WebString::fromUTF8(m_baseURL.c_str()), WebString::fromUTF8(fileName.c_str()));
    }

    WebLayer* getRootScrollLayer()
    {
        RenderLayerCompositor* compositor = m_webViewImpl->mainFrameImpl()->frame()->contentRenderer()->compositor();
        ASSERT(compositor);
        ASSERT(compositor->scrollLayer());

        WebLayer* webScrollLayer = static_cast<WebLayer*>(compositor->scrollLayer()->platformLayer());
        return webScrollLayer;
    }

protected:
    std::string m_baseURL;
    MockWebFrameClient m_mockWebFrameClient;
    FakeWebViewClient m_mockWebViewClient;
    WebViewImpl* m_webViewImpl;
    WebKitTests::WebCompositorInitializer m_compositorInitializer;
};

TEST_F(ScrollingCoordinatorChromiumTest, fastScrollingByDefault)
{
    navigateTo("about:blank");

    // Make sure the scrolling coordinator is active.
    FrameView* frameView = m_webViewImpl->mainFrameImpl()->frameView();
    Page* page = m_webViewImpl->mainFrameImpl()->frame()->page();
    ASSERT_TRUE(page->scrollingCoordinator());
    ASSERT_TRUE(page->scrollingCoordinator()->coordinatesScrollingForFrameView(frameView));

    // Fast scrolling should be enabled by default.
    WebLayer* rootScrollLayer = getRootScrollLayer();
    ASSERT_TRUE(rootScrollLayer->scrollable());
    ASSERT_FALSE(rootScrollLayer->shouldScrollOnMainThread());
    ASSERT_FALSE(rootScrollLayer->haveWheelEventHandlers());
}

TEST_F(ScrollingCoordinatorChromiumTest, fastScrollingForFixedPosition)
{
    registerMockedHttpURLLoad("fixed-position.html");
    navigateTo(m_baseURL + "fixed-position.html");

    Page* page = m_webViewImpl->mainFrameImpl()->frame()->page();
    ASSERT_TRUE(page->scrollingCoordinator()->supportsFixedPositionLayers());

    // Fixed position should not fall back to main thread scrolling.
    WebLayer* rootScrollLayer = getRootScrollLayer();
    ASSERT_FALSE(rootScrollLayer->shouldScrollOnMainThread());

    // Verify the properties of the fixed position element starting from the RenderObject all the
    // way to the WebLayer.
    Element* fixedElement = m_webViewImpl->mainFrameImpl()->frame()->document()->getElementById("fixed");
    ASSERT(fixedElement);

    RenderObject* renderer = fixedElement->renderer();
    ASSERT_TRUE(renderer->isBoxModelObject());
    ASSERT_TRUE(renderer->hasLayer());

    RenderLayer* layer = toRenderBoxModelObject(renderer)->layer();
    ASSERT_TRUE(layer->isComposited());

    RenderLayerBacking* layerBacking = layer->backing();
    WebLayer* webLayer = static_cast<WebLayer*>(layerBacking->graphicsLayer()->platformLayer());
    ASSERT_TRUE(webLayer->fixedToContainerLayer());
}

TEST_F(ScrollingCoordinatorChromiumTest, nonFastScrollableRegion)
{
    registerMockedHttpURLLoad("non-fast-scrollable.html");
    navigateTo(m_baseURL + "non-fast-scrollable.html");

    WebLayer* rootScrollLayer = getRootScrollLayer();
    WebVector<WebRect> nonFastScrollableRegion = rootScrollLayer->nonFastScrollableRegion();

    ASSERT_EQ(1u, nonFastScrollableRegion.size());
    ASSERT_EQ(WebRect(8, 8, 10, 10), nonFastScrollableRegion[0]);
}

TEST_F(ScrollingCoordinatorChromiumTest, wheelEventHandler)
{
    registerMockedHttpURLLoad("wheel-event-handler.html");
    navigateTo(m_baseURL + "wheel-event-handler.html");

    WebLayer* rootScrollLayer = getRootScrollLayer();
    ASSERT_TRUE(rootScrollLayer->haveWheelEventHandlers());
}

TEST_F(ScrollingCoordinatorChromiumTest, clippedBodyTest)
{
    registerMockedHttpURLLoad("clipped-body.html");
    navigateTo(m_baseURL + "clipped-body.html");

    WebLayer* rootScrollLayer = getRootScrollLayer();
    ASSERT_EQ(0u, rootScrollLayer->nonFastScrollableRegion().size());
}

TEST_F(ScrollingCoordinatorChromiumTest, overflowScrolling)
{
    registerMockedHttpURLLoad("overflow-scrolling.html");
    navigateTo(m_baseURL + "overflow-scrolling.html");

    // Verify the properties of the accelerated scrolling element starting from the RenderObject
    // all the way to the WebLayer.
    Element* scrollableElement = m_webViewImpl->mainFrameImpl()->frame()->document()->getElementById("scrollable");
    ASSERT(scrollableElement);

    RenderObject* renderer = scrollableElement->renderer();
    ASSERT_TRUE(renderer->isBoxModelObject());
    ASSERT_TRUE(renderer->hasLayer());

    RenderLayer* layer = toRenderBoxModelObject(renderer)->layer();
    ASSERT_TRUE(layer->usesCompositedScrolling());
    ASSERT_TRUE(layer->isComposited());

    RenderLayerBacking* layerBacking = layer->backing();
    ASSERT_TRUE(layerBacking->hasScrollingLayer());
    ASSERT(layerBacking->scrollingContentsLayer());

    GraphicsLayerChromium* graphicsLayerChromium = static_cast<GraphicsLayerChromium*>(layerBacking->scrollingContentsLayer());
    ASSERT_EQ(layer, graphicsLayerChromium->scrollableArea());

    WebLayer* webScrollLayer = static_cast<WebLayer*>(layerBacking->scrollingContentsLayer()->platformLayer());
    ASSERT_TRUE(webScrollLayer->scrollable());

#if !OS(DARWIN) && !OS(WINDOWS)
    // Now verify we've attached impl-side scrollbars onto the scrollbar layers
    ASSERT_TRUE(layerBacking->layerForHorizontalScrollbar());
    ASSERT_TRUE(layerBacking->layerForHorizontalScrollbar()->hasContentsLayer());
    ASSERT_TRUE(layerBacking->layerForVerticalScrollbar());
    ASSERT_TRUE(layerBacking->layerForVerticalScrollbar()->hasContentsLayer());
#endif
}

TEST_F(ScrollingCoordinatorChromiumTest, iframeScrolling)
{
    registerMockedHttpURLLoad("iframe-scrolling.html");
    registerMockedHttpURLLoad("iframe-scrolling-inner.html");
    navigateTo(m_baseURL + "iframe-scrolling.html");

    // Verify the properties of the accelerated scrolling element starting from the RenderObject
    // all the way to the WebLayer.
    Element* scrollableFrame = m_webViewImpl->mainFrameImpl()->frame()->document()->getElementById("scrollable");
    ASSERT_TRUE(scrollableFrame);

    RenderObject* renderer = scrollableFrame->renderer();
    ASSERT_TRUE(renderer);
    ASSERT_TRUE(renderer->isWidget());

    RenderWidget* renderWidget = toRenderWidget(renderer);
    ASSERT_TRUE(renderWidget);
    ASSERT_TRUE(renderWidget->widget());
    ASSERT_TRUE(renderWidget->widget()->isFrameView());

    FrameView* innerFrameView = toFrameView(renderWidget->widget());
    RenderView* innerRenderView = innerFrameView->renderView();
    ASSERT_TRUE(innerRenderView);

    RenderLayerCompositor* innerCompositor = innerRenderView->compositor();
    ASSERT_TRUE(innerCompositor->inCompositingMode());
    ASSERT_TRUE(innerCompositor->scrollLayer());

    GraphicsLayerChromium* scrollLayer = static_cast<GraphicsLayerChromium*>(innerCompositor->scrollLayer());
    ASSERT_EQ(innerFrameView, scrollLayer->scrollableArea());

    WebLayer* webScrollLayer = static_cast<WebLayer*>(scrollLayer->platformLayer());
    ASSERT_TRUE(webScrollLayer->scrollable());

#if !OS(DARWIN) && !OS(WINDOWS)
    // Now verify we've attached impl-side scrollbars onto the scrollbar layers
    ASSERT_TRUE(innerCompositor->layerForHorizontalScrollbar());
    ASSERT_TRUE(innerCompositor->layerForHorizontalScrollbar()->hasContentsLayer());
    ASSERT_TRUE(innerCompositor->layerForVerticalScrollbar());
    ASSERT_TRUE(innerCompositor->layerForVerticalScrollbar()->hasContentsLayer());
#endif
}

TEST_F(ScrollingCoordinatorChromiumTest, rtlIframe)
{
    registerMockedHttpURLLoad("rtl-iframe.html");
    registerMockedHttpURLLoad("rtl-iframe-inner.html");
    navigateTo(m_baseURL + "rtl-iframe.html");

    // Verify the properties of the accelerated scrolling element starting from the RenderObject
    // all the way to the WebLayer.
    Element* scrollableFrame = m_webViewImpl->mainFrameImpl()->frame()->document()->getElementById("scrollable");
    ASSERT_TRUE(scrollableFrame);

    RenderObject* renderer = scrollableFrame->renderer();
    ASSERT_TRUE(renderer);
    ASSERT_TRUE(renderer->isWidget());

    RenderWidget* renderWidget = toRenderWidget(renderer);
    ASSERT_TRUE(renderWidget);
    ASSERT_TRUE(renderWidget->widget());
    ASSERT_TRUE(renderWidget->widget()->isFrameView());

    FrameView* innerFrameView = static_cast<FrameView*>(renderWidget->widget());
    RenderView* innerRenderView = innerFrameView->renderView();
    ASSERT_TRUE(innerRenderView);

    RenderLayerCompositor* innerCompositor = innerRenderView->compositor();
    ASSERT_TRUE(innerCompositor->inCompositingMode());
    ASSERT_TRUE(innerCompositor->scrollLayer());

    GraphicsLayerChromium* scrollLayer = static_cast<GraphicsLayerChromium*>(innerCompositor->scrollLayer());
    ASSERT_EQ(innerFrameView, scrollLayer->scrollableArea());

    WebLayer* webScrollLayer = static_cast<WebLayer*>(scrollLayer->platformLayer());
    ASSERT_TRUE(webScrollLayer->scrollable());

    ASSERT_EQ(973, webScrollLayer->scrollPosition().x);
    ASSERT_EQ(973, webScrollLayer->maxScrollPosition().width);
}

TEST_F(ScrollingCoordinatorChromiumTest, setupScrollbarLayerShouldNotCrash)
{
    registerMockedHttpURLLoad("setup_scrollbar_layer_crash.html");
    navigateTo(m_baseURL + "setup_scrollbar_layer_crash.html");
    // This test document setup an iframe with scrollbars, then switch to
    // an empty document by javascript.
}

} // namespace
<commit_msg>Fix webkit unit test failure from r148395<commit_after>/*
 * Copyright (C) 2012 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"

#include "ScrollingCoordinator.h"

#include "FrameTestHelpers.h"
#include "GraphicsLayerChromium.h"
#include "RenderLayerBacking.h"
#include "RenderLayerCompositor.h"
#include "RenderView.h"
#include "URLTestHelpers.h"
#include "WebCompositorInitializer.h"
#include "WebFrameClient.h"
#include "WebFrameImpl.h"
#include "WebSettings.h"
#include "WebViewClient.h"
#include "WebViewImpl.h"
#include <gtest/gtest.h>
#include <public/Platform.h>
#include <public/WebLayer.h>
#include <public/WebLayerTreeView.h>
#include <public/WebUnitTestSupport.h>

using namespace WebCore;
using namespace WebKit;

namespace {

class FakeWebViewClient : public WebViewClient {
public:
    virtual void initializeLayerTreeView()
    {
        m_layerTreeView = adoptPtr(Platform::current()->unitTestSupport()->createLayerTreeViewForTesting(WebUnitTestSupport::TestViewTypeUnitTest));
        ASSERT(m_layerTreeView);
    }

    virtual WebLayerTreeView* layerTreeView()
    {
        return m_layerTreeView.get();
    }

private:
    OwnPtr<WebLayerTreeView> m_layerTreeView;
};

class MockWebFrameClient : public WebFrameClient {
};

class ScrollingCoordinatorChromiumTest : public testing::Test {
public:
    ScrollingCoordinatorChromiumTest()
        : m_baseURL("http://www.test.com/")
        , m_compositorInitializer(0)
    {
        // We cannot reuse FrameTestHelpers::createWebViewAndLoad here because the compositing
        // settings need to be set before the page is loaded.
        m_webViewImpl = static_cast<WebViewImpl*>(WebView::create(&m_mockWebViewClient));
        m_webViewImpl->settings()->setJavaScriptEnabled(true);
        m_webViewImpl->settings()->setForceCompositingMode(true);
        m_webViewImpl->settings()->setAcceleratedCompositingEnabled(true);
        m_webViewImpl->settings()->setAcceleratedCompositingForFixedPositionEnabled(true);
        m_webViewImpl->settings()->setAcceleratedCompositingForOverflowScrollEnabled(true);
        m_webViewImpl->settings()->setAcceleratedCompositingForScrollableFramesEnabled(true);
        m_webViewImpl->settings()->setCompositedScrollingForFramesEnabled(true);
        m_webViewImpl->settings()->setFixedPositionCreatesStackingContext(true);
        m_webViewImpl->initializeMainFrame(&m_mockWebFrameClient);
        m_webViewImpl->resize(IntSize(320, 240));
    }

    virtual ~ScrollingCoordinatorChromiumTest()
    {
        Platform::current()->unitTestSupport()->unregisterAllMockedURLs();
        m_webViewImpl->close();
    }

    void navigateTo(const std::string& url)
    {
        FrameTestHelpers::loadFrame(m_webViewImpl->mainFrame(), url);
        Platform::current()->unitTestSupport()->serveAsynchronousMockedRequests();
    }

    void registerMockedHttpURLLoad(const std::string& fileName)
    {
        URLTestHelpers::registerMockedURLFromBaseURL(WebString::fromUTF8(m_baseURL.c_str()), WebString::fromUTF8(fileName.c_str()));
    }

    WebLayer* getRootScrollLayer()
    {
        RenderLayerCompositor* compositor = m_webViewImpl->mainFrameImpl()->frame()->contentRenderer()->compositor();
        ASSERT(compositor);
        ASSERT(compositor->scrollLayer());

        WebLayer* webScrollLayer = static_cast<WebLayer*>(compositor->scrollLayer()->platformLayer());
        return webScrollLayer;
    }

protected:
    std::string m_baseURL;
    MockWebFrameClient m_mockWebFrameClient;
    FakeWebViewClient m_mockWebViewClient;
    WebViewImpl* m_webViewImpl;
    WebKitTests::WebCompositorInitializer m_compositorInitializer;
};

TEST_F(ScrollingCoordinatorChromiumTest, fastScrollingByDefault)
{
    navigateTo("about:blank");

    // Make sure the scrolling coordinator is active.
    FrameView* frameView = m_webViewImpl->mainFrameImpl()->frameView();
    Page* page = m_webViewImpl->mainFrameImpl()->frame()->page();
    ASSERT_TRUE(page->scrollingCoordinator());
    ASSERT_TRUE(page->scrollingCoordinator()->coordinatesScrollingForFrameView(frameView));

    // Fast scrolling should be enabled by default.
    WebLayer* rootScrollLayer = getRootScrollLayer();
    ASSERT_TRUE(rootScrollLayer->scrollable());
    ASSERT_FALSE(rootScrollLayer->shouldScrollOnMainThread());
    ASSERT_FALSE(rootScrollLayer->haveWheelEventHandlers());
}

TEST_F(ScrollingCoordinatorChromiumTest, fastScrollingForFixedPosition)
{
    registerMockedHttpURLLoad("fixed-position.html");
    navigateTo(m_baseURL + "fixed-position.html");

    Page* page = m_webViewImpl->mainFrameImpl()->frame()->page();
    ASSERT_TRUE(page->scrollingCoordinator()->supportsFixedPositionLayers());

    // Fixed position should not fall back to main thread scrolling.
    WebLayer* rootScrollLayer = getRootScrollLayer();
    ASSERT_FALSE(rootScrollLayer->shouldScrollOnMainThread());

    // Verify the properties of the fixed position element starting from the RenderObject all the
    // way to the WebLayer.
    Element* fixedElement = m_webViewImpl->mainFrameImpl()->frame()->document()->getElementById("fixed");
    ASSERT(fixedElement);

    RenderObject* renderer = fixedElement->renderer();
    ASSERT_TRUE(renderer->isBoxModelObject());
    ASSERT_TRUE(renderer->hasLayer());

    RenderLayer* layer = toRenderBoxModelObject(renderer)->layer();
    ASSERT_TRUE(layer->isComposited());

    RenderLayerBacking* layerBacking = layer->backing();
    WebLayer* webLayer = static_cast<WebLayer*>(layerBacking->graphicsLayer()->platformLayer());
    ASSERT_TRUE(webLayer->fixedToContainerLayer());
}

TEST_F(ScrollingCoordinatorChromiumTest, nonFastScrollableRegion)
{
    registerMockedHttpURLLoad("non-fast-scrollable.html");
    navigateTo(m_baseURL + "non-fast-scrollable.html");

    WebLayer* rootScrollLayer = getRootScrollLayer();
    WebVector<WebRect> nonFastScrollableRegion = rootScrollLayer->nonFastScrollableRegion();

    ASSERT_EQ(1u, nonFastScrollableRegion.size());
    ASSERT_EQ(WebRect(8, 8, 10, 10), nonFastScrollableRegion[0]);
}

TEST_F(ScrollingCoordinatorChromiumTest, wheelEventHandler)
{
    registerMockedHttpURLLoad("wheel-event-handler.html");
    navigateTo(m_baseURL + "wheel-event-handler.html");

    WebLayer* rootScrollLayer = getRootScrollLayer();
    ASSERT_TRUE(rootScrollLayer->haveWheelEventHandlers());
}

TEST_F(ScrollingCoordinatorChromiumTest, clippedBodyTest)
{
    registerMockedHttpURLLoad("clipped-body.html");
    navigateTo(m_baseURL + "clipped-body.html");

    WebLayer* rootScrollLayer = getRootScrollLayer();
    ASSERT_EQ(0u, rootScrollLayer->nonFastScrollableRegion().size());
}

TEST_F(ScrollingCoordinatorChromiumTest, overflowScrolling)
{
    registerMockedHttpURLLoad("overflow-scrolling.html");
    navigateTo(m_baseURL + "overflow-scrolling.html");

    // Verify the properties of the accelerated scrolling element starting from the RenderObject
    // all the way to the WebLayer.
    Element* scrollableElement = m_webViewImpl->mainFrameImpl()->frame()->document()->getElementById("scrollable");
    ASSERT(scrollableElement);

    RenderObject* renderer = scrollableElement->renderer();
    ASSERT_TRUE(renderer->isBoxModelObject());
    ASSERT_TRUE(renderer->hasLayer());

    RenderLayer* layer = toRenderBoxModelObject(renderer)->layer();
    ASSERT_TRUE(layer->usesCompositedScrolling());
    ASSERT_TRUE(layer->isComposited());

    RenderLayerBacking* layerBacking = layer->backing();
    ASSERT_TRUE(layerBacking->hasScrollingLayer());
    ASSERT(layerBacking->scrollingContentsLayer());

    GraphicsLayerChromium* graphicsLayerChromium = static_cast<GraphicsLayerChromium*>(layerBacking->scrollingContentsLayer());
    ASSERT_EQ(layer, graphicsLayerChromium->scrollableArea());

    WebLayer* webScrollLayer = static_cast<WebLayer*>(layerBacking->scrollingContentsLayer()->platformLayer());
    ASSERT_TRUE(webScrollLayer->scrollable());

#if OS(ANDROID)
    // Now verify we've attached impl-side scrollbars onto the scrollbar layers
    ASSERT_TRUE(layerBacking->layerForHorizontalScrollbar());
    ASSERT_TRUE(layerBacking->layerForHorizontalScrollbar()->hasContentsLayer());
    ASSERT_TRUE(layerBacking->layerForVerticalScrollbar());
    ASSERT_TRUE(layerBacking->layerForVerticalScrollbar()->hasContentsLayer());
#endif
}

TEST_F(ScrollingCoordinatorChromiumTest, iframeScrolling)
{
    registerMockedHttpURLLoad("iframe-scrolling.html");
    registerMockedHttpURLLoad("iframe-scrolling-inner.html");
    navigateTo(m_baseURL + "iframe-scrolling.html");

    // Verify the properties of the accelerated scrolling element starting from the RenderObject
    // all the way to the WebLayer.
    Element* scrollableFrame = m_webViewImpl->mainFrameImpl()->frame()->document()->getElementById("scrollable");
    ASSERT_TRUE(scrollableFrame);

    RenderObject* renderer = scrollableFrame->renderer();
    ASSERT_TRUE(renderer);
    ASSERT_TRUE(renderer->isWidget());

    RenderWidget* renderWidget = toRenderWidget(renderer);
    ASSERT_TRUE(renderWidget);
    ASSERT_TRUE(renderWidget->widget());
    ASSERT_TRUE(renderWidget->widget()->isFrameView());

    FrameView* innerFrameView = toFrameView(renderWidget->widget());
    RenderView* innerRenderView = innerFrameView->renderView();
    ASSERT_TRUE(innerRenderView);

    RenderLayerCompositor* innerCompositor = innerRenderView->compositor();
    ASSERT_TRUE(innerCompositor->inCompositingMode());
    ASSERT_TRUE(innerCompositor->scrollLayer());

    GraphicsLayerChromium* scrollLayer = static_cast<GraphicsLayerChromium*>(innerCompositor->scrollLayer());
    ASSERT_EQ(innerFrameView, scrollLayer->scrollableArea());

    WebLayer* webScrollLayer = static_cast<WebLayer*>(scrollLayer->platformLayer());
    ASSERT_TRUE(webScrollLayer->scrollable());

#if OS(ANDROID)
    // Now verify we've attached impl-side scrollbars onto the scrollbar layers
    ASSERT_TRUE(innerCompositor->layerForHorizontalScrollbar());
    ASSERT_TRUE(innerCompositor->layerForHorizontalScrollbar()->hasContentsLayer());
    ASSERT_TRUE(innerCompositor->layerForVerticalScrollbar());
    ASSERT_TRUE(innerCompositor->layerForVerticalScrollbar()->hasContentsLayer());
#endif
}

TEST_F(ScrollingCoordinatorChromiumTest, rtlIframe)
{
    registerMockedHttpURLLoad("rtl-iframe.html");
    registerMockedHttpURLLoad("rtl-iframe-inner.html");
    navigateTo(m_baseURL + "rtl-iframe.html");

    // Verify the properties of the accelerated scrolling element starting from the RenderObject
    // all the way to the WebLayer.
    Element* scrollableFrame = m_webViewImpl->mainFrameImpl()->frame()->document()->getElementById("scrollable");
    ASSERT_TRUE(scrollableFrame);

    RenderObject* renderer = scrollableFrame->renderer();
    ASSERT_TRUE(renderer);
    ASSERT_TRUE(renderer->isWidget());

    RenderWidget* renderWidget = toRenderWidget(renderer);
    ASSERT_TRUE(renderWidget);
    ASSERT_TRUE(renderWidget->widget());
    ASSERT_TRUE(renderWidget->widget()->isFrameView());

    FrameView* innerFrameView = static_cast<FrameView*>(renderWidget->widget());
    RenderView* innerRenderView = innerFrameView->renderView();
    ASSERT_TRUE(innerRenderView);

    RenderLayerCompositor* innerCompositor = innerRenderView->compositor();
    ASSERT_TRUE(innerCompositor->inCompositingMode());
    ASSERT_TRUE(innerCompositor->scrollLayer());

    GraphicsLayerChromium* scrollLayer = static_cast<GraphicsLayerChromium*>(innerCompositor->scrollLayer());
    ASSERT_EQ(innerFrameView, scrollLayer->scrollableArea());

    WebLayer* webScrollLayer = static_cast<WebLayer*>(scrollLayer->platformLayer());
    ASSERT_TRUE(webScrollLayer->scrollable());

    ASSERT_EQ(973, webScrollLayer->scrollPosition().x);
    ASSERT_EQ(973, webScrollLayer->maxScrollPosition().width);
}

TEST_F(ScrollingCoordinatorChromiumTest, setupScrollbarLayerShouldNotCrash)
{
    registerMockedHttpURLLoad("setup_scrollbar_layer_crash.html");
    navigateTo(m_baseURL + "setup_scrollbar_layer_crash.html");
    // This test document setup an iframe with scrollbars, then switch to
    // an empty document by javascript.
}

} // namespace
<|endoftext|>


<commit_before>/// Project specific
#include <Manager/AI/AIPathManager.hpp>
#include <EntityComponent/EntityHandler.hpp>
#include <PlayerHandler.hpp>
#include <Helper/ProximityChecker.hpp>
#include <EntityComponent/Components/HealthComponent.hpp>
#include <EntityComponent/Components/RigidBodyComponent.hpp>
#include <EntityComponent/Components/TransformComponent.hpp>
#include <EntityComponent/Components/PotentialFieldComponent.hpp>
#include <EntityComponent/Components/MovementComponent.hpp>
#include <EntityComponent/Components/AIGroupComponent.hpp>
#include <Doremi/Core/Include/PotentialFieldGridCreator.hpp>
#include <EntityComponent/Components/PhysicsMaterialComponent.hpp>
// Events
#include <EventHandler/EventHandler.hpp>
#include <EventHandler/Events/EntityCreatedEvent.hpp>
#include <EventHandler/Events/PlayerCreationEvent.hpp>

// Engine
#include <DoremiEngine/Physics/Include/PhysicsModule.hpp>
#include <DoremiEngine/Physics/Include/RigidBodyManager.hpp>
#include <DoremiEngine/Physics/Include/PhysicsMaterialManager.hpp>
#include <DoremiEngine/Physics/Include/RayCastManager.hpp>
#include <DoremiEngine/AI/Include/Interface/PotentialField/PotentialFieldActor.hpp>
#include <DoremiEngine/AI/Include/Interface/PotentialField/PotentialField.hpp>
#include <DoremiEngine/AI/Include/Interface/PotentialField/PotentialGroup.hpp>
#include <DoremiEngine/AI/Include/Interface/SubModule/PotentialFieldSubModule.hpp>
#include <DoremiEngine/AI/Include/AIModule.hpp>

// Standard
#include <iostream>
#include <DirectXMath.h>
#include <set>

using namespace std;

namespace Doremi
{
    namespace Core
    {
        AIPathManager::AIPathManager(const DoremiEngine::Core::SharedContext& p_sharedContext) : Manager(p_sharedContext, "AIPathManager")
        {
            // TODOKO do this in a better place, might not work to have here in the future
            m_field =
                m_sharedContext.GetAIModule().GetPotentialFieldSubModule().CreateNewField(250, 230, 50, 50,
                                                                                XMFLOAT3(-60, 5.0f, -40)); // Fits for first platform
            m_topField =
                m_sharedContext.GetAIModule().GetPotentialFieldSubModule().CreateNewField(350, 500, 50, 50,
                    XMFLOAT3(-280, 150.0f, -85)); // Fits for top platform
            EventHandler::GetInstance()->Subscribe(EventType::AiGroupActorCreation, this);
            EventHandler::GetInstance()->Subscribe(EventType::PotentialFieldActorCreation, this);
            EventHandler::GetInstance()->Subscribe(EventType::PlayerCreation, this);
            //////////////////////// Fixa PotFlt

            // Testar TODOEA
            Core::EntityHandler& t_entityHandler = Core::EntityHandler::GetInstance();
            PotentialFieldGridCreator t_potentialFieldGridCreator = PotentialFieldGridCreator(m_sharedContext);
            t_potentialFieldGridCreator.BuildGridUsingPhysicXAndGrid(m_field);
            std::cout << "Physical field 1 done";
            m_field->Update();
            std::cout << "Potential field 1 done";

            t_potentialFieldGridCreator.BuildGridUsingPhysicXAndGrid(m_topField);
            std::cout << "Physical field 2 done";
            m_topField->Update();
            std::cout << "Potential field 2 done";
            /// debugskit

            //&& render pos rigidbody, potentialfield
        }

        AIPathManager::~AIPathManager() {}

        void AIPathManager::Update(double p_dt)
        {
            size_t length = EntityHandler::GetInstance().GetLastEntityIndex();

            // TODOKO Test wall
            if(firstUpdate)
            {
                firstUpdate = false;
            }
            for(size_t i = 0; i < length; i++)
            {
                // Update actors position, should perhaps not be here...
                if(EntityHandler::GetInstance().HasComponents(i, (int)ComponentType::PotentialField | (int)ComponentType::Transform))
                { // This is so the player updates his position too...
                    DoremiEngine::AI::PotentialFieldActor* actor = EntityHandler::GetInstance().GetComponentFromStorage<PotentialFieldComponent>(i)->ChargedActor;
                    XMFLOAT3 pos = EntityHandler::GetInstance().GetComponentFromStorage<TransformComponent>(i)->position;
                    actor->SetPosition(pos);
                }
                if(EntityHandler::GetInstance().HasComponents(i, (int)ComponentType::AIAgent | (int)ComponentType::Transform |
                                                                     (int)ComponentType::Movement | (int)ComponentType::AIGroup | (int)ComponentType::PotentialField))
                {
                    // Get the needed components
                    XMFLOAT2 desiredPos;
                    XMFLOAT3 unitPos = EntityHandler::GetInstance().GetComponentFromStorage<TransformComponent>(i)->position;
                    DoremiEngine::AI::PotentialGroup* group = EntityHandler::GetInstance().GetComponentFromStorage<AIGroupComponent>(i)->Group;
                    DoremiEngine::AI::PotentialFieldActor* currentActor = EntityHandler::GetInstance().GetComponentFromStorage<PotentialFieldComponent>(i)->ChargedActor;
                    DoremiEngine::AI::PotentialField* field = EntityHandler::GetInstance().GetComponentFromStorage<PotentialFieldComponent>(i)->Field;
                    // TODOEA BORDE SPARA UNDAN O INTE KOLLA X O Y EFTER VARANN

                    if (currentActor->GetPrevGridPos().x == field->WhatGridPosAmIOn(currentActor->GetPosition()).x && currentActor->GetPrevGridPos().y == field->WhatGridPosAmIOn(currentActor->GetPosition()).y)
                    {
                        //DEBUG
                        int hej = 0;

                        // Remove the first in the list om vi skulle anvnda oss av delta_T fr att uppdatera trailen med hjlp av den om ngon str still.
                        // Do nothing
                    }
                    else
                    {
                        //DEBUG
                        std::vector<XMINT2> hej = currentActor->GetPhermoneTrail();

                        XMINT2 hej1 = currentActor->GetPrevGridPos();
                        // Add the previous gridPos to the trail.
                        // TODOEA This will make the Ai move as the game starts.

                        currentActor->UpdatePhermoneTrail(currentActor->GetPrevGridPos());
                        //DEBUG
                        //XMINT2 newPrevPos = field->WhatGridPosAmIOn(currentActor->GetPosition());
                        XMINT2 newPrevPos = field->WhatGridPosAmIOn(currentActor->GetPosition());
                        currentActor->SetPrevGridPosition(newPrevPos);
                    }
                    if(field != nullptr)
                    {
                        desiredPos = field->GetAttractionPosition(unitPos, currentActor, false);
                    }
                    XMFLOAT3 desiredPos3D = XMFLOAT3(desiredPos.x, unitPos.y, desiredPos.y); // The fields impact
                   // XMFLOAT3 groupImpact = group->GetForceDirection(unitPos, currentActor); // The groups impact
                   // XMVECTOR groupImpactVec = XMLoadFloat3(&groupImpact);
                    XMVECTOR desiredPosVec = XMLoadFloat3(&desiredPos3D);
                    XMVECTOR unitPosVec = XMLoadFloat3(&unitPos);
                    XMVECTOR dirVec = desiredPosVec - unitPosVec;
                    dirVec = XMVector3Normalize(dirVec);
                   // dirVec += groupImpactVec * 0.2f; // TODOKO remove this variable!! Its there to make the static field more influencial
                   //  dirVec = XMVector3Normalize(dirVec);
                    XMFLOAT3 direction;
                    XMStoreFloat3(&direction, dirVec * 0.2f); // TODOKO remove this hard coded shiat
                    MovementComponent* moveComp = EntityHandler::GetInstance().GetComponentFromStorage<MovementComponent>(i);
                    moveComp->movement = direction;

                }
            }
        }
        void AIPathManager::OnEvent(Event* p_event)
        {
            switch(p_event->eventType)
            {
                case Doremi::Core::EventType::PotentialFieldActorCreation:
                {
                    EntityCreatedEvent* realEvent = static_cast<EntityCreatedEvent*>(p_event);
                    if(EntityHandler::GetInstance().HasComponents(realEvent->entityID, (int)ComponentType::PotentialField)) // Make sure the entity
                    // contains the needed
                    // stuff
                    {
                        DoremiEngine::AI::PotentialFieldActor* actor =
                            EntityHandler::GetInstance().GetComponentFromStorage<PotentialFieldComponent>(realEvent->entityID)->ChargedActor;
                        m_field->AddActor(actor);
                    }
                    else
                    {
                        // TODOKO Log error
                    }
                    break;
                }
                case Doremi::Core::EventType::AiGroupActorCreation:
                {
                    EntityCreatedEvent* realEvent = static_cast<EntityCreatedEvent*>(p_event);
                    if(EntityHandler::GetInstance().HasComponents(realEvent->entityID, (int)ComponentType::PotentialField | (int)ComponentType::AIGroup)) // Make sure the entity contains the needed stuff
                    {
                        DoremiEngine::AI::PotentialFieldActor* actor =
                            EntityHandler::GetInstance().GetComponentFromStorage<PotentialFieldComponent>(realEvent->entityID)->ChargedActor;
                        DoremiEngine::AI::PotentialField* field;
                        DoremiEngine::AI::PotentialGroup* group =
                            EntityHandler::GetInstance().GetComponentFromStorage<AIGroupComponent>(realEvent->entityID)->Group;
                        if(group == nullptr)
                        {
                            // TODOKO Log error and what happens
                            group = m_sharedContext.GetAIModule().GetPotentialFieldSubModule().CreateNewPotentialGroup();
                        }
                        group->AddActor(actor);
                        // TODOKO should not be done here but in a more suitable event
                        field = m_sharedContext.GetAIModule().GetPotentialFieldSubModule().FindBestPotentialField(actor->GetPosition());
                        EntityHandler::GetInstance().GetComponentFromStorage<PotentialFieldComponent>(realEvent->entityID)->Field = field;
                    }
                    else
                    {
                        // TODOKO Log error
                    }
                    break;
                }
                case Doremi::Core::EventType::PlayerCreation:
                {
                    PlayerCreationEvent* realEvent = static_cast<PlayerCreationEvent*>(p_event);
                    if(EntityHandler::GetInstance().HasComponents(realEvent->playerEntityID, (int)ComponentType::PotentialField)) // Make sure the
                    // entity contains
                    // the needed stuff
                    {
                        DoremiEngine::AI::PotentialFieldActor* actor =
                            EntityHandler::GetInstance().GetComponentFromStorage<PotentialFieldComponent>(realEvent->playerEntityID)->ChargedActor;
                        m_field->AddActor(actor);
                        m_topField->AddActor(actor);
                    }
                    else
                    {
                        // TODOKO log error
                    }
                    break;
                }
                default:
                    break;
            }
        }
    }
}<commit_msg>Removed AI bug with phermonnetrail<commit_after>/// Project specific
#include <Manager/AI/AIPathManager.hpp>
#include <EntityComponent/EntityHandler.hpp>
#include <PlayerHandler.hpp>
#include <Helper/ProximityChecker.hpp>
#include <EntityComponent/Components/HealthComponent.hpp>
#include <EntityComponent/Components/RigidBodyComponent.hpp>
#include <EntityComponent/Components/TransformComponent.hpp>
#include <EntityComponent/Components/PotentialFieldComponent.hpp>
#include <EntityComponent/Components/MovementComponent.hpp>
#include <EntityComponent/Components/AIGroupComponent.hpp>
#include <Doremi/Core/Include/PotentialFieldGridCreator.hpp>
#include <EntityComponent/Components/PhysicsMaterialComponent.hpp>
// Events
#include <EventHandler/EventHandler.hpp>
#include <EventHandler/Events/EntityCreatedEvent.hpp>
#include <EventHandler/Events/PlayerCreationEvent.hpp>

// Engine
#include <DoremiEngine/Physics/Include/PhysicsModule.hpp>
#include <DoremiEngine/Physics/Include/RigidBodyManager.hpp>
#include <DoremiEngine/Physics/Include/PhysicsMaterialManager.hpp>
#include <DoremiEngine/Physics/Include/RayCastManager.hpp>
#include <DoremiEngine/AI/Include/Interface/PotentialField/PotentialFieldActor.hpp>
#include <DoremiEngine/AI/Include/Interface/PotentialField/PotentialField.hpp>
#include <DoremiEngine/AI/Include/Interface/PotentialField/PotentialGroup.hpp>
#include <DoremiEngine/AI/Include/Interface/SubModule/PotentialFieldSubModule.hpp>
#include <DoremiEngine/AI/Include/AIModule.hpp>

// Standard
#include <iostream>
#include <DirectXMath.h>
#include <set>

using namespace std;

namespace Doremi
{
    namespace Core
    {
        AIPathManager::AIPathManager(const DoremiEngine::Core::SharedContext& p_sharedContext) : Manager(p_sharedContext, "AIPathManager")
        {
            // TODOKO do this in a better place, might not work to have here in the future
            m_field =
                m_sharedContext.GetAIModule().GetPotentialFieldSubModule().CreateNewField(250, 230, 50, 50,
                                                                                XMFLOAT3(-60, 5.0f, -40)); // Fits for first platform
            m_topField =
                m_sharedContext.GetAIModule().GetPotentialFieldSubModule().CreateNewField(350, 500, 50, 50,
                    XMFLOAT3(-280, 150.0f, -85)); // Fits for top platform
            EventHandler::GetInstance()->Subscribe(EventType::AiGroupActorCreation, this);
            EventHandler::GetInstance()->Subscribe(EventType::PotentialFieldActorCreation, this);
            EventHandler::GetInstance()->Subscribe(EventType::PlayerCreation, this);
            //////////////////////// Fixa PotFlt

            // Testar TODOEA
            Core::EntityHandler& t_entityHandler = Core::EntityHandler::GetInstance();
            PotentialFieldGridCreator t_potentialFieldGridCreator = PotentialFieldGridCreator(m_sharedContext);
            t_potentialFieldGridCreator.BuildGridUsingPhysicXAndGrid(m_field);
            std::cout << "Physical field 1 done";
            m_field->Update();
            std::cout << "Potential field 1 done";

            t_potentialFieldGridCreator.BuildGridUsingPhysicXAndGrid(m_topField);
            std::cout << "Physical field 2 done";
            m_topField->Update();
            std::cout << "Potential field 2 done";
            /// debugskit

            //&& render pos rigidbody, potentialfield
        }

        AIPathManager::~AIPathManager() {}

        void AIPathManager::Update(double p_dt)
        {
            size_t length = EntityHandler::GetInstance().GetLastEntityIndex();

            // TODOKO Test wall
            if(firstUpdate)
            {
                firstUpdate = false;
            }
            for(size_t i = 0; i < length; i++)
            {
                // Update actors position, should perhaps not be here...
                if(EntityHandler::GetInstance().HasComponents(i, (int)ComponentType::PotentialField | (int)ComponentType::Transform))
                { // This is so the player updates his position too...
                    DoremiEngine::AI::PotentialFieldActor* actor = EntityHandler::GetInstance().GetComponentFromStorage<PotentialFieldComponent>(i)->ChargedActor;
                    XMFLOAT3 pos = EntityHandler::GetInstance().GetComponentFromStorage<TransformComponent>(i)->position;
                    actor->SetPosition(pos);
                }
                if(EntityHandler::GetInstance().HasComponents(i, (int)ComponentType::AIAgent | (int)ComponentType::Transform |
                                                                     (int)ComponentType::Movement | (int)ComponentType::AIGroup | (int)ComponentType::PotentialField))
                {
                    // Get the needed components
                    XMFLOAT2 desiredPos;
                    XMFLOAT3 unitPos = EntityHandler::GetInstance().GetComponentFromStorage<TransformComponent>(i)->position;
                    DoremiEngine::AI::PotentialGroup* group = EntityHandler::GetInstance().GetComponentFromStorage<AIGroupComponent>(i)->Group;
                    DoremiEngine::AI::PotentialFieldActor* currentActor = EntityHandler::GetInstance().GetComponentFromStorage<PotentialFieldComponent>(i)->ChargedActor;
                    DoremiEngine::AI::PotentialField* field = EntityHandler::GetInstance().GetComponentFromStorage<PotentialFieldComponent>(i)->Field;
                    // TODOEA BORDE SPARA UNDAN O INTE KOLLA X O Y EFTER VARANN

                    //if (currentActor->GetPrevGridPos().x == field->WhatGridPosAmIOn(currentActor->GetPosition()).x && currentActor->GetPrevGridPos().y == field->WhatGridPosAmIOn(currentActor->GetPosition()).y)
                    //{
                    //    //DEBUG
                    //    int hej = 0;

                    //    // Remove the first in the list om vi skulle anvnda oss av delta_T fr att uppdatera trailen med hjlp av den om ngon str still.
                    //    // Do nothing
                    //}
                    //else
                    //{
                    //    //DEBUG
                    //    std::vector<XMINT2> hej = currentActor->GetPhermoneTrail();

                    //    XMINT2 hej1 = currentActor->GetPrevGridPos();
                    //    // Add the previous gridPos to the trail.
                    //    // TODOEA This will make the Ai move as the game starts.

                    //    currentActor->UpdatePhermoneTrail(currentActor->GetPrevGridPos());
                    //    //DEBUG
                    //    //XMINT2 newPrevPos = field->WhatGridPosAmIOn(currentActor->GetPosition());
                    //    XMINT2 newPrevPos = field->WhatGridPosAmIOn(currentActor->GetPosition());
                    //    currentActor->SetPrevGridPosition(newPrevPos);
                    //}
                    if(field != nullptr)
                    {
                        desiredPos = field->GetAttractionPosition(unitPos, currentActor, false);
                    }
                    XMFLOAT3 desiredPos3D = XMFLOAT3(desiredPos.x, unitPos.y, desiredPos.y); // The fields impact
                   // XMFLOAT3 groupImpact = group->GetForceDirection(unitPos, currentActor); // The groups impact
                   // XMVECTOR groupImpactVec = XMLoadFloat3(&groupImpact);
                    XMVECTOR desiredPosVec = XMLoadFloat3(&desiredPos3D);
                    XMVECTOR unitPosVec = XMLoadFloat3(&unitPos);
                    XMVECTOR dirVec = desiredPosVec - unitPosVec;
                    dirVec = XMVector3Normalize(dirVec);
                   // dirVec += groupImpactVec * 0.2f; // TODOKO remove this variable!! Its there to make the static field more influencial
                   //  dirVec = XMVector3Normalize(dirVec);
                    XMFLOAT3 direction;
                    XMStoreFloat3(&direction, dirVec * 0.2f); // TODOKO remove this hard coded shiat
                    MovementComponent* moveComp = EntityHandler::GetInstance().GetComponentFromStorage<MovementComponent>(i);
                    moveComp->movement = direction;

                }
            }
        }
        void AIPathManager::OnEvent(Event* p_event)
        {
            switch(p_event->eventType)
            {
                case Doremi::Core::EventType::PotentialFieldActorCreation:
                {
                    EntityCreatedEvent* realEvent = static_cast<EntityCreatedEvent*>(p_event);
                    if(EntityHandler::GetInstance().HasComponents(realEvent->entityID, (int)ComponentType::PotentialField)) // Make sure the entity
                    // contains the needed
                    // stuff
                    {
                        DoremiEngine::AI::PotentialFieldActor* actor =
                            EntityHandler::GetInstance().GetComponentFromStorage<PotentialFieldComponent>(realEvent->entityID)->ChargedActor;
                        m_field->AddActor(actor);
                    }
                    else
                    {
                        // TODOKO Log error
                    }
                    break;
                }
                case Doremi::Core::EventType::AiGroupActorCreation:
                {
                    EntityCreatedEvent* realEvent = static_cast<EntityCreatedEvent*>(p_event);
                    if(EntityHandler::GetInstance().HasComponents(realEvent->entityID, (int)ComponentType::PotentialField | (int)ComponentType::AIGroup)) // Make sure the entity contains the needed stuff
                    {
                        DoremiEngine::AI::PotentialFieldActor* actor =
                            EntityHandler::GetInstance().GetComponentFromStorage<PotentialFieldComponent>(realEvent->entityID)->ChargedActor;
                        DoremiEngine::AI::PotentialField* field;
                        DoremiEngine::AI::PotentialGroup* group =
                            EntityHandler::GetInstance().GetComponentFromStorage<AIGroupComponent>(realEvent->entityID)->Group;
                        if(group == nullptr)
                        {
                            // TODOKO Log error and what happens
                            group = m_sharedContext.GetAIModule().GetPotentialFieldSubModule().CreateNewPotentialGroup();
                        }
                        group->AddActor(actor);
                        // TODOKO should not be done here but in a more suitable event
                        field = m_sharedContext.GetAIModule().GetPotentialFieldSubModule().FindBestPotentialField(actor->GetPosition());
                        EntityHandler::GetInstance().GetComponentFromStorage<PotentialFieldComponent>(realEvent->entityID)->Field = field;
                    }
                    else
                    {
                        // TODOKO Log error
                    }
                    break;
                }
                case Doremi::Core::EventType::PlayerCreation:
                {
                    PlayerCreationEvent* realEvent = static_cast<PlayerCreationEvent*>(p_event);
                    if(EntityHandler::GetInstance().HasComponents(realEvent->playerEntityID, (int)ComponentType::PotentialField)) // Make sure the
                    // entity contains
                    // the needed stuff
                    {
                        DoremiEngine::AI::PotentialFieldActor* actor =
                            EntityHandler::GetInstance().GetComponentFromStorage<PotentialFieldComponent>(realEvent->playerEntityID)->ChargedActor;
                        m_field->AddActor(actor);
                        m_topField->AddActor(actor);
                    }
                    else
                    {
                        // TODOKO log error
                    }
                    break;
                }
                default:
                    break;
            }
        }
    }
}<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <climits>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <string>
#include <map>
using namespace std;

/* FLAGS */
static int n_flag;
static int min_flag;
static int max_flag;
static int mean_flag;
static int sum_flag;
static int sd_flag;
static int population_flag;
static int sample_flag;
static int comp_flag;
static int var_flag;
static int help_flag;

/* DATA STRUCTURES */
vector<long double> * stats = new vector<long double>();
vector<long double> * points = new vector<long double>();
map<string, long double> * global_stats = new map<string, long double>();
map<string,int> * opts = new map<string, int>();

//running stats needed
void compute_line_stats(vector<long double> * stats){
	long double stat = (*stats).at(0);

	//sum
	(*stats).at(1) += stat;

	//N
	(*stats).at(4)+=1;

	//min
	if ((*stats).at(2) > stat){
		(*stats).at(2) = stat;
	}

	//max
	if ((*stats).at(3) < stat){
		(*stats).at(3) = stat;
	}
}

void print_help(){
}

//global descriptive statistics
void compute_global_stats(){
	//mean
	long double mean = (*stats).at(1) / (*stats).at(4);
	long double n = (*stats).at(4);

	//sum of squared deviations
	long double sum = 0;
	//for compensated variant
	long double sum3 = 0;
	for (long index=0; index<(long)(*points).size(); ++index){
		long double diff = (*points).at(index) - mean;
		sum += (diff * diff);
		sum3 += diff;
	}

	//for compensated variant biased
	long double comp_var_s = (sum-((sum3*sum3)/n))/n;

	//for compensated variant unbiased when n is not equal to |population|
	long double comp_var_p = (sum-((sum3*sum3)/n))/n-1;

	//sample sd comp
	long double samp_sd_comp = sqrt(comp_var_s);

	//pop sd comp
	long double pop_sd_comp = sqrt(comp_var_p);

	//sample variance
	long double var_s = sum/n;

	//population variance
	long double var_p = sum/(n-1);

	//sample sd
	long double samp_sd = sqrt(var_s);

	//pop sd
	long double pop_sd = sqrt(var_p);

	//init global_stats

	(*global_stats)["N"] = n;
	(*global_stats)["mean"] = mean;

	(*global_stats)["sampl_sd"] = samp_sd;
	(*global_stats)["pop_sd"] = pop_sd;

	(*global_stats)["pop_sd_comp"] = pop_sd_comp;
	(*global_stats)["samp_sd_comp"] = samp_sd_comp;

	(*global_stats)["sum"] = (*stats).at(1);
	(*global_stats)["min"] = (*stats).at(2);
	(*global_stats)["max"] = (*stats).at(3);

	if( (*opts).find("population") != (*opts).end() && (*opts).find("compensated") != (*opts).end()){
		(*global_stats)["sd"] = pop_sd_comp;
		(*global_stats)["var"] = comp_var_p;
	}
	if( (*opts).find("population") != (*opts).end() && (*opts).find("compensated") == (*opts).end() ) {
		(*global_stats)["sd"] = pop_sd;
		(*global_stats)["var"] = var_p;
	}
	if( (*opts).find("population") == (*opts).end() && (*opts).find("compensated") != (*opts).end()){
		(*global_stats)["sd"] = samp_sd_comp;
		(*global_stats)["var"] = comp_var_s;
	}
	if( (*opts).find("population") == (*opts).end() && (*opts).find("compensated") == (*opts).end() ) {
		(*global_stats)["sd"] = samp_sd;
		(*global_stats)["var"] = var_s;
	}

}

void print_stats(){

	vector<string> opts_ordered;
	opts_ordered.push_back("N");
	opts_ordered.push_back("min");
	opts_ordered.push_back("max");
	opts_ordered.push_back("sum");
	opts_ordered.push_back("mean");
	opts_ordered.push_back("sd");
	opts_ordered.push_back("var");

	string output = " ";

	for(vector<string>::iterator ii=opts_ordered.begin(); ii!=opts_ordered.end();++ii){
		if ( (*opts).find(*ii)  ==  (*opts).end())
			continue;
		cout << *ii << "\t";

	}
	cout<<endl;
	for(vector<string>::iterator ii=opts_ordered.begin(); ii!=opts_ordered.end();++ii){
		if ( (*opts).find(*ii)  ==  (*opts).end())
			continue;
		cout << (*global_stats)[*ii] << "\t";
	}
	cout<<endl;
}

void set_flags(int argc, char **argv, map<string,int>  * opts){
	int c;
	while (1){
	   static struct option long_options[] = {
	       /* These options set a flag. */
	       {"sum", no_argument,       &sum_flag, 1},
	       {"min",   no_argument,       &min_flag, 1},
	       {"max",   no_argument,       &max_flag, 1},
	       {"mean",   no_argument,       &mean_flag, 1},
	       {"sd",   no_argument,       &sd_flag, 1},
	       {"var",   no_argument,       &var_flag, 1},
	       {"n",   no_argument,       &n_flag, 1},
	       {"population",   no_argument,       &population_flag, 1},
	       {"sample",   no_argument,       &sample_flag, 1},
	       {"compensated",   no_argument,       &comp_flag, 1},
	     };
	   /* getopt_long stores the option index here. */
	   int option_index = 0;

	   c = getopt_long (argc, argv, "abc:d:f:",
			    long_options, &option_index);

	   /* Detect the end of the options. */
	   if (c == -1)
	     break;

	   switch (c)
	     {
	     case 0:
	       /* If this option set a flag, do nothing else now. */
	       if (long_options[option_index].flag != 0)
		 break;
	       printf ("option %s", long_options[option_index].name);
	       if (optarg)
		 printf (" with arg %s", optarg);
	       printf ("\n");
	       break;

	     case '?':
	       /* getopt_long already printed an error message. */
	       break;

	     default:
	       abort ();
	     }
	 }

	if (sum_flag)
		(*opts)["sum"] = 1;
	if (n_flag)
		(*opts)["N"] = 1;
	if (min_flag)
		(*opts)["min"] = 1;
	if (max_flag)
		(*opts)["max"] = 1;
	if (sd_flag)
		(*opts)["sd"] = 1;
	if (comp_flag)
		(*opts)["compensated"] = 1;
	if (sample_flag)
		(*opts)["sample"] = 1;
	if (population_flag)
		(*opts)["population"] = 1;
	if (mean_flag)
		(*opts)["mean"] = 1;
	if (var_flag)
		(*opts)["var"] = 1;
	if (help_flag)
		print_help();

       /* Print any remaining command line arguments (not options). */
	if (optind < argc){
           printf ("non-option ARGV-elements: ");
           while (optind < argc)
             printf ("%s ", argv[optind++]);
           putchar ('\n');
	}

	/**
	If opts is empty, print out all info, and assume sample statistics
	**/
	if((*opts).size()==0){
		(*opts)["sum"] = 1;
		(*opts)["N"] = 1;
		(*opts)["min"] = 1;
		(*opts)["max"] = 1;
		(*opts)["mean"] = 1;
		(*opts)["sd"] = 1;
	}

}

int main (int argc, char **argv){
	set_flags(argc, argv,opts);
	long double sum = 0;
	long double n = 0;
	long double min = INT_MAX;
	long double max = INT_MIN;
	long double mean = 0;
	long double sd = 0;

	(*stats).push_back(sum);
	(*stats).push_back(sum);
	(*stats).push_back(min);
	(*stats).push_back(max);
	(*stats).push_back(n);
	(*stats).push_back(mean);
	(*stats).push_back(sd);

	while(cin){
		string input_line;
		getline(cin,input_line);
		if(input_line=="") continue;
		long double stat = (long double) ::atof(input_line.c_str());
		(*stats).at(0) = stat;
		compute_line_stats(stats);
		(*points).push_back(stat);
	}
	compute_global_stats();
	print_stats();

	delete points;
	delete stats;
	delete global_stats;
	delete opts;
	return 0;
}

<commit_msg>Various small changes<commit_after>#include <iostream>
#include <vector>
#include <climits>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <string>
#include <map>
using namespace std;

/* FLAGS */
static int n_flag;
static int min_flag;
static int max_flag;
static int mean_flag;
static int sum_flag;
static int sd_flag;
static int population_flag;
static int sample_flag;
static int comp_flag;
static int var_flag;
static int help_flag;

/* DATA STRUCTURES */
vector<long double> * stats = new vector<long double>();
vector<long double> * points = new vector<long double>();
map<string, long double> * global_stats = new map<string, long double>();
map<string,int> * opts = new map<string, int>();

/* STATS COMPUTED AT THE LINE */
void compute_line_stats(){
	long double stat = (*stats).at(0);

	//sum
	(*stats).at(1) += stat;

	//N
	(*stats).at(4)+=1;

	//min
	if ((*stats).at(2) > stat){
		(*stats).at(2) = stat;
	}

	//max
	if ((*stats).at(3) < stat){
		(*stats).at(3) = stat;
	}
}

void print_help(){
}

/* COMPUTE GLOBAL STATS */
void compute_global_stats(){
	//mean
	long double mean = (*stats).at(1) / (*stats).at(4);
	long double n = (*stats).at(4);

	//sum of squared deviations
	long double sum = 0;
	//for compensated variant
	long double sum3 = 0;
	for (long index=0; index<(long)(*points).size(); ++index){
		long double diff = (*points).at(index) - mean;
		sum += (diff * diff);
		sum3 += diff;
	}

	//for compensated variant biased
	long double comp_var_s = (sum-((sum3*sum3)/n))/n;

	//for compensated variant unbiased when n is not equal to |population|
	long double comp_var_p = (sum-((sum3*sum3)/n))/n-1;

	//sample sd comp
	long double samp_sd_comp = sqrt(comp_var_s);

	//pop sd comp
	long double pop_sd_comp = sqrt(comp_var_p);

	//sample variance
	long double var_s = sum/n;

	//population variance
	long double var_p = sum/(n-1);

	//sample sd
	long double samp_sd = sqrt(var_s);

	//pop sd
	long double pop_sd = sqrt(var_p);

	//init global_stats

	(*global_stats)["N"] = n;
	(*global_stats)["mean"] = mean;

	(*global_stats)["sampl_sd"] = samp_sd;
	(*global_stats)["pop_sd"] = pop_sd;

	(*global_stats)["pop_sd_comp"] = pop_sd_comp;
	(*global_stats)["samp_sd_comp"] = samp_sd_comp;

	(*global_stats)["sum"] = (*stats).at(1);
	(*global_stats)["min"] = (*stats).at(2);
	(*global_stats)["max"] = (*stats).at(3);

	if( (*opts).find("population") != (*opts).end() && (*opts).find("compensated") != (*opts).end()){
		(*global_stats)["sd"] = pop_sd_comp;
		(*global_stats)["var"] = comp_var_p;
	}
	if( (*opts).find("population") != (*opts).end() && (*opts).find("compensated") == (*opts).end() ) {
		(*global_stats)["sd"] = pop_sd;
		(*global_stats)["var"] = var_p;
	}
	if( (*opts).find("population") == (*opts).end() && (*opts).find("compensated") != (*opts).end()){
		(*global_stats)["sd"] = samp_sd_comp;
		(*global_stats)["var"] = comp_var_s;
	}
	if( (*opts).find("population") == (*opts).end() && (*opts).find("compensated") == (*opts).end() ) {
		(*global_stats)["sd"] = samp_sd;
		(*global_stats)["var"] = var_s;
	}

}

void print_stats(){

	vector<string> opts_ordered;
	opts_ordered.push_back("N");
	opts_ordered.push_back("min");
	opts_ordered.push_back("max");
	opts_ordered.push_back("sum");
	opts_ordered.push_back("mean");
	opts_ordered.push_back("sd");
	opts_ordered.push_back("var");

	string output = " ";

	for(vector<string>::iterator ii=opts_ordered.begin(); ii!=opts_ordered.end();++ii){
		if ( (*opts).find(*ii)  ==  (*opts).end())
			continue;
		cout << *ii << "\t";

	}
	cout<<endl;
	for(vector<string>::iterator ii=opts_ordered.begin(); ii!=opts_ordered.end();++ii){
		if ( (*opts).find(*ii)  ==  (*opts).end())
			continue;
		cout << (*global_stats)[*ii] << "\t";
	}
	cout<<endl;
}

void read_parameters(int argc, char **argv){
	int c;
	while (1){
	   static struct option long_options[] = {
	       /* These options set a flag. */
	       {"sum", no_argument,       &sum_flag, 1},
	       {"min",   no_argument,       &min_flag, 1},
	       {"max",   no_argument,       &max_flag, 1},
	       {"mean",   no_argument,       &mean_flag, 1},
	       {"sd",   no_argument,       &sd_flag, 1},
	       {"var",   no_argument,       &var_flag, 1},
	       {"n",   no_argument,       &n_flag, 1},
	       {"population",   no_argument,       &population_flag, 1},
	       {"sample",   no_argument,       &sample_flag, 1},
	       {"compensated",   no_argument,       &comp_flag, 1},
	     };
	   /* getopt_long stores the option index here. */
	   int option_index = 0;

	   c = getopt_long (argc, argv, "abc:d:f:",
			    long_options, &option_index);

	   /* Detect the end of the options. */
	   if (c == -1)
	     break;

	   switch (c)
	     {
	     case 0:
	       /* If this option set a flag, do nothing else now. */
	       if (long_options[option_index].flag != 0)
		 break;
	       printf ("option %s", long_options[option_index].name);
	       if (optarg)
		 printf (" with arg %s", optarg);
	       printf ("\n");
	       break;

	     case '?':
	       /* getopt_long already printed an error message. */
	       break;

	     default:
	       abort ();
	     }
	 }

	if (sum_flag)
		(*opts)["sum"] = 1;
	if (n_flag)
		(*opts)["N"] = 1;
	if (min_flag)
		(*opts)["min"] = 1;
	if (max_flag)
		(*opts)["max"] = 1;
	if (sd_flag)
		(*opts)["sd"] = 1;
	if (comp_flag)
		(*opts)["compensated"] = 1;
	if (sample_flag)
		(*opts)["sample"] = 1;
	if (population_flag)
		(*opts)["population"] = 1;
	if (mean_flag)
		(*opts)["mean"] = 1;
	if (var_flag)
		(*opts)["var"] = 1;
	if (help_flag)
		print_help();

       /* Print any remaining command line arguments (not options). */
	if (optind < argc){
           printf ("non-option ARGV-elements: ");
           while (optind < argc)
             printf ("%s ", argv[optind++]);
           putchar ('\n');
	}

	/**
	If opts is empty, print out all info, and assume sample statistics
	**/
	if((*opts).size()==0){
		(*opts)["sum"] = 1;
		(*opts)["N"] = 1;
		(*opts)["min"] = 1;
		(*opts)["max"] = 1;
		(*opts)["mean"] = 1;
		(*opts)["sd"] = 1;
	}

}

int main (int argc, char **argv){
	read_parameters(argc, argv);
	long double sum = 0;
	long double n = 0;
	long double min = INT_MAX;
	long double max = INT_MIN;
	long double mean = 0;
	long double sd = 0;

	(*stats).push_back(sum);
	(*stats).push_back(sum);
	(*stats).push_back(min);
	(*stats).push_back(max);
	(*stats).push_back(n);
	(*stats).push_back(mean);
	(*stats).push_back(sd);

	while(cin){
		string input_line;
		getline(cin,input_line);
		if(input_line=="") continue;
		long double stat = (long double) ::atof(input_line.c_str());
		(*stats).at(0) = stat;
		compute_line_stats();
		(*points).push_back(stat);
	}
	compute_global_stats();
	print_stats();

	delete points;
	delete stats;
	delete global_stats;
	delete opts;
	return 0;
}

<|endoftext|>


<commit_before>#include "QXmppRemoteMethod.h"
#include "QXmppClient.h"
#include "QXmppUtils.h"
#include "QXmppConfiguration.h"

#include <QEventLoop>
#include <QTimer>

QXmppRemoteMethod::QXmppRemoteMethod(const QString &jid, const QString &method, const QVariantList &args, QXmppClient *client) :
        QObject(client), m_client(client)
{
    m_payload.setId( generateStanzaHash() );
    m_payload.setTo( jid );
    m_payload.setFrom( client->getConfiguration().getJid() );
    m_payload.setInterface( method.section('.', 0 ) );
    m_payload.setMethod( method.section('.', 1) );
    m_payload.setPayload( args );
}

QXmppRemoteMethodResult QXmppRemoteMethod::call( )
{
    QEventLoop loop(this);
    connect( this, SIGNAL(callDone()), &loop, SLOT(quit()));
    QTimer::singleShot(30000,&loop, SLOT(quit())); // Timeout incase the other end hangs...

    m_client->sendPacket( m_payload );

    loop.exec( QEventLoop::ExcludeUserInputEvents | QEventLoop::WaitForMoreEvents );
    return m_result;
}

void QXmppRemoteMethod::gotError( const QXmppRpcErrorIq &iq )
{
    if ( iq.getId() == m_payload.getId() )
    {
        m_result.hasError = true;
        m_result.errorMessage = iq.getError().getText();
        m_result.code = iq.getError().getType();
        emit callDone();
    }
}

void QXmppRemoteMethod::gotResult( const QXmppRpcResponseIq &iq )
{
    if ( iq.getId() == m_payload.getId() )
    {
        m_result.hasError = false;
        m_result.result = iq.getPayload();
        emit callDone();
    }
}
<commit_msg>Split interfaces correctly<commit_after>#include "QXmppRemoteMethod.h"
#include "QXmppClient.h"
#include "QXmppUtils.h"
#include "QXmppConfiguration.h"

#include <QEventLoop>
#include <QTimer>
#include <qdebug.h>

QXmppRemoteMethod::QXmppRemoteMethod(const QString &jid, const QString &method, const QVariantList &args, QXmppClient *client) :
        QObject(client), m_client(client)
{
    m_payload.setId( generateStanzaHash() );
    m_payload.setTo( jid );
    m_payload.setFrom( client->getConfiguration().getJid() );
    m_payload.setInterface( method.section('.', 0, 0 ) );
    m_payload.setMethod( method.section('.', 1) );
    m_payload.setPayload( args );
}

QXmppRemoteMethodResult QXmppRemoteMethod::call( )
{
    QEventLoop loop(this);
    connect( this, SIGNAL(callDone()), &loop, SLOT(quit()));
    QTimer::singleShot(30000,&loop, SLOT(quit())); // Timeout incase the other end hangs...

    m_client->sendPacket( m_payload );

    loop.exec( QEventLoop::ExcludeUserInputEvents | QEventLoop::WaitForMoreEvents );
    return m_result;
}

void QXmppRemoteMethod::gotError( const QXmppRpcErrorIq &iq )
{
    if ( iq.getId() == m_payload.getId() )
    {
        m_result.hasError = true;
        m_result.errorMessage = iq.getError().getText();
        m_result.code = iq.getError().getType();
        emit callDone();
    }
}

void QXmppRemoteMethod::gotResult( const QXmppRpcResponseIq &iq )
{
    if ( iq.getId() == m_payload.getId() )
    {
        m_result.hasError = false;
        m_result.result = iq.getPayload();
        emit callDone();
    }
}
<|endoftext|>