<commit_before>#include "graphics/renderer.h"
#include "core/array.h"
#include "core/crc32.h"
#include "core/fs/file_system.h"
#include "core/json_serializer.h"
#include "core/math_utils.h"
#include "core/profiler.h"
#include "core/resource_manager.h"
#include "core/resource_manager_base.h"
#include "core/vec4.h"
#include "editor/world_editor.h"
#include "engine/engine.h"
#include "graphics/geometry.h"
#include "graphics/gl_ext.h"
#include "graphics/irender_device.h"
#include "graphics/material.h"
#include "graphics/model.h"
#include "graphics/model_instance.h"
#include "graphics/pipeline.h"
#include "graphics/render_scene.h"
#include "graphics/shader.h"
#include "graphics/texture.h"
#include "universe/universe.h"

namespace Lumix
{

static const uint32_t LIGHT_HASH = crc32("light");
static const uint32_t RENDERABLE_HASH = crc32("renderable");
static const uint32_t CAMERA_HASH = crc32("camera");

struct RendererImpl : public Renderer
{
	RendererImpl()
	{
		m_last_bind_geometry = NULL;
		m_last_program_id = 0xffffFFFF;
		m_is_editor_wireframe = false;
	}

	virtual IScene* createScene(Universe& universe)
	{
		return RenderScene::createInstance(*this, *m_engine, universe);
	}

	virtual void setProjection(float width, float height, float fov, float near_plane, float far_plane, const Matrix& mtx) override
	{
		glViewport(0, 0, (GLsizei)width, (GLsizei)height);
		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		gluPerspective(fov, width / height, near_plane, far_plane);
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		Vec3 pos = mtx.getTranslation();
		Vec3 center = pos - mtx.getZVector();
		Vec3 up = mtx.getYVector();
		gluLookAt(pos.x, pos.y, pos.z, center.x, center.y, center.z, up.x, up.y, up.z);
	}

	virtual void setRenderDevice(IRenderDevice& device) override
	{
		m_render_device = &device;
	}

	virtual void renderGame() override
	{
		PROFILE_FUNCTION();
		if (m_render_device)
		{
			m_render_device->beginFrame();
			render(*m_render_device);
			m_render_device->endFrame();
		}
	}

	virtual void render(IRenderDevice& device) override
	{
		PROFILE_FUNCTION();
		glEnable(GL_DEPTH_TEST);
		glDisable(GL_BLEND);

		device.getPipeline().render();

		cleanup();
	}

	virtual void cleanup() override
	{
		m_last_bind_geometry = NULL;
		glBindBuffer(GL_ARRAY_BUFFER, 0);
		glUseProgram(0);
		for(int i = 0; i < 16; ++i)
		{
			glActiveTexture(GL_TEXTURE0 + i);
			glDisable(GL_TEXTURE_2D);
		}
		glActiveTexture(GL_TEXTURE0);
	}

	virtual void setUniform(Shader& shader, const char* name, const uint32_t name_hash, int value) override
	{
		PROFILE_FUNCTION();
		GLint loc = shader.getUniformLocation(name, name_hash);
		if (loc >= 0)
		{
			if (m_last_program_id != shader.getProgramId())
			{
				glUseProgram(shader.getProgramId());
				m_last_program_id = shader.getProgramId();
			}
			glUniform1i(loc, value);
		}
	}

	virtual void setUniform(Shader& shader, const char* name, const uint32_t name_hash, const Vec3& value) override
	{
		PROFILE_FUNCTION();
		GLint loc = shader.getUniformLocation(name, name_hash);
		if (loc >= 0)
		{
			if (m_last_program_id != shader.getProgramId())
			{
				glUseProgram(shader.getProgramId());
				m_last_program_id = shader.getProgramId();
			}
			glUniform3f(loc, value.x, value.y, value.z);
		}
	}

	virtual void setUniform(Shader& shader, const char* name, const uint32_t name_hash, float value) override
	{
		PROFILE_FUNCTION();
		GLint loc = shader.getUniformLocation(name, name_hash);
		if (loc >= 0)
		{
			if (m_last_program_id != shader.getProgramId())
			{
				glUseProgram(shader.getProgramId());
				m_last_program_id = shader.getProgramId();
			}
			glUniform1f(loc, value);
		}
	}

	virtual void setUniform(Shader& shader, const char* name, const uint32_t name_hash, const Matrix& mtx) override
	{
		PROFILE_FUNCTION();
		GLint loc = shader.getUniformLocation(name, name_hash);
		if (loc >= 0)
		{
			//glProgramUniformMatrix4fv(shader.getProgramId(), loc, 1, false, &mtx.m11);
			if (m_last_program_id != shader.getProgramId())
			{
				glUseProgram(shader.getProgramId());
				m_last_program_id = shader.getProgramId();
			}
			glUniformMatrix4fv(loc, 1, false, &mtx.m11);
		}
	}

	virtual void setUniform(Shader& shader, const char* name, const uint32_t name_hash, const Matrix* matrices, int count) override
	{
		PROFILE_FUNCTION();
		GLint loc = shader.getUniformLocation(name, name_hash);
		if (loc >= 0)
		{
			if (m_last_program_id != shader.getProgramId())
			{
				glUseProgram(shader.getProgramId());
				m_last_program_id = shader.getProgramId();
			}
			glUniformMatrix4fv(loc, count, false, (float*)matrices);
		}
	}

	virtual void setFixedCachedUniform(Shader& shader, int name, const Vec3& value) override
	{
		PROFILE_FUNCTION();
		GLint loc = shader.getFixedCachedUniformLocation((Shader::FixedCachedUniforms)name);
		if (loc >= 0)
		{
			if (m_last_program_id != shader.getProgramId())
			{
				glUseProgram(shader.getProgramId());
				m_last_program_id = shader.getProgramId();
			}
			glUniform3f(loc, value.x, value.y, value.z);
		}
	}

	virtual void setFixedCachedUniform(Shader& shader, int name, float value) override
	{
		PROFILE_FUNCTION();
		GLint loc = shader.getFixedCachedUniformLocation((Shader::FixedCachedUniforms)name);
		if (loc >= 0)
		{
			if (m_last_program_id != shader.getProgramId())
			{
				glUseProgram(shader.getProgramId());
				m_last_program_id = shader.getProgramId();
			}
			glUniform1f(loc, value);
		}
	}

	virtual void setFixedCachedUniform(Shader& shader, int name, const Matrix& mtx) override
	{
		PROFILE_FUNCTION();
		GLint loc = shader.getFixedCachedUniformLocation((Shader::FixedCachedUniforms)name);
		if (loc >= 0)
		{
			//glProgramUniformMatrix4fv(shader.getProgramId(), loc, 1, false, &mtx.m11);
			if (m_last_program_id != shader.getProgramId())
			{
				glUseProgram(shader.getProgramId());
				m_last_program_id = shader.getProgramId();
			}
			glUniformMatrix4fv(loc, 1, false, &mtx.m11);
		}
	}

	virtual void setFixedCachedUniform(Shader& shader, int name, const Matrix* matrices, int count) override
	{
		PROFILE_FUNCTION();
		GLint loc = shader.getFixedCachedUniformLocation((Shader::FixedCachedUniforms)name);
		if (loc >= 0)
		{
			if (m_last_program_id != shader.getProgramId())
			{
				glUseProgram(shader.getProgramId());
				m_last_program_id = shader.getProgramId();
			}
			glUniformMatrix4fv(loc, count, false, (float*)matrices);
		}
	}

	virtual void applyShader(const Shader& shader) override
	{
		GLuint id = shader.getProgramId();
		m_last_program_id = id;
		glUseProgram(id);
	}

	virtual void renderGeometry(Geometry& geometry, int start, int count, Shader& shader) override
	{
		PROFILE_FUNCTION();
		if (m_last_bind_geometry != &geometry)
		{
			if (m_last_bind_geometry)
			{
				m_last_bind_geometry->getVertexDefinition().end(shader);
			}
			glBindBuffer(GL_ARRAY_BUFFER, geometry.getID());
			glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, geometry.getIndicesID());
			m_last_bind_geometry = &geometry;
			geometry.getVertexDefinition().begin(shader);
		}
		glDrawElements(GL_TRIANGLES, count, GL_UNSIGNED_INT, (void*)(start * sizeof(GLint)));
	}

	void registerPropertyDescriptors(WorldEditor& editor)
	{
		editor.registerProperty("camera", LUMIX_NEW(StringPropertyDescriptor<RenderScene>)("slot", &RenderScene::getCameraSlot, &RenderScene::setCameraSlot));
		editor.registerProperty("camera", LUMIX_NEW(DecimalPropertyDescriptor<RenderScene>)("fov", &RenderScene::getCameraFOV, &RenderScene::setCameraFOV));
		editor.registerProperty("camera", LUMIX_NEW(DecimalPropertyDescriptor<RenderScene>)("near", &RenderScene::getCameraNearPlane, &RenderScene::setCameraNearPlane));
		editor.registerProperty("camera", LUMIX_NEW(DecimalPropertyDescriptor<RenderScene>)("far", &RenderScene::getCameraFarPlane, &RenderScene::setCameraFarPlane));

		editor.registerProperty("renderable", LUMIX_NEW(FilePropertyDescriptor<RenderScene>)("source", &RenderScene::getRenderablePath, &RenderScene::setRenderablePath, "Mesh (*.msh)"));

		editor.registerProperty("terrain", LUMIX_NEW(FilePropertyDescriptor<RenderScene>)("material", &RenderScene::getTerrainMaterial, &RenderScene::setTerrainMaterial, "Material (*.mat)"));
		editor.registerProperty("terrain", LUMIX_NEW(DecimalPropertyDescriptor<RenderScene>)("xz_scale", &RenderScene::getTerrainXZScale, &RenderScene::setTerrainXZScale));
		editor.registerProperty("terrain", LUMIX_NEW(DecimalPropertyDescriptor<RenderScene>)("y_scale", &RenderScene::getTerrainYScale, &RenderScene::setTerrainYScale));

		auto grass = LUMIX_NEW(ArrayDescriptor<RenderScene>)("grass", &RenderScene::getGrassCount, &RenderScene::addGrass, &RenderScene::removeGrass);
		grass->addChild(LUMIX_NEW(FileArrayObjectDescriptor<RenderScene>)("mesh", &RenderScene::getGrass, &RenderScene::setGrass, "Mesh (*.msh)"));
		auto ground = LUMIX_NEW(IntArrayObjectDescriptor<RenderScene>)("ground", &RenderScene::getGrassGround, &RenderScene::setGrassGround);
		ground->setLimit(0, 4);
		grass->addChild(ground);
		grass->addChild(LUMIX_NEW(IntArrayObjectDescriptor<RenderScene>)("density", &RenderScene::getGrassDensity, &RenderScene::setGrassDensity));
		editor.registerProperty("terrain", grass);
	}

	virtual bool create(Engine& engine) override
	{
		registerPropertyDescriptors(*engine.getWorldEditor());

		m_engine = &engine;
		glewExperimental = GL_TRUE;
		GLenum err = glewInit();
		return err == GLEW_OK;
	}

	virtual void destroy() override
	{
	}

	virtual const char* getName() const override
	{
		return "renderer";
	}

	virtual void enableAlphaToCoverage(bool enable) override
	{
		if (enable)
		{
			glEnable(GL_MULTISAMPLE);
			glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
		}
		else
		{
			glDisable(GL_MULTISAMPLE);
			glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
		}
	}

	virtual void enableZTest(bool enable) override
	{
		if (enable)
		{
			glEnable(GL_DEPTH_TEST);
		}
		else
		{
			glDisable(GL_DEPTH_TEST);
		}
	}

	virtual Engine& getEngine() override
	{
		return *m_engine;
	}

	virtual void renderModel(const Model& model, const Matrix& transform, PipelineInstance& pipeline) override
	{
		glPushMatrix();
		glMultMatrixf(&transform.m11);
		for (int i = 0, c = model.getMeshCount(); i < c;  ++i)
		{
			const Mesh& mesh = model.getMesh(i);
			mesh.getMaterial()->apply(*this, pipeline);
			renderGeometry(*model.getGeometry(), mesh.getStart(), mesh.getCount(), *mesh.getMaterial()->getShader());
		}
		glPopMatrix();
	}

	virtual void serialize(ISerializer&) override
	{
	}

	virtual void deserialize(ISerializer&) override
	{
	}

	virtual void setEditorWireframe(bool is_wireframe)
	{
		m_is_editor_wireframe = is_wireframe;
	}

	virtual bool isEditorWireframe() const
	{
		return m_is_editor_wireframe;
	}

	Engine* m_engine;
	IRenderDevice* m_render_device;
	bool m_is_editor_wireframe;
	Geometry* m_last_bind_geometry;
	GLuint m_last_program_id;
};

Renderer* Renderer::createInstance()
{
	return LUMIX_NEW(RendererImpl);
}

void Renderer::destroyInstance(Renderer& renderer)
{
	LUMIX_DELETE(&renderer);
}

} // ~namespace Lumix
<commit_msg>crash after map reload fixed<commit_after>#include "graphics/renderer.h"
#include "core/array.h"
#include "core/crc32.h"
#include "core/fs/file_system.h"
#include "core/json_serializer.h"
#include "core/math_utils.h"
#include "core/profiler.h"
#include "core/resource_manager.h"
#include "core/resource_manager_base.h"
#include "core/vec4.h"
#include "editor/world_editor.h"
#include "engine/engine.h"
#include "graphics/geometry.h"
#include "graphics/gl_ext.h"
#include "graphics/irender_device.h"
#include "graphics/material.h"
#include "graphics/model.h"
#include "graphics/model_instance.h"
#include "graphics/pipeline.h"
#include "graphics/render_scene.h"
#include "graphics/shader.h"
#include "graphics/texture.h"
#include "universe/universe.h"

namespace Lumix
{

static const uint32_t LIGHT_HASH = crc32("light");
static const uint32_t RENDERABLE_HASH = crc32("renderable");
static const uint32_t CAMERA_HASH = crc32("camera");

struct RendererImpl : public Renderer
{
	RendererImpl()
	{
		m_last_bind_geometry = NULL;
		m_last_program_id = 0xffffFFFF;
		m_is_editor_wireframe = false;
	}

	virtual IScene* createScene(Universe& universe)
	{
		return RenderScene::createInstance(*this, *m_engine, universe);
	}

	virtual void setProjection(float width, float height, float fov, float near_plane, float far_plane, const Matrix& mtx) override
	{
		glViewport(0, 0, (GLsizei)width, (GLsizei)height);
		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		gluPerspective(fov, width / height, near_plane, far_plane);
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		Vec3 pos = mtx.getTranslation();
		Vec3 center = pos - mtx.getZVector();
		Vec3 up = mtx.getYVector();
		gluLookAt(pos.x, pos.y, pos.z, center.x, center.y, center.z, up.x, up.y, up.z);
	}

	virtual void setRenderDevice(IRenderDevice& device) override
	{
		m_render_device = &device;
	}

	virtual void renderGame() override
	{
		PROFILE_FUNCTION();
		if (m_render_device)
		{
			m_render_device->beginFrame();
			render(*m_render_device);
			m_render_device->endFrame();
		}
	}

	virtual void render(IRenderDevice& device) override
	{
		PROFILE_FUNCTION();
		glEnable(GL_DEPTH_TEST);
		glDisable(GL_BLEND);

		device.getPipeline().render();

		cleanup();
	}

	virtual void cleanup() override
	{
		if(m_last_bind_geometry)
		{
			m_last_bind_geometry->getVertexDefinition().end(*m_last_bind_geometry_shader);
		}
		m_last_bind_geometry = NULL;
		glBindBuffer(GL_ARRAY_BUFFER, 0);
		glUseProgram(0);
		for(int i = 0; i < 16; ++i)
		{
			glActiveTexture(GL_TEXTURE0 + i);
			glDisable(GL_TEXTURE_2D);
		}
		glActiveTexture(GL_TEXTURE0);
	}

	virtual void setUniform(Shader& shader, const char* name, const uint32_t name_hash, int value) override
	{
		PROFILE_FUNCTION();
		GLint loc = shader.getUniformLocation(name, name_hash);
		if (loc >= 0)
		{
			if (m_last_program_id != shader.getProgramId())
			{
				glUseProgram(shader.getProgramId());
				m_last_program_id = shader.getProgramId();
			}
			glUniform1i(loc, value);
		}
	}

	virtual void setUniform(Shader& shader, const char* name, const uint32_t name_hash, const Vec3& value) override
	{
		PROFILE_FUNCTION();
		GLint loc = shader.getUniformLocation(name, name_hash);
		if (loc >= 0)
		{
			if (m_last_program_id != shader.getProgramId())
			{
				glUseProgram(shader.getProgramId());
				m_last_program_id = shader.getProgramId();
			}
			glUniform3f(loc, value.x, value.y, value.z);
		}
	}

	virtual void setUniform(Shader& shader, const char* name, const uint32_t name_hash, float value) override
	{
		PROFILE_FUNCTION();
		GLint loc = shader.getUniformLocation(name, name_hash);
		if (loc >= 0)
		{
			if (m_last_program_id != shader.getProgramId())
			{
				glUseProgram(shader.getProgramId());
				m_last_program_id = shader.getProgramId();
			}
			glUniform1f(loc, value);
		}
	}

	virtual void setUniform(Shader& shader, const char* name, const uint32_t name_hash, const Matrix& mtx) override
	{
		PROFILE_FUNCTION();
		GLint loc = shader.getUniformLocation(name, name_hash);
		if (loc >= 0)
		{
			//glProgramUniformMatrix4fv(shader.getProgramId(), loc, 1, false, &mtx.m11);
			if (m_last_program_id != shader.getProgramId())
			{
				glUseProgram(shader.getProgramId());
				m_last_program_id = shader.getProgramId();
			}
			glUniformMatrix4fv(loc, 1, false, &mtx.m11);
		}
	}

	virtual void setUniform(Shader& shader, const char* name, const uint32_t name_hash, const Matrix* matrices, int count) override
	{
		PROFILE_FUNCTION();
		GLint loc = shader.getUniformLocation(name, name_hash);
		if (loc >= 0)
		{
			if (m_last_program_id != shader.getProgramId())
			{
				glUseProgram(shader.getProgramId());
				m_last_program_id = shader.getProgramId();
			}
			glUniformMatrix4fv(loc, count, false, (float*)matrices);
		}
	}

	virtual void setFixedCachedUniform(Shader& shader, int name, const Vec3& value) override
	{
		PROFILE_FUNCTION();
		GLint loc = shader.getFixedCachedUniformLocation((Shader::FixedCachedUniforms)name);
		if (loc >= 0)
		{
			if (m_last_program_id != shader.getProgramId())
			{
				glUseProgram(shader.getProgramId());
				m_last_program_id = shader.getProgramId();
			}
			glUniform3f(loc, value.x, value.y, value.z);
		}
	}

	virtual void setFixedCachedUniform(Shader& shader, int name, float value) override
	{
		PROFILE_FUNCTION();
		GLint loc = shader.getFixedCachedUniformLocation((Shader::FixedCachedUniforms)name);
		if (loc >= 0)
		{
			if (m_last_program_id != shader.getProgramId())
			{
				glUseProgram(shader.getProgramId());
				m_last_program_id = shader.getProgramId();
			}
			glUniform1f(loc, value);
		}
	}

	virtual void setFixedCachedUniform(Shader& shader, int name, const Matrix& mtx) override
	{
		PROFILE_FUNCTION();
		GLint loc = shader.getFixedCachedUniformLocation((Shader::FixedCachedUniforms)name);
		if (loc >= 0)
		{
			//glProgramUniformMatrix4fv(shader.getProgramId(), loc, 1, false, &mtx.m11);
			if (m_last_program_id != shader.getProgramId())
			{
				glUseProgram(shader.getProgramId());
				m_last_program_id = shader.getProgramId();
			}
			glUniformMatrix4fv(loc, 1, false, &mtx.m11);
		}
	}

	virtual void setFixedCachedUniform(Shader& shader, int name, const Matrix* matrices, int count) override
	{
		PROFILE_FUNCTION();
		GLint loc = shader.getFixedCachedUniformLocation((Shader::FixedCachedUniforms)name);
		if (loc >= 0)
		{
			if (m_last_program_id != shader.getProgramId())
			{
				glUseProgram(shader.getProgramId());
				m_last_program_id = shader.getProgramId();
			}
			glUniformMatrix4fv(loc, count, false, (float*)matrices);
		}
	}

	virtual void applyShader(const Shader& shader) override
	{
		GLuint id = shader.getProgramId();
		m_last_program_id = id;
		glUseProgram(id);
	}

	virtual void renderGeometry(Geometry& geometry, int start, int count, Shader& shader) override
	{
		PROFILE_FUNCTION();
		if (m_last_bind_geometry != &geometry)
		{
			if (m_last_bind_geometry)
			{
				m_last_bind_geometry->getVertexDefinition().end(shader);
			}
			glBindBuffer(GL_ARRAY_BUFFER, geometry.getID());
			glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, geometry.getIndicesID());
			m_last_bind_geometry = &geometry;
			m_last_bind_geometry_shader = &shader;
			geometry.getVertexDefinition().begin(shader);
		}
		glDrawElements(GL_TRIANGLES, count, GL_UNSIGNED_INT, (void*)(start * sizeof(GLint)));
	}

	void registerPropertyDescriptors(WorldEditor& editor)
	{
		editor.registerProperty("camera", LUMIX_NEW(StringPropertyDescriptor<RenderScene>)("slot", &RenderScene::getCameraSlot, &RenderScene::setCameraSlot));
		editor.registerProperty("camera", LUMIX_NEW(DecimalPropertyDescriptor<RenderScene>)("fov", &RenderScene::getCameraFOV, &RenderScene::setCameraFOV));
		editor.registerProperty("camera", LUMIX_NEW(DecimalPropertyDescriptor<RenderScene>)("near", &RenderScene::getCameraNearPlane, &RenderScene::setCameraNearPlane));
		editor.registerProperty("camera", LUMIX_NEW(DecimalPropertyDescriptor<RenderScene>)("far", &RenderScene::getCameraFarPlane, &RenderScene::setCameraFarPlane));

		editor.registerProperty("renderable", LUMIX_NEW(FilePropertyDescriptor<RenderScene>)("source", &RenderScene::getRenderablePath, &RenderScene::setRenderablePath, "Mesh (*.msh)"));

		editor.registerProperty("terrain", LUMIX_NEW(FilePropertyDescriptor<RenderScene>)("material", &RenderScene::getTerrainMaterial, &RenderScene::setTerrainMaterial, "Material (*.mat)"));
		editor.registerProperty("terrain", LUMIX_NEW(DecimalPropertyDescriptor<RenderScene>)("xz_scale", &RenderScene::getTerrainXZScale, &RenderScene::setTerrainXZScale));
		editor.registerProperty("terrain", LUMIX_NEW(DecimalPropertyDescriptor<RenderScene>)("y_scale", &RenderScene::getTerrainYScale, &RenderScene::setTerrainYScale));

		auto grass = LUMIX_NEW(ArrayDescriptor<RenderScene>)("grass", &RenderScene::getGrassCount, &RenderScene::addGrass, &RenderScene::removeGrass);
		grass->addChild(LUMIX_NEW(FileArrayObjectDescriptor<RenderScene>)("mesh", &RenderScene::getGrass, &RenderScene::setGrass, "Mesh (*.msh)"));
		auto ground = LUMIX_NEW(IntArrayObjectDescriptor<RenderScene>)("ground", &RenderScene::getGrassGround, &RenderScene::setGrassGround);
		ground->setLimit(0, 4);
		grass->addChild(ground);
		grass->addChild(LUMIX_NEW(IntArrayObjectDescriptor<RenderScene>)("density", &RenderScene::getGrassDensity, &RenderScene::setGrassDensity));
		editor.registerProperty("terrain", grass);
	}

	virtual bool create(Engine& engine) override
	{
		registerPropertyDescriptors(*engine.getWorldEditor());

		m_engine = &engine;
		glewExperimental = GL_TRUE;
		GLenum err = glewInit();
		return err == GLEW_OK;
	}

	virtual void destroy() override
	{
	}

	virtual const char* getName() const override
	{
		return "renderer";
	}

	virtual void enableAlphaToCoverage(bool enable) override
	{
		if (enable)
		{
			glEnable(GL_MULTISAMPLE);
			glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
		}
		else
		{
			glDisable(GL_MULTISAMPLE);
			glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
		}
	}

	virtual void enableZTest(bool enable) override
	{
		if (enable)
		{
			glEnable(GL_DEPTH_TEST);
		}
		else
		{
			glDisable(GL_DEPTH_TEST);
		}
	}

	virtual Engine& getEngine() override
	{
		return *m_engine;
	}

	virtual void renderModel(const Model& model, const Matrix& transform, PipelineInstance& pipeline) override
	{
		glPushMatrix();
		glMultMatrixf(&transform.m11);
		for (int i = 0, c = model.getMeshCount(); i < c;  ++i)
		{
			const Mesh& mesh = model.getMesh(i);
			mesh.getMaterial()->apply(*this, pipeline);
			renderGeometry(*model.getGeometry(), mesh.getStart(), mesh.getCount(), *mesh.getMaterial()->getShader());
		}
		glPopMatrix();
	}

	virtual void serialize(ISerializer&) override
	{
	}

	virtual void deserialize(ISerializer&) override
	{
	}

	virtual void setEditorWireframe(bool is_wireframe)
	{
		m_is_editor_wireframe = is_wireframe;
	}

	virtual bool isEditorWireframe() const
	{
		return m_is_editor_wireframe;
	}

	Engine* m_engine;
	IRenderDevice* m_render_device;
	bool m_is_editor_wireframe;
	Geometry* m_last_bind_geometry;
	Shader* m_last_bind_geometry_shader;
	GLuint m_last_program_id;
};

Renderer* Renderer::createInstance()
{
	return LUMIX_NEW(RendererImpl);
}

void Renderer::destroyInstance(Renderer& renderer)
{
	LUMIX_DELETE(&renderer);
}

} // ~namespace Lumix
<|endoftext|>


<commit_before>#include "external_task.h"
#include "../sandbox/isolate_sandbox.h"

external_task::external_task(const create_params &data)
	: task_base(data.id, data.task_meta), worker_id_(data.worker_id), sandbox_(nullptr), limits_(data.limits),
	  logger_(data.logger), temp_dir_(data.temp_dir)
{
	sandbox_check();
}

external_task::~external_task()
{
}

void external_task::sandbox_check()
{
	bool found = false;

	if (task_meta_->sandbox == nullptr) {
		throw task_exception("No sandbox configuration provided.");
	}

#ifndef _WIN32
	if (task_meta_->sandbox->name == "isolate") {
		found = true;
	}
#endif

	if (found == false) {
		throw task_exception("Unknown sandbox type: " + task_meta_->sandbox->name);
	}
}

void external_task::sandbox_init()
{
#ifndef _WIN32
	if (task_meta_->sandbox->name == "isolate") {
		sandbox_ = std::make_shared<isolate_sandbox>(*limits_, worker_id_, temp_dir_, logger_);
	}
#endif
}

void external_task::sandbox_fini()
{
	sandbox_ = nullptr;
}

std::shared_ptr<task_results> external_task::run()
{
	sandbox_init();

	// TODO: only temporary solution, should be removed
	if (sandbox_ == nullptr) {
		return nullptr;
	}

	auto res = std::shared_ptr<task_results>(new task_results());
	res->sandbox_status =
		std::unique_ptr<sandbox_results>(new sandbox_results(sandbox_->run(task_meta_->binary, task_meta_->cmd_args)));

	sandbox_fini();

	return res;
}

std::shared_ptr<sandbox_limits> external_task::get_limits()
{
	return limits_;
}
<commit_msg>Fix return status of failed external task<commit_after>#include "external_task.h"
#include "../sandbox/isolate_sandbox.h"

external_task::external_task(const create_params &data)
	: task_base(data.id, data.task_meta), worker_id_(data.worker_id), sandbox_(nullptr), limits_(data.limits),
	  logger_(data.logger), temp_dir_(data.temp_dir)
{
	sandbox_check();
}

external_task::~external_task()
{
}

void external_task::sandbox_check()
{
	bool found = false;

	if (task_meta_->sandbox == nullptr) {
		throw task_exception("No sandbox configuration provided.");
	}

#ifndef _WIN32
	if (task_meta_->sandbox->name == "isolate") {
		found = true;
	}
#endif

	if (found == false) {
		throw task_exception("Unknown sandbox type: " + task_meta_->sandbox->name);
	}
}

void external_task::sandbox_init()
{
#ifndef _WIN32
	if (task_meta_->sandbox->name == "isolate") {
		sandbox_ = std::make_shared<isolate_sandbox>(*limits_, worker_id_, temp_dir_, logger_);
	}
#endif
}

void external_task::sandbox_fini()
{
	sandbox_ = nullptr;
}

std::shared_ptr<task_results> external_task::run()
{
	sandbox_init();

	// TODO: only temporary solution, should be removed
	if (sandbox_ == nullptr) {
		return nullptr;
	}

	auto res = std::shared_ptr<task_results>(new task_results());
	res->sandbox_status =
		std::unique_ptr<sandbox_results>(new sandbox_results(sandbox_->run(task_meta_->binary, task_meta_->cmd_args)));

	sandbox_fini();

	// Check if sandbox ran successfully, else report error
	if (res->sandbox_status->status != isolate_status::OK) {
		throw task_exception("Sandboxed program failed: " + res->sandbox_status->message);
	}

	return res;
}

std::shared_ptr<sandbox_limits> external_task::get_limits()
{
	return limits_;
}
<|endoftext|>


<commit_before>/*
  Copyright (c) 2014-2015 DataStax

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

#ifndef __CASS_CONFIG_HPP_INCLUDED__
#define __CASS_CONFIG_HPP_INCLUDED__

#include "auth.hpp"
#include "cassandra.h"
#include "dc_aware_policy.hpp"
#include "latency_aware_policy.hpp"
#include "ssl.hpp"
#include "token_aware_policy.hpp"

#include <list>
#include <string>

namespace cass {

void stderr_log_callback(const CassLogMessage* message, void* data);

class Config {
public:
  typedef std::list<std::string> ContactPointList;

  Config()
      : port_(9042)
      , protocol_version_(3)
      , thread_count_io_(1)
      , queue_size_io_(8192)
      , queue_size_event_(8192)
      , queue_size_log_(8192)
      , core_connections_per_host_(1)
      , max_connections_per_host_(2)
      , reconnect_wait_time_ms_(2000)
      , max_concurrent_creation_(1)
      , max_requests_per_flush_(128)
      , max_concurrent_requests_threshold_(100)
      , write_bytes_high_water_mark_(64 * 1024)
      , write_bytes_low_water_mark_(32 * 1024)
      , pending_requests_high_water_mark_(128 * max_connections_per_host_)
      , pending_requests_low_water_mark_(pending_requests_high_water_mark_ / 2)
      , connect_timeout_ms_(5000)
      , request_timeout_ms_(12000)
      , log_level_(CASS_LOG_WARN)
      , log_callback_(stderr_log_callback)
      , log_data_(NULL)
      , auth_provider_(new AuthProvider())
      , load_balancing_policy_(new DCAwarePolicy())
      , token_aware_routing_(true)
      , latency_aware_routing_(false)
      , tcp_nodelay_enable_(false)
      , tcp_keepalive_enable_(false)
      , tcp_keepalive_delay_secs_(0) {}

  unsigned thread_count_io() const { return thread_count_io_; }

  void set_thread_count_io(unsigned num_threads) {
    thread_count_io_ = num_threads;
  }

  unsigned queue_size_io() const { return queue_size_io_; }

  void set_queue_size_io(unsigned queue_size) {
    queue_size_io_ = queue_size;
  }

  unsigned queue_size_event() const { return queue_size_event_; }

  void set_queue_size_event(unsigned queue_size) {
    queue_size_event_ = queue_size;
  }

  unsigned queue_size_log() const { return queue_size_log_; }

  void set_queue_size_log(unsigned queue_size) {
    queue_size_log_ = queue_size;
  }

  unsigned core_connections_per_host() const {
    return core_connections_per_host_;
  }

  void set_core_connections_per_host(unsigned num_connections) {
    core_connections_per_host_ = num_connections;
  }

  unsigned max_connections_per_host() const { return max_connections_per_host_; }

  void set_max_connections_per_host(unsigned num_connections) {
    max_connections_per_host_ = num_connections;
  }

  unsigned max_concurrent_creation() const {
    return max_concurrent_creation_;
  }

  void set_max_concurrent_creation(unsigned num_connections) {
    max_concurrent_creation_ = num_connections;
  }

  unsigned write_bytes_high_water_mark() const {
    return write_bytes_high_water_mark_;
  }

  void set_write_bytes_high_water_mark(unsigned write_bytes_high_water_mark) {
    write_bytes_high_water_mark_ = write_bytes_high_water_mark;
  }

  unsigned write_bytes_low_water_mark() const {
    return write_bytes_low_water_mark_;
  }

  void set_write_bytes_low_water_mark(unsigned write_bytes_low_water_mark) {
    write_bytes_low_water_mark_ = write_bytes_low_water_mark;
  }

  unsigned pending_requests_high_water_mark() const {
    return pending_requests_high_water_mark_;
  }

  void set_pending_requests_high_water_mark(unsigned pending_requests_high_water_mark) {
    pending_requests_high_water_mark_ = pending_requests_high_water_mark;
  }

  unsigned pending_requests_low_water_mark() const {
    return pending_requests_low_water_mark_;
  }

  void set_pending_requests_low_water_mark(unsigned pending_requests_low_water_mark) {
    pending_requests_low_water_mark_ = pending_requests_low_water_mark;
  }

  unsigned reconnect_wait_time_ms() const { return reconnect_wait_time_ms_; }

  void set_reconnect_wait_time(unsigned wait_time_ms) {
    reconnect_wait_time_ms_ = wait_time_ms;
  }

  unsigned max_requests_per_flush() const { return max_requests_per_flush_; }

  void set_max_requests_per_flush(unsigned num_requests) {
    max_requests_per_flush_ = num_requests;
  }

  unsigned max_concurrent_requests_threshold() const {
    return max_concurrent_requests_threshold_;
  }

  void set_max_concurrent_requests_threshold(unsigned num_requests) {
    max_concurrent_requests_threshold_ = num_requests;
  }

  unsigned connect_timeout_ms() const { return connect_timeout_ms_; }

  void set_connect_timeout(unsigned timeout_ms) {
    connect_timeout_ms_ = timeout_ms;
  }

  unsigned request_timeout_ms() const { return request_timeout_ms_; }

  void set_request_timeout(unsigned timeout_ms) {
    request_timeout_ms_ = timeout_ms;
  }

  const ContactPointList& contact_points() const {
    return contact_points_;
  }

  ContactPointList& contact_points() {
    return contact_points_;
  }

  int port() const { return port_; }

  void set_port(int port) {
    port_ = port;
  }

  int protocol_version() const { return protocol_version_; }

  void set_protocol_version(int protocol_version) {
    protocol_version_ = protocol_version;
  }

  CassLogLevel log_level() const { return log_level_; }

  void set_log_level(CassLogLevel log_level) {
    log_level_ = log_level;
  }

  void* log_data() const { return log_data_; }

  CassLogCallback log_callback() const { return log_callback_; }

  void set_log_callback(CassLogCallback callback, void* data) {
    log_callback_ = callback;
    log_data_ = data;
  }

  const SharedRefPtr<AuthProvider>& auth_provider() const { return auth_provider_; }

  void set_auth_provider(AuthProvider* auth_provider) {
    if (auth_provider == NULL) return;
    auth_provider_.reset(auth_provider);
  }

  void set_credentials(const std::string& username, const std::string& password) {
    auth_provider_.reset(new PlainTextAuthProvider(username, password));
  }

  LoadBalancingPolicy* load_balancing_policy() const {
    // base LBP can be augmented by special wrappers (whitelist, token aware, latency aware)
    LoadBalancingPolicy* chain = load_balancing_policy_->new_instance();
    if (token_aware_routing()) {
      chain = new TokenAwarePolicy(chain);
    }
    if (latency_aware()) {
      chain = new LatencyAwarePolicy(chain, latency_aware_routing_settings_);
    }
    return chain;
  }

  void set_load_balancing_policy(LoadBalancingPolicy* lbp) {
    if (lbp == NULL) return;
    load_balancing_policy_.reset(lbp);
  }

  SslContext* ssl_context() const { return ssl_context_.get(); }

  void set_ssl_context(SslContext* ssl_context) {
    ssl_context_.reset(ssl_context);
  }

  bool token_aware_routing() const { return token_aware_routing_; }

  void set_token_aware_routing(bool is_token_aware) { token_aware_routing_ = is_token_aware; }

  bool latency_aware() const { return latency_aware_routing_; }

  void set_latency_aware_routing(bool is_latency_aware) { latency_aware_routing_ = is_latency_aware; }

  void set_latency_aware_routing_settings(const LatencyAwarePolicy::Settings& settings) {
    latency_aware_routing_settings_ = settings;
  }

  bool tcp_nodelay_enable() const { return tcp_nodelay_enable_; }

  void set_tcp_nodelay(bool enable) {
    tcp_nodelay_enable_ = enable;
  }

  bool tcp_keepalive_enable() const { return tcp_keepalive_enable_; }
  unsigned tcp_keepalive_delay_secs() const { return tcp_keepalive_delay_secs_; }

  void set_tcp_keepalive(bool enable, unsigned delay_secs) {
    tcp_keepalive_enable_ = enable;
    tcp_keepalive_delay_secs_ = delay_secs;
  }

private:
  int port_;
  int protocol_version_;
  ContactPointList contact_points_;
  unsigned thread_count_io_;
  unsigned queue_size_io_;
  unsigned queue_size_event_;
  unsigned queue_size_log_;
  unsigned core_connections_per_host_;
  unsigned max_connections_per_host_;
  unsigned reconnect_wait_time_ms_;
  unsigned max_concurrent_creation_;
  unsigned max_requests_per_flush_;
  unsigned max_concurrent_requests_threshold_;
  unsigned write_bytes_high_water_mark_;
  unsigned write_bytes_low_water_mark_;
  unsigned pending_requests_high_water_mark_;
  unsigned pending_requests_low_water_mark_;
  unsigned connect_timeout_ms_;
  unsigned request_timeout_ms_;
  CassLogLevel log_level_;
  CassLogCallback log_callback_;
  void* log_data_;
  SharedRefPtr<AuthProvider> auth_provider_;
  SharedRefPtr<LoadBalancingPolicy> load_balancing_policy_;
  SharedRefPtr<SslContext> ssl_context_;
  bool token_aware_routing_;
  bool latency_aware_routing_;
  LatencyAwarePolicy::Settings latency_aware_routing_settings_;
  bool tcp_nodelay_enable_;
  bool tcp_keepalive_enable_;
  unsigned tcp_keepalive_delay_secs_;
};

} // namespace cass

#endif
<commit_msg>Enabled TCP no delay by default<commit_after>/*
  Copyright (c) 2014-2015 DataStax

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

#ifndef __CASS_CONFIG_HPP_INCLUDED__
#define __CASS_CONFIG_HPP_INCLUDED__

#include "auth.hpp"
#include "cassandra.h"
#include "dc_aware_policy.hpp"
#include "latency_aware_policy.hpp"
#include "ssl.hpp"
#include "token_aware_policy.hpp"

#include <list>
#include <string>

namespace cass {

void stderr_log_callback(const CassLogMessage* message, void* data);

class Config {
public:
  typedef std::list<std::string> ContactPointList;

  Config()
      : port_(9042)
      , protocol_version_(3)
      , thread_count_io_(1)
      , queue_size_io_(8192)
      , queue_size_event_(8192)
      , queue_size_log_(8192)
      , core_connections_per_host_(1)
      , max_connections_per_host_(2)
      , reconnect_wait_time_ms_(2000)
      , max_concurrent_creation_(1)
      , max_requests_per_flush_(128)
      , max_concurrent_requests_threshold_(100)
      , write_bytes_high_water_mark_(64 * 1024)
      , write_bytes_low_water_mark_(32 * 1024)
      , pending_requests_high_water_mark_(128 * max_connections_per_host_)
      , pending_requests_low_water_mark_(pending_requests_high_water_mark_ / 2)
      , connect_timeout_ms_(5000)
      , request_timeout_ms_(12000)
      , log_level_(CASS_LOG_WARN)
      , log_callback_(stderr_log_callback)
      , log_data_(NULL)
      , auth_provider_(new AuthProvider())
      , load_balancing_policy_(new DCAwarePolicy())
      , token_aware_routing_(true)
      , latency_aware_routing_(false)
      , tcp_nodelay_enable_(true)
      , tcp_keepalive_enable_(false)
      , tcp_keepalive_delay_secs_(0) {}

  unsigned thread_count_io() const { return thread_count_io_; }

  void set_thread_count_io(unsigned num_threads) {
    thread_count_io_ = num_threads;
  }

  unsigned queue_size_io() const { return queue_size_io_; }

  void set_queue_size_io(unsigned queue_size) {
    queue_size_io_ = queue_size;
  }

  unsigned queue_size_event() const { return queue_size_event_; }

  void set_queue_size_event(unsigned queue_size) {
    queue_size_event_ = queue_size;
  }

  unsigned queue_size_log() const { return queue_size_log_; }

  void set_queue_size_log(unsigned queue_size) {
    queue_size_log_ = queue_size;
  }

  unsigned core_connections_per_host() const {
    return core_connections_per_host_;
  }

  void set_core_connections_per_host(unsigned num_connections) {
    core_connections_per_host_ = num_connections;
  }

  unsigned max_connections_per_host() const { return max_connections_per_host_; }

  void set_max_connections_per_host(unsigned num_connections) {
    max_connections_per_host_ = num_connections;
  }

  unsigned max_concurrent_creation() const {
    return max_concurrent_creation_;
  }

  void set_max_concurrent_creation(unsigned num_connections) {
    max_concurrent_creation_ = num_connections;
  }

  unsigned write_bytes_high_water_mark() const {
    return write_bytes_high_water_mark_;
  }

  void set_write_bytes_high_water_mark(unsigned write_bytes_high_water_mark) {
    write_bytes_high_water_mark_ = write_bytes_high_water_mark;
  }

  unsigned write_bytes_low_water_mark() const {
    return write_bytes_low_water_mark_;
  }

  void set_write_bytes_low_water_mark(unsigned write_bytes_low_water_mark) {
    write_bytes_low_water_mark_ = write_bytes_low_water_mark;
  }

  unsigned pending_requests_high_water_mark() const {
    return pending_requests_high_water_mark_;
  }

  void set_pending_requests_high_water_mark(unsigned pending_requests_high_water_mark) {
    pending_requests_high_water_mark_ = pending_requests_high_water_mark;
  }

  unsigned pending_requests_low_water_mark() const {
    return pending_requests_low_water_mark_;
  }

  void set_pending_requests_low_water_mark(unsigned pending_requests_low_water_mark) {
    pending_requests_low_water_mark_ = pending_requests_low_water_mark;
  }

  unsigned reconnect_wait_time_ms() const { return reconnect_wait_time_ms_; }

  void set_reconnect_wait_time(unsigned wait_time_ms) {
    reconnect_wait_time_ms_ = wait_time_ms;
  }

  unsigned max_requests_per_flush() const { return max_requests_per_flush_; }

  void set_max_requests_per_flush(unsigned num_requests) {
    max_requests_per_flush_ = num_requests;
  }

  unsigned max_concurrent_requests_threshold() const {
    return max_concurrent_requests_threshold_;
  }

  void set_max_concurrent_requests_threshold(unsigned num_requests) {
    max_concurrent_requests_threshold_ = num_requests;
  }

  unsigned connect_timeout_ms() const { return connect_timeout_ms_; }

  void set_connect_timeout(unsigned timeout_ms) {
    connect_timeout_ms_ = timeout_ms;
  }

  unsigned request_timeout_ms() const { return request_timeout_ms_; }

  void set_request_timeout(unsigned timeout_ms) {
    request_timeout_ms_ = timeout_ms;
  }

  const ContactPointList& contact_points() const {
    return contact_points_;
  }

  ContactPointList& contact_points() {
    return contact_points_;
  }

  int port() const { return port_; }

  void set_port(int port) {
    port_ = port;
  }

  int protocol_version() const { return protocol_version_; }

  void set_protocol_version(int protocol_version) {
    protocol_version_ = protocol_version;
  }

  CassLogLevel log_level() const { return log_level_; }

  void set_log_level(CassLogLevel log_level) {
    log_level_ = log_level;
  }

  void* log_data() const { return log_data_; }

  CassLogCallback log_callback() const { return log_callback_; }

  void set_log_callback(CassLogCallback callback, void* data) {
    log_callback_ = callback;
    log_data_ = data;
  }

  const SharedRefPtr<AuthProvider>& auth_provider() const { return auth_provider_; }

  void set_auth_provider(AuthProvider* auth_provider) {
    if (auth_provider == NULL) return;
    auth_provider_.reset(auth_provider);
  }

  void set_credentials(const std::string& username, const std::string& password) {
    auth_provider_.reset(new PlainTextAuthProvider(username, password));
  }

  LoadBalancingPolicy* load_balancing_policy() const {
    // base LBP can be augmented by special wrappers (whitelist, token aware, latency aware)
    LoadBalancingPolicy* chain = load_balancing_policy_->new_instance();
    if (token_aware_routing()) {
      chain = new TokenAwarePolicy(chain);
    }
    if (latency_aware()) {
      chain = new LatencyAwarePolicy(chain, latency_aware_routing_settings_);
    }
    return chain;
  }

  void set_load_balancing_policy(LoadBalancingPolicy* lbp) {
    if (lbp == NULL) return;
    load_balancing_policy_.reset(lbp);
  }

  SslContext* ssl_context() const { return ssl_context_.get(); }

  void set_ssl_context(SslContext* ssl_context) {
    ssl_context_.reset(ssl_context);
  }

  bool token_aware_routing() const { return token_aware_routing_; }

  void set_token_aware_routing(bool is_token_aware) { token_aware_routing_ = is_token_aware; }

  bool latency_aware() const { return latency_aware_routing_; }

  void set_latency_aware_routing(bool is_latency_aware) { latency_aware_routing_ = is_latency_aware; }

  void set_latency_aware_routing_settings(const LatencyAwarePolicy::Settings& settings) {
    latency_aware_routing_settings_ = settings;
  }

  bool tcp_nodelay_enable() const { return tcp_nodelay_enable_; }

  void set_tcp_nodelay(bool enable) {
    tcp_nodelay_enable_ = enable;
  }

  bool tcp_keepalive_enable() const { return tcp_keepalive_enable_; }
  unsigned tcp_keepalive_delay_secs() const { return tcp_keepalive_delay_secs_; }

  void set_tcp_keepalive(bool enable, unsigned delay_secs) {
    tcp_keepalive_enable_ = enable;
    tcp_keepalive_delay_secs_ = delay_secs;
  }

private:
  int port_;
  int protocol_version_;
  ContactPointList contact_points_;
  unsigned thread_count_io_;
  unsigned queue_size_io_;
  unsigned queue_size_event_;
  unsigned queue_size_log_;
  unsigned core_connections_per_host_;
  unsigned max_connections_per_host_;
  unsigned reconnect_wait_time_ms_;
  unsigned max_concurrent_creation_;
  unsigned max_requests_per_flush_;
  unsigned max_concurrent_requests_threshold_;
  unsigned write_bytes_high_water_mark_;
  unsigned write_bytes_low_water_mark_;
  unsigned pending_requests_high_water_mark_;
  unsigned pending_requests_low_water_mark_;
  unsigned connect_timeout_ms_;
  unsigned request_timeout_ms_;
  CassLogLevel log_level_;
  CassLogCallback log_callback_;
  void* log_data_;
  SharedRefPtr<AuthProvider> auth_provider_;
  SharedRefPtr<LoadBalancingPolicy> load_balancing_policy_;
  SharedRefPtr<SslContext> ssl_context_;
  bool token_aware_routing_;
  bool latency_aware_routing_;
  LatencyAwarePolicy::Settings latency_aware_routing_settings_;
  bool tcp_nodelay_enable_;
  bool tcp_keepalive_enable_;
  unsigned tcp_keepalive_delay_secs_;
};

} // namespace cass

#endif
<|endoftext|>


<commit_before>#include "CNinjaRope.h"

#include "util/vec.h"
#include "util/macros.h"
#include "gusgame.h"
#include "CGameObject.h"
#include "CWorm.h"
#include "part_type.h"
#ifndef DEDICATED_ONLY
#include "sprite_set.h"
#include "sprite.h"
#include "base_animator.h"
#include "animators.h"
#include "CViewport.h"
#endif
#include "part_type.h"
#include "CMap.h"
#include "context.h"

#include <vector>

using namespace std;

void CNinjaRope::gusInit()
{
	justCreated = false;
	active = false;
	attached = false;

	m_length = 0;
	m_angle = 0;
	m_angleSpeed = 0;
	m_animator = NULL;
	m_sprite = NULL;

	if(gusGame.NRPartType != NULL) {
#ifndef DEDICATED_ONLY
		m_sprite = gusGame.NRPartType->sprite;
		m_animator = gusGame.NRPartType->allocateAnimator();
#endif

		// Why this?? :OO // Re: Modders may want to make the rope leave trails or sth :o
		foreach(i, gusGame.NRPartType->timer)
		{
			timer.push_back( (*i)->createState() );
		}

	}
	else
		errors << "NinjaRope::NinjaRope: particle type is NULL" << endl;
}

void CNinjaRope::shoot(Vec _pos, Vec _spd)
{
	if(gusGame.NRPartType == NULL) return;

	pos() = CVec(_pos);
	velocity() = CVec(_spd);
	m_length = gusGame.options.ninja_rope_startDistance;

	justCreated = true;
	active = true;
	attached = false;

	m_angle = Vec(velocity()).getAngle();
	m_angleSpeed = 0;

	foreach(t, timer)
	{
		t->reset();
	}
}

void CNinjaRope::remove()
{
	active = false;
	justCreated = false;
	attached = false;
}

void CNinjaRope::think()
{
	if ( m_length > (float)(int)gusGame.options.ninja_rope_maxLength )
		m_length = (float)(int)gusGame.options.ninja_rope_maxLength;

	if (!active)
		return;

	if(gusGame.NRPartType == NULL)
		return;

	if ( justCreated && gusGame.NRPartType->creation )
	{
		gusGame.NRPartType->creation->run(this);
		justCreated = false;
	}

	for ( int i = 0; !deleteMe && i < gusGame.NRPartType->repeat; ++i)
	{
		pos() += velocity();

		BaseVec<long> ipos = BaseVec<long>(Vec(pos()));

		// TODO: Try to attach to worms/objects

		Vec diff(owner->pos(), pos());
		float curLen = (float)diff.length();
		Vec force(diff * gusGame.options.ninja_rope_pullForce);

		/*
		if(<attached to object>)
		{
			//Apply force to object
		}
		else
		*/
		if(!gusGame.level().getMaterial( ipos.x, ipos.y ).particle_pass)
		{
			if(!attached)
			{
				m_length = 450.f / 16.f - 1.0f;
				attached = true;
				velocity() = CVec();
				if ( gusGame.NRPartType->groundCollision  )
					gusGame.NRPartType->groundCollision->run(this);
			}
		}
		else
			attached = false;

		if(attached)
		{
			if(curLen > m_length)
			{
				owner->addSpeed(force / curLen);
			}
		}
		else
		{
			velocity().y += gusGame.NRPartType->gravity;

			if(curLen > m_length)
			{
				velocity() -= CVec(force) / curLen;
			}
		}

#ifndef DEDICATED_ONLY
		if ( m_animator )
			m_animator->tick();
#endif
	}
}

Angle CNinjaRope::getPointingAngle()
{
	return m_angle;
}

void CNinjaRope::addAngleSpeed( AngleDiff speed )
{
	m_angleSpeed += speed;
}

int CNinjaRope::getColour()
{
	if(gusGame.NRPartType)
		return gusGame.NRPartType->colour;
	else
		return 0;
}

CVec& CNinjaRope::getPosReference()
{
	return pos();
}

#ifndef DEDICATED_ONLY
void CNinjaRope::draw(CViewport *viewport)
{
	if(gusGame.NRPartType == NULL) return;

	ALLEGRO_BITMAP* where = viewport->dest;
	IVec rPos = viewport->convertCoords( IVec(Vec(pos())) );
	if (active)
	{
		if (!m_sprite)
			putpixel(where,rPos.x,rPos.y,gusGame.NRPartType->colour);
		else
		{
			m_sprite->getSprite(m_animator->getFrame(), m_angle)->draw(where,rPos.x,rPos.y);
		}
		if (gusGame.NRPartType->distortion)
		{
			gusGame.NRPartType->distortion->apply( where, rPos.x,rPos.y, gusGame.NRPartType->distortMagnitude );
		}
	}
}
#endif

void CNinjaRope::deleteThis() {
	notes << "CNinjaRope:deleteThis: " << owner->getName() << endl;

	finalize();

	if(luaReference)
	{
		lua.destroyReference(luaReference);
		luaReference.reset();
	}

	// dont delete the object itself because we store it in CClient.cWorms atm
	// also dont set deleted=true because we may reuse this object
}
<commit_msg>comment (Gus ninja_rope_maxLength)<commit_after>#include "CNinjaRope.h"

#include "util/vec.h"
#include "util/macros.h"
#include "gusgame.h"
#include "CGameObject.h"
#include "CWorm.h"
#include "part_type.h"
#ifndef DEDICATED_ONLY
#include "sprite_set.h"
#include "sprite.h"
#include "base_animator.h"
#include "animators.h"
#include "CViewport.h"
#endif
#include "part_type.h"
#include "CMap.h"
#include "context.h"

#include <vector>

using namespace std;

void CNinjaRope::gusInit()
{
	justCreated = false;
	active = false;
	attached = false;

	m_length = 0;
	m_angle = 0;
	m_angleSpeed = 0;
	m_animator = NULL;
	m_sprite = NULL;

	if(gusGame.NRPartType != NULL) {
#ifndef DEDICATED_ONLY
		m_sprite = gusGame.NRPartType->sprite;
		m_animator = gusGame.NRPartType->allocateAnimator();
#endif

		// Why this?? :OO // Re: Modders may want to make the rope leave trails or sth :o
		foreach(i, gusGame.NRPartType->timer)
		{
			timer.push_back( (*i)->createState() );
		}

	}
	else
		errors << "NinjaRope::NinjaRope: particle type is NULL" << endl;
}

void CNinjaRope::shoot(Vec _pos, Vec _spd)
{
	if(gusGame.NRPartType == NULL) return;

	pos() = CVec(_pos);
	velocity() = CVec(_spd);
	m_length = gusGame.options.ninja_rope_startDistance;

	justCreated = true;
	active = true;
	attached = false;

	m_angle = Vec(velocity()).getAngle();
	m_angleSpeed = 0;

	foreach(t, timer)
	{
		t->reset();
	}
}

void CNinjaRope::remove()
{
	active = false;
	justCreated = false;
	attached = false;
}

void CNinjaRope::think()
{
	// TODO: ninja_rope_maxLength is not really implemented/used correctly here, is it?
	// But is this original Gusanos code? Has this ever worked correctly?
	// It seems it was added in the latest Gus0.9c release but might not be used at all.
	if ( m_length > (float)(int)gusGame.options.ninja_rope_maxLength )
		m_length = (float)(int)gusGame.options.ninja_rope_maxLength;

	if (!active)
		return;

	if(gusGame.NRPartType == NULL)
		return;

	if ( justCreated && gusGame.NRPartType->creation )
	{
		gusGame.NRPartType->creation->run(this);
		justCreated = false;
	}

	for ( int i = 0; !deleteMe && i < gusGame.NRPartType->repeat; ++i)
	{
		pos() += velocity();

		BaseVec<long> ipos = BaseVec<long>(Vec(pos()));

		// TODO: Try to attach to worms/objects

		Vec diff(owner->pos(), pos());
		float curLen = (float)diff.length();
		Vec force(diff * gusGame.options.ninja_rope_pullForce);

		/*
		if(<attached to object>)
		{
			//Apply force to object
		}
		else
		*/
		if(!gusGame.level().getMaterial( ipos.x, ipos.y ).particle_pass)
		{
			if(!attached)
			{
				m_length = 450.f / 16.f - 1.0f;
				attached = true;
				velocity() = CVec();
				if ( gusGame.NRPartType->groundCollision  )
					gusGame.NRPartType->groundCollision->run(this);
			}
		}
		else
			attached = false;

		if(attached)
		{
			if(curLen > m_length)
			{
				owner->addSpeed(force / curLen);
			}
		}
		else
		{
			velocity().y += gusGame.NRPartType->gravity;

			if(curLen > m_length)
			{
				velocity() -= CVec(force) / curLen;
			}
		}

#ifndef DEDICATED_ONLY
		if ( m_animator )
			m_animator->tick();
#endif
	}
}

Angle CNinjaRope::getPointingAngle()
{
	return m_angle;
}

void CNinjaRope::addAngleSpeed( AngleDiff speed )
{
	m_angleSpeed += speed;
}

int CNinjaRope::getColour()
{
	if(gusGame.NRPartType)
		return gusGame.NRPartType->colour;
	else
		return 0;
}

CVec& CNinjaRope::getPosReference()
{
	return pos();
}

#ifndef DEDICATED_ONLY
void CNinjaRope::draw(CViewport *viewport)
{
	if(gusGame.NRPartType == NULL) return;

	ALLEGRO_BITMAP* where = viewport->dest;
	IVec rPos = viewport->convertCoords( IVec(Vec(pos())) );
	if (active)
	{
		if (!m_sprite)
			putpixel(where,rPos.x,rPos.y,gusGame.NRPartType->colour);
		else
		{
			m_sprite->getSprite(m_animator->getFrame(), m_angle)->draw(where,rPos.x,rPos.y);
		}
		if (gusGame.NRPartType->distortion)
		{
			gusGame.NRPartType->distortion->apply( where, rPos.x,rPos.y, gusGame.NRPartType->distortMagnitude );
		}
	}
}
#endif

void CNinjaRope::deleteThis() {
	notes << "CNinjaRope:deleteThis: " << owner->getName() << endl;

	finalize();

	if(luaReference)
	{
		lua.destroyReference(luaReference);
		luaReference.reset();
	}

	// dont delete the object itself because we store it in CClient.cWorms atm
	// also dont set deleted=true because we may reuse this object
}
<|endoftext|>


<commit_before>
#include "glm_pod_wrappers.hpp"
#include "magic_number.hpp"
#include "msh_builder.hpp"
#include "ucfb_reader.hpp"

#include "glm/gtc/quaternion.hpp"

namespace {

struct Xframe {
   pod::Mat3 rotation;
   pod::Vec3 position;
};

static_assert(std::is_pod_v<Xframe>);
static_assert(sizeof(Xframe) == 48);

struct Primitive_Data {
   msh::Primitive_type type;
   pod::Vec3 size;
};

static_assert(std::is_pod_v<Primitive_Data>);
static_assert(sizeof(Primitive_Data) == 16);

auto read_next_primitive(Ucfb_reader& primitives) -> msh::Collision_primitive
{
   msh::Collision_primitive msh_prim;

   primitives.read_child_strict<"NAME"_mn>();

   auto mask = primitives.read_child_strict_optional<"MASK"_mn>();

   if (mask) msh_prim.flags = mask->read_trivial<msh::Collision_flags>();

   msh_prim.parent = primitives.read_child_strict<"PRNT"_mn>().read_string();

   const auto xframe = primitives.read_child_strict<"XFRM"_mn>().read_trivial<Xframe>();

   msh_prim.rotation = glm::quat_cast(glm::mat3{xframe.rotation});
   msh_prim.position = xframe.position;

   const auto data =
      primitives.read_child_strict<"DATA"_mn>().read_trivial<Primitive_Data>();

   msh_prim.type = data.type;
   msh_prim.size = data.size;

   return msh_prim;
}
}

void handle_primitives(Ucfb_reader primitives, msh::Builders_map& builders)
{
   auto info = primitives.read_child_strict<"INFO"_mn>();

   std::string name{info.read_string_unaligned()};
   const auto primitive_count = info.read_trivial<std::int32_t>();

   auto& builder = builders[name];

   for (auto i = 0; i < primitive_count; ++i) {
      builder.add_collision_primitive(read_next_primitive(primitives));
   }
}<commit_msg>Fixed size error in read_next_primitive<commit_after>
#include "glm_pod_wrappers.hpp"
#include "magic_number.hpp"
#include "msh_builder.hpp"
#include "ucfb_reader.hpp"

#include "glm/gtc/quaternion.hpp"

namespace {

struct Xframe {
   pod::Mat3 rotation;
   pod::Vec3 position;
};

static_assert(std::is_pod_v<Xframe>);
static_assert(sizeof(Xframe) == 48);

struct Primitive_Data {
   msh::Primitive_type type;
   pod::Vec3 size;
};

static_assert(std::is_pod_v<Primitive_Data>);
static_assert(sizeof(Primitive_Data) == 16);

auto read_next_primitive(Ucfb_reader& primitives) -> msh::Collision_primitive
{
   msh::Collision_primitive msh_prim;

   primitives.read_child_strict<"NAME"_mn>();

   auto mask = primitives.read_child_strict_optional<"MASK"_mn>();

   if (mask) {
      msh_prim.flags =
         static_cast<msh::Collision_flags>(mask->read_trivial<std::uint8_t>());
   }

   msh_prim.parent = primitives.read_child_strict<"PRNT"_mn>().read_string();

   const auto xframe = primitives.read_child_strict<"XFRM"_mn>().read_trivial<Xframe>();

   msh_prim.rotation = glm::quat_cast(glm::mat3{xframe.rotation});
   msh_prim.position = xframe.position;

   const auto data =
      primitives.read_child_strict<"DATA"_mn>().read_trivial<Primitive_Data>();

   msh_prim.type = data.type;
   msh_prim.size = data.size;

   return msh_prim;
}
}

void handle_primitives(Ucfb_reader primitives, msh::Builders_map& builders)
{
   auto info = primitives.read_child_strict<"INFO"_mn>();

   std::string name{info.read_string_unaligned()};
   const auto primitive_count = info.read_trivial<std::int32_t>();

   auto& builder = builders[name];

   for (auto i = 0; i < primitive_count; ++i) {
      builder.add_collision_primitive(read_next_primitive(primitives));
   }
}<|endoftext|>


<commit_before>#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <string>

// Loriano: let's try Armadillo quick code
#include <armadillo>
#include <cassert>

#include <pcafitter.hpp>
#include <pcaffunctype.hpp>

#include <sys/stat.h>

namespace
{
  bool check_to_read (bool useonlyeven, bool useonlyodd, int i)
  {
    if (useonlyeven || useonlyodd)
    {
      if (useonlyeven)
      {
        if (!((i+1) % 2))
          return true;
      }

      if (useonlyodd)
      {
        if ((i+1) % 2)
          return true;
      }
    }
    else
      return true;

    return false;
  }

  double cot (double x)
  {
    return tan(M_PI_2 - x);
  }
}

using namespace pca;

bool pca::file_exists(const std::string& filename)
{
  struct stat buf;
  if (stat(filename.c_str(), &buf) != -1)
    return true;

  return false;
}

double pca::delta_phi(double phi1, double phi2) // http://cmslxr.fnal.gov/source/DataFormats/Math/interface/deltaPhi.h
{
  double result = phi1 - phi2;

  while (result > M_PI) result -= 2*M_PI;
  while (result <= -M_PI) result += 2*M_PI;

  return result;
}

void pca::read_armmat (const char * fname, arma::mat & cmtx)
{
  int n, m;
  std::ifstream myfilec(fname, std::ios::binary | std::ios::in);
  myfilec.read((char *)&n, sizeof(n));
  myfilec.read((char *)&m, sizeof(m));
  cmtx.set_size(n, m);
  for (int i=0; i<(int)cmtx.n_rows; i++)
  {
    for (int j=0; j<(int)cmtx.n_cols; j++)
    {
      double v;
      myfilec.read((char *)&v, sizeof(v));

      cmtx(i, j) = v;
    }
  }
  myfilec.close();
}

void pca::read_armvct (const char * fname, arma::rowvec & q)
{
  int n;
  std::ifstream myfileq(fname, std::ios::binary);
  myfileq.read((char*)&(n), sizeof(n));
  q.set_size(n);
  for (int i=0; i<(int)q.n_cols; i++)
  {
    double v;
    myfileq.read((char*)&v, sizeof(v));

    q(i) = v;
  }
  myfileq.close();
}

void pca::write_armmat (const char * fname, arma::mat & cmtx)
{
  std::ofstream myfilec(fname, std::ios::binary);
  myfilec.write((const char*)&(cmtx.n_rows), sizeof(cmtx.n_rows));
  myfilec.write((const char*)&(cmtx.n_cols), sizeof(cmtx.n_cols));
  for (int i=0; i<(int)cmtx.n_rows; i++)
    for (int j=0; j<(int)cmtx.n_cols; j++)
      myfilec.write((const char*)&(cmtx(i, j)), sizeof(cmtx(i, j)));
  myfilec.close();
}

void pca::write_armvct (const char * fname, arma::rowvec & q)
{
  std::ofstream myfileq(fname, std::ios::binary);
  myfileq.write((const char*)&(q.n_cols), sizeof(q.n_cols));
  for (int i=0; i<(int)q.n_cols; i++)
    myfileq.write((const char*)&(q(i)), sizeof(q(i)));
  myfileq.close();
}

void pca::write_to_file (const char * fname,
    const arma::mat & vec, int idx)
{
  std::ofstream myfile(fname);

  for (int i=0; i<(int)vec.n_rows; i++)
    myfile << vec(i, idx) << std::endl;

  myfile.close();
}

void pca::reading_from_file (const char * filename,
    arma::mat & paramin, arma::mat & coordin,
    arma::mat & layer, arma::mat & ladder,
    arma::mat & module,
    std::map<std::string, int> & subsectors,
    std::map<std::string, int> & subladders,
    std::vector<std::string> & subsectorslist,
    std::vector<std::string> & subladderslist,
    int num_of_ent, bool usesegid,
    bool useonlyeven, bool useonlyodd)
{

  std::string line;
  std::ifstream mytfp;
  mytfp.open (filename, std::ios::in);

  if (useonlyeven && useonlyodd)
  {
    useonlyeven = false;
    useonlyodd = false;
  }

  int counter = 0;
  std::getline (mytfp, line);
  for (int i = 0; i < num_of_ent; ++i)
  {
    int fake1, fake2;
    // valori aggiunti solo di controllo
    mytfp >> fake1 >> fake2 ;
#ifdef DEBUG
    std::cout << fake1 << " " << fake2 << std::endl;
#endif
    std::ostringstream osss, ossl;
    osss << std::setfill('0');
    ossl << std::setfill('0');

    for (int j = 0; j < NUMOFLAYER; ++j)
    {
      int a, b, c, segid;
      double x, y, z;

      mytfp >> x >>
               y >>
               z >>
               a >> b >> c >> segid; // segid I am reading because can be used as local ccordinate ?
                                       // in case of l1tkstubs is the tp value here

      if (check_to_read (useonlyeven,useonlyodd,i))
      {
        if (usesegid)
          coordin(counter, j) = (double) segid;
        else
        {
          coordin(counter, j*3) = x;
          coordin(counter, j*3+1) = y;
          coordin(counter, j*3+2) = z;
        }

        layer(counter, j) = a;
        ladder(counter, j) = b;
        module(counter, j) = c;

        osss << std::setw(2) << layer(counter, j);
        osss << std::setw(2) << ladder(counter, j);
        if (j != NUMOFLAYER-1)
          osss<<"-";

        ossl << std::setw(2) << layer(counter, j);
        ossl << std::setw(2) << ladder(counter, j);
        ossl << std::setw(2) << module(counter, j);
        if (j != NUMOFLAYER-1)
          ossl<<"-";
      }
    }

    if (check_to_read (useonlyeven,useonlyodd,i))
    {

      subsectorslist.push_back(osss.str());
      subladderslist.push_back(ossl.str());

      std::map<std::string, int>::iterator its = subsectors.find(osss.str());
      if (its == subsectors.end())
        subsectors[osss.str()] = 1;
      else
        subsectors[osss.str()] += 1;

      std::map<std::string, int>::iterator itl = subladders.find(ossl.str());
      if (itl == subladders.end())
        subladders[ossl.str()] = 1;
      else
        subladders[ossl.str()] += 1;
    }

    double ptread, phiread, d0read, etaread, z0read;

    mytfp >> ptread >>
             phiread >>
             d0read >>
             etaread >>
             z0read;

    if (check_to_read (useonlyeven,useonlyodd,i))
    {
      paramin(counter, PHIIDX) = phiread;
      paramin(counter, D0IDX) = d0read;
      paramin(counter, Z0IDX) = z0read;
      // lstorchi: I use this to diretcly convert input parameters into
      //     better parameters for the fitting
      // eta = -ln[tan(tetha / 2)]
      // tetha = 2 * arctan (e^(-eta))
      // cotan (tetha) = cotan (2 * arctan (e^(-eta)))
      paramin(counter, COTTETHAIDX) =  cot(2.0 * atan (exp (-1.0e0 * etaread)));
      // use 1/pt
      paramin(counter, ONEOVERPTIDX) = 1.0e0 / ptread;

      ++counter;
    }
  }

  mytfp.close();
}

int pca::numofline (const char * fname)
{
  int number_of_lines = 0;
  std::string line;
  std::ifstream myfile(fname);

  while (std::getline(myfile, line))
    ++number_of_lines;

  myfile.close();

  return number_of_lines;
}

void pca::reading_from_file_split (const pca::pcafitter & fitter,
     const char * filename,
     arma::mat & paramin, arma::mat & coordin,
     int num_of_ent, bool useonlyeven, bool useonlyodd,
     bool rzplane, bool rphiplane,
     double etamin, double etamax)
{
  int extdim = 9;
  std::string line;
  std::ifstream mytfp;
  mytfp.open (filename, std::ios::in);

  arma::mat paramread;
  arma::mat coordread;
  arma::vec etavals;

  coordread.set_size(num_of_ent, fitter.get_coordim());
  paramread.set_size(num_of_ent, fitter.get_paramdim());
  etavals.set_size(num_of_ent);

  if (useonlyeven && useonlyodd)
  {
    useonlyeven = false;
    useonlyodd = false;
  }

  int counter = 0;
  std::getline (mytfp, line);
  for (int i = 0; i < num_of_ent; ++i)
  {
    int fake1, fake2;
    // valori aggiunti solo di controllo
    mytfp >> fake1 >> fake2 ;
#ifdef DEBUG
    std::cout << fake1 << " " << fake2 << std::endl;
#endif
    std::ostringstream osss, ossl;
    osss << std::setfill('0');
    ossl << std::setfill('0');

    for (int j = 0; j < NUMOFLAYER; ++j)
    {
      int a, b, c, segid;
      double x, y, z;

      mytfp >> x >>
               y >>
               z >>
               a >> b >> c >> segid; // segid I am reading because can be used as local ccordinate ?
                                       // in case of l1tkstubs is the tp value here

      if (check_to_read (useonlyeven,useonlyodd,i))
      {
        double ri = sqrt(pow(x, 2.0) + pow (y, 2.0));

        if (rzplane)
        {
          coordread(counter, j*2) = z;
          coordread(counter, j*2+1) = ri;
        }
        else if (rphiplane)
        {
          double phii = asin(y/ri);

          coordread(counter, j*2) = phii;
          coordread(counter, j*2+1) = ri;
        }
      }
    }

    double ptread, phiread, d0read, etaread, z0read;

    mytfp >> ptread >>
             phiread >>
             d0read >>
             etaread >>
             z0read;

    if (check_to_read (useonlyeven,useonlyodd,i))
    {
      etavals(counter) = etaread;

      if (rzplane)
      {
        paramread(counter, SPLIT_Z0IDX) = z0read;
        // lstorchi: I use this to diretcly convert input parameters into
        //     better parameters for the fitting
        // eta = -ln[tan(tetha / 2)]
        // tetha = 2 * arctan (e^(-eta))
        // cotan (tetha) = cotan (2 * arctan (e^(-eta)))
        paramread(counter, SPLIT_COTTETHAIDX) =  cot(2.0 * atan (exp (-1.0e0 * etaread)));
        double tetha = atan(1.0 /  paramread(counter, SPLIT_COTTETHAIDX));
        std::cout << etaread << " " << tetha << std::endl;
      }
      else if (rphiplane)
      {
        paramread(counter, SPLIT_PHIIDX) = phiread;
        // use 1/pt
        paramread(counter, SPLIT_ONEOVERPTIDX) = 1.0e0 / ptread;
      }

      ++counter;
    }
  }

  assert (coordread.n_rows == paramread.n_rows);
  assert (etavals.n_rows == paramread.n_rows);

  extdim = 0;
  for (int i=0; i<(int)etavals.n_rows; ++i)
    if ((etavals(i) <= etamax) && (etavals(i) >= etamin))
      ++extdim;

  coordin.resize(extdim, fitter.get_coordim());
  paramin.resize(extdim, fitter.get_paramdim());

  //std::cout << "extdim: " << extdim << std::endl;

  counter = 0;
  for (int i=0; i<(int)etavals.n_rows; ++i)
  {
    if ((etavals(i) <= etamax) && (etavals(i) >= etamin))
    {
      for (int j=0; j<(int)paramread.n_cols; ++j)
      {
        paramin(counter, j) = paramread(i, j);
        //std::cout << "Track: " << counter+1 << std::endl;
        //std::cout <<  paramin(counter, j) << " from " <<
        //  paramread(i, j) << std::endl;
      }

      for (int j=0; j<(int)coordread.n_cols; ++j)
        coordin(counter, j) = coordread(i, j);

      ++counter;
    }
  }

  //std::cout << "counter: " << counter << std::endl;

  mytfp.close();
}

<commit_msg>comment<commit_after>#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <string>

// Loriano: let's try Armadillo quick code
#include <armadillo>
#include <cassert>

#include <pcafitter.hpp>
#include <pcaffunctype.hpp>

#include <sys/stat.h>

namespace
{
  bool check_to_read (bool useonlyeven, bool useonlyodd, int i)
  {
    if (useonlyeven || useonlyodd)
    {
      if (useonlyeven)
      {
        if (!((i+1) % 2))
          return true;
      }

      if (useonlyodd)
      {
        if ((i+1) % 2)
          return true;
      }
    }
    else
      return true;

    return false;
  }

  double cot (double x)
  {
    return tan(M_PI_2 - x);
  }
}

using namespace pca;

bool pca::file_exists(const std::string& filename)
{
  struct stat buf;
  if (stat(filename.c_str(), &buf) != -1)
    return true;

  return false;
}

double pca::delta_phi(double phi1, double phi2) // http://cmslxr.fnal.gov/source/DataFormats/Math/interface/deltaPhi.h
{
  double result = phi1 - phi2;

  while (result > M_PI) result -= 2*M_PI;
  while (result <= -M_PI) result += 2*M_PI;

  return result;
}

void pca::read_armmat (const char * fname, arma::mat & cmtx)
{
  int n, m;
  std::ifstream myfilec(fname, std::ios::binary | std::ios::in);
  myfilec.read((char *)&n, sizeof(n));
  myfilec.read((char *)&m, sizeof(m));
  cmtx.set_size(n, m);
  for (int i=0; i<(int)cmtx.n_rows; i++)
  {
    for (int j=0; j<(int)cmtx.n_cols; j++)
    {
      double v;
      myfilec.read((char *)&v, sizeof(v));

      cmtx(i, j) = v;
    }
  }
  myfilec.close();
}

void pca::read_armvct (const char * fname, arma::rowvec & q)
{
  int n;
  std::ifstream myfileq(fname, std::ios::binary);
  myfileq.read((char*)&(n), sizeof(n));
  q.set_size(n);
  for (int i=0; i<(int)q.n_cols; i++)
  {
    double v;
    myfileq.read((char*)&v, sizeof(v));

    q(i) = v;
  }
  myfileq.close();
}

void pca::write_armmat (const char * fname, arma::mat & cmtx)
{
  std::ofstream myfilec(fname, std::ios::binary);
  myfilec.write((const char*)&(cmtx.n_rows), sizeof(cmtx.n_rows));
  myfilec.write((const char*)&(cmtx.n_cols), sizeof(cmtx.n_cols));
  for (int i=0; i<(int)cmtx.n_rows; i++)
    for (int j=0; j<(int)cmtx.n_cols; j++)
      myfilec.write((const char*)&(cmtx(i, j)), sizeof(cmtx(i, j)));
  myfilec.close();
}

void pca::write_armvct (const char * fname, arma::rowvec & q)
{
  std::ofstream myfileq(fname, std::ios::binary);
  myfileq.write((const char*)&(q.n_cols), sizeof(q.n_cols));
  for (int i=0; i<(int)q.n_cols; i++)
    myfileq.write((const char*)&(q(i)), sizeof(q(i)));
  myfileq.close();
}

void pca::write_to_file (const char * fname,
    const arma::mat & vec, int idx)
{
  std::ofstream myfile(fname);

  for (int i=0; i<(int)vec.n_rows; i++)
    myfile << vec(i, idx) << std::endl;

  myfile.close();
}

void pca::reading_from_file (const char * filename,
    arma::mat & paramin, arma::mat & coordin,
    arma::mat & layer, arma::mat & ladder,
    arma::mat & module,
    std::map<std::string, int> & subsectors,
    std::map<std::string, int> & subladders,
    std::vector<std::string> & subsectorslist,
    std::vector<std::string> & subladderslist,
    int num_of_ent, bool usesegid,
    bool useonlyeven, bool useonlyodd)
{

  std::string line;
  std::ifstream mytfp;
  mytfp.open (filename, std::ios::in);

  if (useonlyeven && useonlyodd)
  {
    useonlyeven = false;
    useonlyodd = false;
  }

  int counter = 0;
  std::getline (mytfp, line);
  for (int i = 0; i < num_of_ent; ++i)
  {
    int fake1, fake2;
    // valori aggiunti solo di controllo
    mytfp >> fake1 >> fake2 ;
#ifdef DEBUG
    std::cout << fake1 << " " << fake2 << std::endl;
#endif
    std::ostringstream osss, ossl;
    osss << std::setfill('0');
    ossl << std::setfill('0');

    for (int j = 0; j < NUMOFLAYER; ++j)
    {
      int a, b, c, segid;
      double x, y, z;

      mytfp >> x >>
               y >>
               z >>
               a >> b >> c >> segid; // segid I am reading because can be used as local ccordinate ?
                                       // in case of l1tkstubs is the tp value here

      if (check_to_read (useonlyeven,useonlyodd,i))
      {
        if (usesegid)
          coordin(counter, j) = (double) segid;
        else
        {
          coordin(counter, j*3) = x;
          coordin(counter, j*3+1) = y;
          coordin(counter, j*3+2) = z;
        }

        layer(counter, j) = a;
        ladder(counter, j) = b;
        module(counter, j) = c;

        osss << std::setw(2) << layer(counter, j);
        osss << std::setw(2) << ladder(counter, j);
        if (j != NUMOFLAYER-1)
          osss<<"-";

        ossl << std::setw(2) << layer(counter, j);
        ossl << std::setw(2) << ladder(counter, j);
        ossl << std::setw(2) << module(counter, j);
        if (j != NUMOFLAYER-1)
          ossl<<"-";
      }
    }

    if (check_to_read (useonlyeven,useonlyodd,i))
    {

      subsectorslist.push_back(osss.str());
      subladderslist.push_back(ossl.str());

      std::map<std::string, int>::iterator its = subsectors.find(osss.str());
      if (its == subsectors.end())
        subsectors[osss.str()] = 1;
      else
        subsectors[osss.str()] += 1;

      std::map<std::string, int>::iterator itl = subladders.find(ossl.str());
      if (itl == subladders.end())
        subladders[ossl.str()] = 1;
      else
        subladders[ossl.str()] += 1;
    }

    double ptread, phiread, d0read, etaread, z0read;

    mytfp >> ptread >>
             phiread >>
             d0read >>
             etaread >>
             z0read;

    if (check_to_read (useonlyeven,useonlyodd,i))
    {
      paramin(counter, PHIIDX) = phiread;
      paramin(counter, D0IDX) = d0read;
      paramin(counter, Z0IDX) = z0read;
      // lstorchi: I use this to diretcly convert input parameters into
      //     better parameters for the fitting
      // eta = -ln[tan(tetha / 2)]
      // tetha = 2 * arctan (e^(-eta))
      // cotan (tetha) = cotan (2 * arctan (e^(-eta)))
      paramin(counter, COTTETHAIDX) =  cot(2.0 * atan (exp (-1.0e0 * etaread)));
      // use 1/pt
      paramin(counter, ONEOVERPTIDX) = 1.0e0 / ptread;

      ++counter;
    }
  }

  mytfp.close();
}

int pca::numofline (const char * fname)
{
  int number_of_lines = 0;
  std::string line;
  std::ifstream myfile(fname);

  while (std::getline(myfile, line))
    ++number_of_lines;

  myfile.close();

  return number_of_lines;
}

void pca::reading_from_file_split (const pca::pcafitter & fitter,
     const char * filename,
     arma::mat & paramin, arma::mat & coordin,
     int num_of_ent, bool useonlyeven, bool useonlyodd,
     bool rzplane, bool rphiplane,
     double etamin, double etamax)
{
  int extdim = 9;
  std::string line;
  std::ifstream mytfp;
  mytfp.open (filename, std::ios::in);

  arma::mat paramread;
  arma::mat coordread;
  arma::vec etavals;

  coordread.set_size(num_of_ent, fitter.get_coordim());
  paramread.set_size(num_of_ent, fitter.get_paramdim());
  etavals.set_size(num_of_ent);

  if (useonlyeven && useonlyodd)
  {
    useonlyeven = false;
    useonlyodd = false;
  }

  int counter = 0;
  std::getline (mytfp, line);
  for (int i = 0; i < num_of_ent; ++i)
  {
    int fake1, fake2;
    // valori aggiunti solo di controllo
    mytfp >> fake1 >> fake2 ;
#ifdef DEBUG
    std::cout << fake1 << " " << fake2 << std::endl;
#endif
    std::ostringstream osss, ossl;
    osss << std::setfill('0');
    ossl << std::setfill('0');

    for (int j = 0; j < NUMOFLAYER; ++j)
    {
      int a, b, c, segid;
      double x, y, z;

      mytfp >> x >>
               y >>
               z >>
               a >> b >> c >> segid; // segid I am reading because can be used as local ccordinate ?
                                       // in case of l1tkstubs is the tp value here

      if (check_to_read (useonlyeven,useonlyodd,i))
      {
        double ri = sqrt(pow(x, 2.0) + pow (y, 2.0));

        if (rzplane)
        {
          coordread(counter, j*2) = z;
          coordread(counter, j*2+1) = ri;
        }
        else if (rphiplane)
        {
          double phii = asin(y/ri);

          coordread(counter, j*2) = phii;
          coordread(counter, j*2+1) = ri;
        }
      }
    }

    double ptread, phiread, d0read, etaread, z0read;

    mytfp >> ptread >>
             phiread >>
             d0read >>
             etaread >>
             z0read;

    if (check_to_read (useonlyeven,useonlyodd,i))
    {
      etavals(counter) = etaread;

      if (rzplane)
      {
        paramread(counter, SPLIT_Z0IDX) = z0read;
        // lstorchi: I use this to diretcly convert input parameters into
        //     better parameters for the fitting
        // eta = -ln[tan(tetha / 2)]
        // tetha = 2 * arctan (e^(-eta))
        // cotan (tetha) = cotan (2 * arctan (e^(-eta)))
        paramread(counter, SPLIT_COTTETHAIDX) =  cot(2.0 * atan (exp (-1.0e0 * etaread)));
        //double tetha = atan(1.0 /  paramread(counter, SPLIT_COTTETHAIDX));
        //std::cout << etaread << " " << tetha * (180/M_PI) << std::endl;
        //just to visualize pseudorapidity
      }
      else if (rphiplane)
      {
        paramread(counter, SPLIT_PHIIDX) = phiread;
        // use 1/pt
        paramread(counter, SPLIT_ONEOVERPTIDX) = 1.0e0 / ptread;
      }

      ++counter;
    }
  }

  assert (coordread.n_rows == paramread.n_rows);
  assert (etavals.n_rows == paramread.n_rows);

  extdim = 0;
  for (int i=0; i<(int)etavals.n_rows; ++i)
    if ((etavals(i) <= etamax) && (etavals(i) >= etamin))
      ++extdim;

  coordin.resize(extdim, fitter.get_coordim());
  paramin.resize(extdim, fitter.get_paramdim());

  //std::cout << "extdim: " << extdim << std::endl;

  counter = 0;
  for (int i=0; i<(int)etavals.n_rows; ++i)
  {
    if ((etavals(i) <= etamax) && (etavals(i) >= etamin))
    {
      for (int j=0; j<(int)paramread.n_cols; ++j)
      {
        paramin(counter, j) = paramread(i, j);
        //std::cout << "Track: " << counter+1 << std::endl;
        //std::cout <<  paramin(counter, j) << " from " <<
        //  paramread(i, j) << std::endl;
      }

      for (int j=0; j<(int)coordread.n_cols; ++j)
        coordin(counter, j) = coordread(i, j);

      ++counter;
    }
  }

  //std::cout << "counter: " << counter << std::endl;

  mytfp.close();
}

<|endoftext|>


<commit_before>
/*!
	\file

	\author Igor Mironchik (igor.mironchik at gmail dot com).

	Copyright (c) 2014 Igor Mironchik

	Permission is hereby granted, free of charge, to any person
	obtaining a copy of this software and associated documentation
	files (the "Software"), to deal in the Software without
	restriction, including without limitation the rights to use,
	copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the
	Software is furnished to do so, subject to the following
	conditions:

	The above copyright notice and this permission notice shall be
	included in all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
	EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
	OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
	NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
	HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
	WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
	FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
	OTHER DEALINGS IN THE SOFTWARE.
*/

// Qt include.
#include <QObject>
#include <QtTest/QtTest>
#include <QSharedPointer>

// QtMWidgets include.
#include <QtMWidgets/Switch>

class TestSwitch
	:	public QObject
{
	Q_OBJECT

private slots:

	void initTestCase()
	{
		m_switch.reset( new QtMWidgets::Switch );

		m_font = m_switch->font();
		m_font.setBold( true );
		m_switch->setFont( m_font );

		m_switch->setOnText( QStringLiteral( "ON" ) );
		m_switch->setOffText( QStringLiteral( "OFF" ) );

		m_switch->show();

		QVERIFY( QTest::qWaitForWindowActive( m_switch.data() ) );

		m_delta = QPoint( m_switch->height() / 2, m_switch->height() / 2 );
	}

	void testSwitch()
	{
		QVERIFY( m_switch->state() == QtMWidgets::Switch::AcceptedUncheck );
		QVERIFY( m_switch->isChecked() == false );
		QVERIFY( m_switch->onText() == QStringLiteral( "ON" ) );
		QVERIFY( m_switch->offText() == QStringLiteral( "OFF" ) );

		QSignalSpy spy( m_switch.data(), &QtMWidgets::Switch::stateChanged );

		QTest::mouseClick( m_switch.data(), Qt::LeftButton, {}, m_delta, 20 );

		QVERIFY( spy.count() == 1 );

		QVERIFY( m_switch->state() == QtMWidgets::Switch::NotAcceptedCheck );
		QVERIFY( m_switch->isChecked() == true );

		m_switch->setState( QtMWidgets::Switch::AcceptedCheck );

		QVERIFY( m_switch->state() == QtMWidgets::Switch::AcceptedCheck );
		QVERIFY( m_switch->isChecked() == true );

		const auto w = m_switch->width() - 2;
		const auto m = qRound( (double) ( w - m_delta.x() * 2 + 2 ) / 2.5 );
		QTest::mousePress( m_switch.data(), Qt::LeftButton, {},
			QPoint( w - m_delta.x(), m_delta.y() ), 20 );
		QMouseEvent me( QEvent::MouseMove, QPoint( m, m_delta.y() ),
			Qt::LeftButton, Qt::LeftButton, {} );
		QApplication::sendEvent( m_switch.data(), &me );
		QTest::mouseRelease( m_switch.data(), Qt::LeftButton, {},
			QPoint( m, m_delta.y() ), 20 );

		QVERIFY( spy.count() == 3 );

		QVERIFY( m_switch->state() == QtMWidgets::Switch::NotAcceptedUncheck );
		QVERIFY( m_switch->isChecked() == false );

		m_switch->setState( QtMWidgets::Switch::AcceptedUncheck );

		QVERIFY( m_switch->state() == QtMWidgets::Switch::AcceptedUncheck );
		QVERIFY( m_switch->isChecked() == false );
	}

private:
	QSharedPointer< QtMWidgets::Switch > m_switch;
	QFont m_font;
	QPoint m_delta;
};

QTEST_MAIN( TestSwitch )

#include "main.moc"
<commit_msg>Add more tests of Switch.<commit_after>
/*!
	\file

	\author Igor Mironchik (igor.mironchik at gmail dot com).

	Copyright (c) 2014 Igor Mironchik

	Permission is hereby granted, free of charge, to any person
	obtaining a copy of this software and associated documentation
	files (the "Software"), to deal in the Software without
	restriction, including without limitation the rights to use,
	copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the
	Software is furnished to do so, subject to the following
	conditions:

	The above copyright notice and this permission notice shall be
	included in all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
	EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
	OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
	NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
	HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
	WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
	FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
	OTHER DEALINGS IN THE SOFTWARE.
*/

// Qt include.
#include <QObject>
#include <QtTest/QtTest>
#include <QSharedPointer>

// QtMWidgets include.
#include <QtMWidgets/Switch>

class TestSwitch
	:	public QObject
{
	Q_OBJECT

private slots:

	void initTestCase()
	{
		m_switch.reset( new QtMWidgets::Switch );

		m_font = m_switch->font();
		m_font.setBold( true );
		m_switch->setFont( m_font );

		m_switch->setOnText( QStringLiteral( "ON" ) );
		m_switch->setOffText( QStringLiteral( "OFF" ) );

		m_switch->show();

		QVERIFY( QTest::qWaitForWindowActive( m_switch.data() ) );

		m_delta = QPoint( m_switch->height() / 2, m_switch->height() / 2 );
	}

	void testSwitch()
	{
		QVERIFY( m_switch->state() == QtMWidgets::Switch::AcceptedUncheck );
		QVERIFY( m_switch->isChecked() == false );
		QVERIFY( m_switch->onText() == QStringLiteral( "ON" ) );
		QVERIFY( m_switch->offText() == QStringLiteral( "OFF" ) );

		QSignalSpy spy( m_switch.data(), &QtMWidgets::Switch::stateChanged );

		QTest::mouseClick( m_switch.data(), Qt::LeftButton, {}, m_delta, 20 );

		QVERIFY( spy.count() == 1 );

		QVERIFY( m_switch->state() == QtMWidgets::Switch::NotAcceptedCheck );
		QVERIFY( m_switch->isChecked() == true );

		m_switch->setState( QtMWidgets::Switch::AcceptedCheck );

		QVERIFY( m_switch->state() == QtMWidgets::Switch::AcceptedCheck );
		QVERIFY( m_switch->isChecked() == true );

		const auto w = m_switch->width();
		const auto m1 = qRound( (double) ( w - m_delta.x() * 2 + 2 ) / 2.5 );
		QTest::mousePress( m_switch.data(), Qt::LeftButton, {},
			QPoint( w - m_delta.x(), m_delta.y() ), 20 );
		QMouseEvent me1( QEvent::MouseMove, QPoint( m1, m_delta.y() ),
			Qt::LeftButton, Qt::LeftButton, {} );
		QApplication::sendEvent( m_switch.data(), &me1 );
		QTest::mouseRelease( m_switch.data(), Qt::LeftButton, {},
			QPoint( m1, m_delta.y() ), 20 );

		QVERIFY( spy.count() == 3 );

		QVERIFY( m_switch->state() == QtMWidgets::Switch::NotAcceptedUncheck );
		QVERIFY( m_switch->isChecked() == false );

		m_switch->setState( QtMWidgets::Switch::AcceptedUncheck );

		QVERIFY( m_switch->state() == QtMWidgets::Switch::AcceptedUncheck );
		QVERIFY( m_switch->isChecked() == false );

		const auto m2 = w - m_delta.x() * 2;
		QTest::mousePress( m_switch.data(), Qt::LeftButton, {},
			QPoint( m_delta.x(), m_delta.y() ), 20 );
		QMouseEvent me2( QEvent::MouseMove, QPoint( m2, m_delta.y() ),
			Qt::LeftButton, Qt::LeftButton, {} );
		QApplication::sendEvent( m_switch.data(), &me2 );
		QTest::mouseRelease( m_switch.data(), Qt::LeftButton, {},
			QPoint( m2, m_delta.y() ), 20 );

		QVERIFY( spy.count() == 5 );

		QVERIFY( m_switch->state() == QtMWidgets::Switch::NotAcceptedCheck );
		QVERIFY( m_switch->isChecked() == true );

		m_switch->setState( QtMWidgets::Switch::AcceptedCheck );

		QVERIFY( m_switch->state() == QtMWidgets::Switch::AcceptedCheck );
		QVERIFY( m_switch->isChecked() == true );

		QTest::mouseClick( m_switch.data(), Qt::LeftButton, {}, m_delta, 20 );

		QVERIFY( spy.count() == 7 );

		QVERIFY( m_switch->state() == QtMWidgets::Switch::NotAcceptedUncheck );
		QVERIFY( m_switch->isChecked() == false );
	}

private:
	QSharedPointer< QtMWidgets::Switch > m_switch;
	QFont m_font;
	QPoint m_delta;
};

QTEST_MAIN( TestSwitch )

#include "main.moc"
<|endoftext|>


<commit_before>#include "newcertificatewizard.h"

#include "ui_chooseprotocolpage.h"
#include "ui_enterdetailspage.h"
#include "ui_overviewpage.h"
#include "ui_resultpage.h"

using namespace Kleo;
using namespace Kleo::NewCertificateUi;

namespace {

    class ChooseProtocolPage : public QWizardPage {
        Q_OBJECT
    public:
        explicit ChooseProtocolPage( QWidget * p=0 )
            : QWizardPage( p ), ui()
        {
            ui.setupUi( this );
            registerField( "pgp", ui.pgpCLB );
            registerField( "x509", ui.x509CLB );
        }

    private Q_SLOTS:
        void slotPgpClicked() {
            done( true );
        }

        void slotX509Clicked() {
            done( false );
        }

        void done( bool pgp ) {
            QMetaObject::invokeMethod( wizard(), "next", Qt::QueuedConnection );
        }

    private:
        Ui_ChooseProtocolPage ui;
    };

    class EnterDetailsPage : public QWizardPage {
        Q_OBJECT
    public:
        explicit EnterDetailsPage( QWidget * p=0 )
            : QWizardPage( p ), ui()
        {
            ui.setupUi( this );
        }

    private:
        Ui_EnterDetailsPage ui;
    };

    class OverviewPage : public QWizardPage {
        Q_OBJECT
    public:
        explicit OverviewPage( QWidget * p=0 )
            : QWizardPage( p ), ui()
        {

        }

    private:
        Ui_OverviewPage ui;
    };

    class ResultPage : public QWizardPage {
        Q_OBJECT
    public:
        explicit ResultPage( QWidget * p=0 )
            : QWizardPage( p ), ui()
        {

        }

    private:
        Ui_ResultPage ui;
    };
}

class NewCertificateWizard::Private {
    friend class ::Kleo::NewCertificateWizard;
    NewCertificateWizard * const q;
public:
    explicit Private( NewCertificateWizard * qq )
        : q( qq ),
          ui( q )
    {

    }

private:
    struct Ui {
        ChooseProtocolPage chooseProtocolPage;
        EnterDetailsPage enterDetailsPage;
        OverviewPage overviewPage;
        ResultPage resultPage;

        explicit Ui( NewCertificateWizard * q )
            : chooseProtocolPage( q ),
              enterDetailsPage( q ),
              overviewPage( q ),
              resultPage( q )
        {
            q->setPage( ChooseProtocolPageId, &chooseProtocolPage );
            q->setPage( EnterDetailsPageId,   &enterDetailsPage   );
            q->setPage( OverviewPageId,       &overviewPage       );
            q->setPage( ResultPageId,         &resultPage         );

            q->setStartId( ChooseProtocolPageId );
        }

    } ui;

};

NewCertificateWizard::NewCertificateWizard( QWidget * p )
    : QWizard( p ), d( new Private( this ) )
{

}

NewCertificateWizard::~NewCertificateWizard() {}

#include "moc_newcertificatewizard.cpp"
#include "newcertificatewizard.moc"
<commit_msg>Implement some of the Enter Details Page<commit_after>#include "newcertificatewizard.h"

#include "ui_chooseprotocolpage.h"
#include "ui_enterdetailspage.h"
#include "ui_overviewpage.h"
#include "ui_resultpage.h"

#include <kleo/dn.h>

#include <KConfigGroup>
#include <KGlobal>
#include <KLocale>
#include <KDebug>

#include <QRegExpValidator>
#include <QLineEdit>

using namespace Kleo;
using namespace Kleo::NewCertificateUi;

namespace {

    class ChooseProtocolPage : public QWizardPage {
        Q_OBJECT
    public:
        explicit ChooseProtocolPage( QWidget * p=0 )
            : QWizardPage( p ), ui()
        {
            ui.setupUi( this );
            registerField( "pgp", ui.pgpCLB );
            registerField( "x509", ui.x509CLB );
        }

    private Q_SLOTS:
        void slotPgpClicked() {
            done();
        }

        void slotX509Clicked() {
            done();
        }

        void done() {
            QMetaObject::invokeMethod( wizard(), "next", Qt::QueuedConnection );
        }

    private:
        Ui_ChooseProtocolPage ui;
    };

    class EnterDetailsPage : public QWizardPage {
        Q_OBJECT
    public:
        explicit EnterDetailsPage( QWidget * p=0 )
            : QWizardPage( p ), ui()
        {
            ui.setupUi( this );
            updateForm();
        }

        /* reimp */ bool isComplete() const;

    private:
        void updateForm();
        void clearForm();

    private:
        QVector< QPair<QString,QLineEdit*> > attributePairList;
        QList<QWidget*> dynamicWidgets;
        Ui_EnterDetailsPage ui;
    };

    class OverviewPage : public QWizardPage {
        Q_OBJECT
    public:
        explicit OverviewPage( QWidget * p=0 )
            : QWizardPage( p ), ui()
        {

        }

    private:
        Ui_OverviewPage ui;
    };

    class ResultPage : public QWizardPage {
        Q_OBJECT
    public:
        explicit ResultPage( QWidget * p=0 )
            : QWizardPage( p ), ui()
        {

        }

    private:
        Ui_ResultPage ui;
    };
}

class NewCertificateWizard::Private {
    friend class ::Kleo::NewCertificateWizard;
    NewCertificateWizard * const q;
public:
    explicit Private( NewCertificateWizard * qq )
        : q( qq ),
          ui( q )
    {

    }

private:
    struct Ui {
        ChooseProtocolPage chooseProtocolPage;
        EnterDetailsPage enterDetailsPage;
        OverviewPage overviewPage;
        ResultPage resultPage;

        explicit Ui( NewCertificateWizard * q )
            : chooseProtocolPage( q ),
              enterDetailsPage( q ),
              overviewPage( q ),
              resultPage( q )
        {
            q->setPage( ChooseProtocolPageId, &chooseProtocolPage );
            q->setPage( EnterDetailsPageId,   &enterDetailsPage   );
            q->setPage( OverviewPageId,       &overviewPage       );
            q->setPage( ResultPageId,         &resultPage         );

            q->setStartId( ChooseProtocolPageId );
        }

    } ui;

};

NewCertificateWizard::NewCertificateWizard( QWidget * p )
    : QWizard( p ), d( new Private( this ) )
{

}

NewCertificateWizard::~NewCertificateWizard() {}

static QString pgpLabel( const QString & attr ) {
    if ( attr == "NAME" )
        return i18n("Name");
    if ( attr == "COMMENT" )
        return i18n("Comment");
    if ( attr == "EMAIL" )
        return i18n("EMail");
    return QString();
}

static QString attributeLabel( const QString & attr, bool required, bool pgp ) {
  if ( attr.isEmpty() )
    return QString();
  const QString label = pgp ? pgpLabel( attr ) : Kleo::DNAttributeMapper::instance()->name2label( attr ) ;
  if ( !label.isEmpty() )
      if ( pgp )
          return label + ':';
      else
          return i18nc("Format string for the labels in the \"Your Personal Data\" page",
                       "%1 (%2):", label, attr );
  else
    return attr + ':';
}

static QString attributeFromKey( QString key ) {
  return key.remove( '!' );
}

namespace {
    class LineEdit : public QWidget {
        Q_OBJECT
    public:
        explicit LineEdit( const QString & text, bool required, QWidget * parent )
            : QWidget( parent ),
              lineEdit( text, this ),
              label( required ? i18n("(required)") : i18n("(optional)"), this ),
              layout( this )
        {
            KDAB_SET_OBJECT_NAME( lineEdit );
            KDAB_SET_OBJECT_NAME( label );
            KDAB_SET_OBJECT_NAME( layout );

            layout.addWidget( &lineEdit );
            layout.addWidget( &label );
        }

    public:
        QLineEdit lineEdit;
        QLabel label;
        QHBoxLayout layout;
    };
}

void EnterDetailsPage::updateForm() {

    clearForm();

    const KConfigGroup config( KGlobal::config(), "CertificateCreationWizard" );

    const bool pgp = field("pgp").toBool();

    QStringList attrOrder = config.readEntry( pgp ? "OpenPGPAttributeOrder" : "DNAttributeOrder", QStringList() );
    if ( attrOrder.empty() )
        if ( pgp )
            attrOrder << "NAME!" << "EMAIL!" << "COMMENT";
        else
            attrOrder << "CN!" << "L" << "OU" << "O!" << "C!" << "EMAIL!";

    Q_FOREACH( const QString & rawKey, attrOrder ) {
        const QString key = rawKey.trimmed().toUpper();
        const QString attr = attributeFromKey( key );
        if ( attr.isEmpty() )
            continue;
        const QString preset = config.readEntry( attr, QString() );
        const bool required = key.endsWith( QLatin1Char('!') );
        const QString label = config.readEntry( attr + "_label",
                                                attributeLabel( attr, required, pgp ) );

        LineEdit * const le = new LineEdit( preset, required, ui.formLayout->parentWidget() );
        ui.formLayout->addRow( label, le );

        if ( config.isEntryImmutable( attr ) )
            le->lineEdit.setEnabled( false );

        QString regex = config.readEntry( attr + "_regex" );
        if ( regex.isEmpty() )
            regex = "[^\\s].*"; // !empty
        le->lineEdit.setValidator( new QRegExpValidator( QRegExp( regex ), le ) );

        attributePairList.append( qMakePair(key, &le->lineEdit) );

        connect( &le->lineEdit, SIGNAL(textChanged(QString)),
                 SIGNAL(completeChanged()) );

        dynamicWidgets.push_back( ui.formLayout->labelForField( le ) );
        dynamicWidgets.push_back( le );
    }
}

void EnterDetailsPage::clearForm() {
    qDeleteAll( dynamicWidgets );
    dynamicWidgets.clear();
    attributePairList.clear();
}

static bool requirementsAreMet( const QVector< QPair<QString,QLineEdit*> > & list ) {
    for ( QVector< QPair<QString,QLineEdit*> >::const_iterator it = list.begin() ;
          it != list.end() ; ++it ) {
    const QLineEdit * le = (*it).second;
    if ( !le )
      continue;
    const QString key = (*it).first;
    kDebug() << "requirementsAreMet(): checking \"" << key << "\" against \"" << le->text() << "\":";
    if ( key.endsWith('!') && !le->hasAcceptableInput() ) {
      kDebug() << "required field has non-acceptable input!";
      return false;
    }
    kDebug() << "ok" << endl;
  }
  return true;
}

namespace {
    bool EnterDetailsPage::isComplete() const {
        return requirementsAreMet( attributePairList );
    }
}

#include "moc_newcertificatewizard.cpp"
#include "newcertificatewizard.moc"
<|endoftext|>


<commit_before>//
// Created by Miguel Rentes on 30/01/2017.
//

#include "STL.h"

void printKMax(int arr[], int n, int k) {
    deque<int> mydeque;
    int greatest = 0;
    int value = 0;
    int index = 0;
    std::deque<int>::iterator it;
    for (int i = 0; i < n; i++) {
        mydeque.push_front(arr[i]);
    }
    for (int i = 0; i <= n-k; i++) {
        it = mydeque.begin();
        while (index < k) {
            value = *it;
            if (value > greatest)
                greatest = value;
            it++;
            index++;
        }
        mydeque.pop_front();
        mydeque.push_back(greatest);
        greatest = 0;
        index = 0;
    }
    for (int i = 0; i <= n-k; i++) {
        cout << mydeque.back() << " ";
        mydeque.pop_back();
    }
    cout << endl;
}

int main(void) {
    int t;
    cin >> t;
    while (t > 0) {
        int n, k;
        cin >> n >> k;
        int i;
        int arr[n];
        for (i = 0; i < n; i++)
            cin >> arr[i];
        printKMax(arr, n, k);
        t--;
    }
    return EXIT_SUCCESS;
}<commit_msg>Starts solution for the Deque-STL challenge.<commit_after>//
// Created by Miguel Rentes on 30/01/2017.
//

#include "STL.h"

void printKMax(int arr[], int n, int k) {
    deque<int> mydeque;
    int greatest = 0;
    int value = 0;
    int index = 0;
    int iteration = 0;
    // pushing all the greatest values on each k-elements
    // to the front of the deque
    for (int i = 0; i < n; ) {
        if (index < k) {
            value = arr[i];
            if (value > greatest)
                greatest = value;
            if (index == k - 1) {
                mydeque.push_front(greatest);
                greatest = 0;
                index = 0;
                iteration++;
                i = iteration;
            } else {
                index++;
                i++;
            }
        }
    }
    // poping the greatest values
    // from the back of the deque
    while(mydeque.size() > 0) {
        cout << mydeque.back() << " ";
        mydeque.pop_back();
    }
    cout << endl;
}

int main(void) {
    int t;
    cin >> t;
    while (t > 0) {
        int n, k;
        cin >> n >> k;
        int i;
        int arr[n];
        for (i = 0; i < n; i++)
            cin >> arr[i];
        printKMax(arr, n, k);
        t--;
    }
    return EXIT_SUCCESS;
}<|endoftext|>