<commit_before>#include "csv.hpp"
#include <fstream>

using namespace std;

namespace cp
{

	void CSV::findMinMax(int result_index, bool isUseFilter, double minValue, double maxValue)
	{
		argMin.resize(data[0].size());
		argMax.resize(data[0].size());

		argMin[result_index] = DBL_MAX;
		argMax[result_index] = DBL_MIN;

		const int dsize = (int)argMin.size();
		if (isUseFilter)
		{
			for (int i = 0; i < data.size(); i++)
			{
				if (filter[i])
				{
					if (argMin[result_index] < data[i][result_index])
					{
						for (int j = 0; j < dsize; j++)
						{
							argMin[j] = data[i][j];
						}
					}
					if (argMax[result_index] > data[i][result_index])
					{
						for (int j = 0; j < dsize; j++)
						{
							argMax[j] = data[i][j];
						}
					}
				}
			}
		}
		else
		{
			for (int i = 0; i < data.size(); i++)
			{
				if (argMin[result_index] < data[i][result_index])
				{
					for (int j = 0; j < dsize; j++)
					{
						argMin[j] = data[i][j];
					}
				}
				if (argMax[result_index] > data[i][result_index])
				{
					for (int j = 0; j < dsize; j++)
					{
						argMax[j] = data[i][j];
					}
				}
			}
		}
		minValue = argMin[result_index];
		maxValue = argMax[result_index];
	}
	void CSV::initFilter()
	{
		filter.clear();
		for (int i = 0; i < data.size(); i++)
		{
			filter.push_back(true);
		}
	}
	void CSV::filterClear()
	{
		for (int i = 0; i < data.size(); i++)
		{
			filter[i] = true;
		}
	}
	void CSV::makeFilter(int index, double val, double emax)
	{
		for (int i = 0; i < data.size(); i++)
		{
			double diff = abs(data[i][index] - val);
			if (diff > emax)
			{
				filter[i] = false;
			}
		}
	}
	void CSV::readHeader()
	{
		fseek(fp, 0, SEEK_END);
		fileSize = ftell(fp);
		fseek(fp, 0, SEEK_SET);

		int countSep = 0;
		char str[1000];
		fgets(str, 1000, fp);
		for (int i = 0; i < strlen(str); i++)
		{
			switch (str[i])
			{
			case ',': countSep++;  break;
			}
		}
		width = countSep + 1;
	}
	void CSV::readData()
	{
		char vv[100];
		char* str = new char[fileSize];
		fileSize = (long)fread(str, sizeof(char), fileSize, fp);

		int c = 0;
		vector<double> v;
		for (int i = 0; i < fileSize; i++)
		{
			if (str[i] == ',')
			{
				vv[c] = '\0';
				double d = atof(vv);
				c = 0;
				v.push_back(d);
			}
			else if (str[i] == '\n')
			{
				vv[c] = '\0';
				double d = atof(vv);
				c = 0;
				v.push_back(d);

				/*for(int n=0;n<v.size();n++)
				cout<<v[n]<<",";
				cout<<endl;*/

				data.push_back(v);
				v.clear();
			}
			else
			{
				vv[c] = str[i];
				c++;
			}
		}

		delete[] str;
	}

	void CSV::init(string name, bool isWrite, bool isClear)
	{
		isTop = true;
		if (isWrite)
		{
			if (isClear)
			{
				fp = fopen(name.c_str(), "w");
			}
			else
			{
				fp = fopen(name.c_str(), "w+");
			}
			if (fp == NULL)
			{
				string n = name + "(1)";
				filename = n;
				fp = fopen(n.c_str(), "w");
			}
		}
		else
		{
			if (isClear)
			{
				fp = fopen(name.c_str(), "r");
			}
			else
			{
				fp = fopen(name.c_str(), "r+");
			}
			filename = name;
			if (fp == NULL)
			{
				cout << "file open error " << name << endl;
			}
			else
			{
				readHeader();
			}
		}
	}
	CSV::CSV()
	{
		fp = NULL;
	}
	CSV::CSV(string name, bool isWrite, bool isClear)
	{
		fp = NULL;
		init(name, isWrite, isClear);
	}

	CSV::~CSV()
	{
		if (fp != NULL) fclose(fp);
		//ifstream file1(filename);
		//ofstream file2("backup"+filename);
		//char ch;
		//while(file1 && file1.get(ch))
		//{
		//	file2.put(ch);
		//}
	}
	void CSV::write(string v)
	{
		if (isTop)
			fprintf(fp, "%s", v.c_str());
		else
		{
			if (isCommaSeparator)
				fprintf(fp, ",%s", v.c_str());
			else
				fprintf(fp, " %s", v.c_str());
		}

		isTop = false;
	}

	void CSV::write(int v)
	{
		if (isTop)
			fprintf(fp, "%d", v);
		else
		{
			if (isCommaSeparator)
				fprintf(fp, ",%d", v);
			else
				fprintf(fp, " %d", v);
		}

		isTop = false;
	}

	void CSV::write(double v)
	{
		if (isTop)
			fprintf(fp, "%f", v);
		else
		{
			if (isCommaSeparator)
			{
				fprintf(fp, ",%f", v);
			}
			else
			{
				fprintf(fp, " %f", v);
			}
		}
		isTop = false;
	}

	void CSV::end()
	{
		fprintf(fp, "\n");
		isTop = true;
	}

	void CSV::setSeparator(bool flag)
	{
		isCommaSeparator = flag;
	}

	template<typename srcType>
	void writeCSV_(string name, cv::Mat& src)
	{
		CSV csv(name, true, true);
		for (int i = 0; i < src.rows; i++)
		{
			for (int j = 0; j < src.cols; j++)
			{
				csv.write(src.at<srcType>(i, j));
			}
			csv.end();
		}
	}

	void writeCSV(string name, cv::InputArray src_)
	{
		cv::Mat src = src_.getMat();
		CV_Assert(src.channels() == 1);

		switch (src.depth())
		{
		case CV_8U: writeCSV_<uchar>(name, src); break;
		case CV_16S: writeCSV_<short>(name, src); break;
		case CV_16U: writeCSV_<ushort>(name, src); break;
		case CV_32S: writeCSV_<int>(name, src); break;
		case CV_32F: writeCSV_<float>(name, src); break;
		case CV_64F: writeCSV_<double>(name, src); break;
		default:
			break;
		}
	}
}<commit_msg>Update csv.cpp<commit_after>#include "csv.hpp"
#include <fstream>

using namespace std;

namespace cp
{

	void CSV::findMinMax(int result_index, bool isUseFilter, double minValue, double maxValue)
	{
		argMin.resize(data[0].size());
		argMax.resize(data[0].size());

		argMin[result_index] = DBL_MAX;
		argMax[result_index] = DBL_MIN;

		const int dsize = (int)argMin.size();
		if (isUseFilter)
		{
			for (int i = 0; i < data.size(); i++)
			{
				if (filter[i])
				{
					if (argMin[result_index] < data[i][result_index])
					{
						for (int j = 0; j < dsize; j++)
						{
							argMin[j] = data[i][j];
						}
					}
					if (argMax[result_index] > data[i][result_index])
					{
						for (int j = 0; j < dsize; j++)
						{
							argMax[j] = data[i][j];
						}
					}
				}
			}
		}
		else
		{
			for (int i = 0; i < data.size(); i++)
			{
				if (argMin[result_index] < data[i][result_index])
				{
					for (int j = 0; j < dsize; j++)
					{
						argMin[j] = data[i][j];
					}
				}
				if (argMax[result_index] > data[i][result_index])
				{
					for (int j = 0; j < dsize; j++)
					{
						argMax[j] = data[i][j];
					}
				}
			}
		}
		minValue = argMin[result_index];
		maxValue = argMax[result_index];
	}

	void CSV::initFilter()
	{
		filter.clear();
		for (int i = 0; i < data.size(); i++)
		{
			filter.push_back(true);
		}
	}

	void CSV::filterClear()
	{
		for (int i = 0; i < data.size(); i++)
		{
			filter[i] = true;
		}
	}

	void CSV::makeFilter(int index, double val, double emax)
	{
		for (int i = 0; i < data.size(); i++)
		{
			double diff = abs(data[i][index] - val);
			if (diff > emax)
			{
				filter[i] = false;
			}
		}
	}

	void CSV::readHeader()
	{
		fseek(fp, 0, SEEK_END);
		fileSize = ftell(fp);
		fseek(fp, 0, SEEK_SET);

		int countSep = 0;
		char str[1000];
		fgets(str, 1000, fp);
		for (int i = 0; i < strlen(str); i++)
		{
			switch (str[i])
			{
			case ',': countSep++;  break;
			}
		}
		width = countSep + 1;
	}

	void CSV::readData()
	{
		char vv[100];
		char* str = new char[fileSize];
		fileSize = (long)fread(str, sizeof(char), fileSize, fp);

		int c = 0;
		vector<double> v;
		for (int i = 0; i < fileSize; i++)
		{
			if (str[i] == ',')
			{
				vv[c] = '\0';
				double d = atof(vv);
				c = 0;
				v.push_back(d);
			}
			else if (str[i] == '\n')
			{
				vv[c] = '\0';
				double d = atof(vv);
				c = 0;
				v.push_back(d);

				/*for(int n=0;n<v.size();n++)
				cout<<v[n]<<",";
				cout<<endl;*/

				data.push_back(v);
				v.clear();
			}
			else
			{
				vv[c] = str[i];
				c++;
			}
		}

		delete[] str;
	}

	void CSV::init(string name, bool isWrite, bool isClear)
	{
		isTop = true;
		if (isWrite)
		{
			if (isClear)
			{
				fp = fopen(name.c_str(), "w");
			}
			else
			{
				fp = fopen(name.c_str(), "w+");
			}
			if (fp == NULL)
			{
				string n = name + "(1)";
				filename = n;
				fp = fopen(n.c_str(), "w");
			}
		}
		else
		{
			if (isClear)
			{
				fp = fopen(name.c_str(), "r");
			}
			else
			{
				fp = fopen(name.c_str(), "r+");
			}
			filename = name;
			if (fp == NULL)
			{
				cout << "file open error " << name << endl;
			}
			else
			{
				readHeader();
			}
		}
	}

	CSV::CSV()
	{
		fp = nullptr;
	}

	CSV::CSV(string name, bool isWrite, bool isClear)
	{
		fp = nullptr;
		init(name, isWrite, isClear);
	}

	CSV::~CSV()
	{
		if (fp != NULL) fclose(fp);
		//ifstream file1(filename);
		//ofstream file2("backup"+filename);
		//char ch;
		//while(file1 && file1.get(ch))
		//{
		//	file2.put(ch);
		//}
	}

	void CSV::write(string v)
	{
		if (isTop)
			fprintf(fp, "%s", v.c_str());
		else
		{
			if (isCommaSeparator)
				fprintf(fp, ",%s", v.c_str());
			else
				fprintf(fp, " %s", v.c_str());
		}

		isTop = false;
	}

	void CSV::write(int v)
	{
		if (isTop)
			fprintf(fp, "%d", v);
		else
		{
			if (isCommaSeparator)
				fprintf(fp, ",%d", v);
			else
				fprintf(fp, " %d", v);
		}

		isTop = false;
	}

	void CSV::write(double v)
	{
		if (isTop)
			fprintf(fp, "%f", v);
		else
		{
			if (isCommaSeparator)
			{
				fprintf(fp, ",%f", v);
			}
			else
			{
				fprintf(fp, " %f", v);
			}
		}
		isTop = false;
	}

	void CSV::end()
	{
		fprintf(fp, "\n");
		isTop = true;
	}

	void CSV::setSeparator(bool flag)
	{
		isCommaSeparator = flag;
	}

	template<typename srcType>
	void writeCSV_(string name, cv::Mat& src)
	{
		CSV csv(name, true, true);
		for (int i = 0; i < src.rows; i++)
		{
			for (int j = 0; j < src.cols; j++)
			{
				csv.write(src.at<srcType>(i, j));
			}
			csv.end();
		}
	}

	void writeCSV(string name, cv::InputArray src_)
	{
		cv::Mat src = src_.getMat();
		CV_Assert(src.channels() == 1);

		switch (src.depth())
		{
		case CV_8U: writeCSV_<uchar>(name, src); break;
		case CV_16S: writeCSV_<short>(name, src); break;
		case CV_16U: writeCSV_<ushort>(name, src); break;
		case CV_32S: writeCSV_<int>(name, src); break;
		case CV_32F: writeCSV_<float>(name, src); break;
		case CV_64F: writeCSV_<double>(name, src); break;
		default:
			break;
		}
	}
}<|endoftext|>


<commit_before>/*
 Copyright (c) 2017 Tuukka Norri
 This code is licensed under MIT license (see LICENSE for details).
 */

#include <cstdlib>
#include <iostream>
#include <unistd.h>
#include <vcf2multialign/generate_haplotypes.hh>
#include <vcf2multialign/util.hh>

#ifdef __linux__
#include <pthread_workqueue.h>
#endif

#include "cmdline.h"

namespace v2m	= vcf2multialign;

namespace {
	v2m::sv_handling sv_handling_method(enum_structural_variants const sva)
	{
		switch (sva)
		{
			case structural_variants_arg_discard:
				return v2m::sv_handling::DISCARD;

			case structural_variants_arg_keep:
				return v2m::sv_handling::KEEP;

			case structural_variants__NULL:
			default:
				v2m::fail("Unexpected value for structural variant handling.");
				return v2m::sv_handling::KEEP; // Not reached.
		}
	}
}

int main(int argc, char **argv)
{
	gengetopt_args_info args_info;
	if (0 != cmdline_parser(argc, argv, &args_info))
		exit(EXIT_FAILURE);

	if (args_info.chunk_size_arg <= 0)
	{
		std::cerr << "Chunk size must be positive." << std::endl;
		exit(EXIT_FAILURE);
	}

	std::ios_base::sync_with_stdio(false);	// Don't use C style IO after calling cmdline_parser.
	std::cin.tie(nullptr);					// We don't require any input from the user.

	// libdispatch on macOS does not need pthread_workqueue.
#ifdef __linux__
	pthread_workqueue_init_np();
#endif

	v2m::generate_haplotypes(
		args_info.reference_arg,
		args_info.variants_arg,
		args_info.output_reference_arg,
		args_info.report_file_arg,
		args_info.null_allele_seq_arg,
		args_info.chunk_size_arg,
		args_info.variant_padding_arg,
		sv_handling_method(args_info.structural_variants_arg),
		args_info.overwrite_flag,
		!args_info.no_check_ref_flag,
		args_info.compress_variants_flag
	);

	// Not reached b.c. pthread_exit() is eventually called in generate_haplotypes().
	return EXIT_SUCCESS;
}
<commit_msg>Output a message in case assertions have been enabled<commit_after>/*
 Copyright (c) 2017 Tuukka Norri
 This code is licensed under MIT license (see LICENSE for details).
 */

#include <cstdlib>
#include <iostream>
#include <unistd.h>
#include <vcf2multialign/generate_haplotypes.hh>
#include <vcf2multialign/util.hh>

#ifdef __linux__
#include <pthread_workqueue.h>
#endif

#include "cmdline.h"

namespace v2m	= vcf2multialign;

namespace {
	v2m::sv_handling sv_handling_method(enum_structural_variants const sva)
	{
		switch (sva)
		{
			case structural_variants_arg_discard:
				return v2m::sv_handling::DISCARD;

			case structural_variants_arg_keep:
				return v2m::sv_handling::KEEP;

			case structural_variants__NULL:
			default:
				v2m::fail("Unexpected value for structural variant handling.");
				return v2m::sv_handling::KEEP; // Not reached.
		}
	}
}

int main(int argc, char **argv)
{
	gengetopt_args_info args_info;
	if (0 != cmdline_parser(argc, argv, &args_info))
		exit(EXIT_FAILURE);

	if (args_info.chunk_size_arg <= 0)
	{
		std::cerr << "Chunk size must be positive." << std::endl;
		exit(EXIT_FAILURE);
	}

	std::ios_base::sync_with_stdio(false);	// Don't use C style IO after calling cmdline_parser.
	std::cin.tie(nullptr);					// We don't require any input from the user.

#ifndef NDEBUG
	std::cerr << "Assertions have been enabled." << std::endl;
#endif

	// libdispatch on macOS does not need pthread_workqueue.
#ifdef __linux__
	pthread_workqueue_init_np();
#endif

	v2m::generate_haplotypes(
		args_info.reference_arg,
		args_info.variants_arg,
		args_info.output_reference_arg,
		args_info.report_file_arg,
		args_info.null_allele_seq_arg,
		args_info.chunk_size_arg,
		args_info.variant_padding_arg,
		sv_handling_method(args_info.structural_variants_arg),
		args_info.overwrite_flag,
		!args_info.no_check_ref_flag,
		args_info.compress_variants_flag
	);

	// Not reached b.c. pthread_exit() is eventually called in generate_haplotypes().
	return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include "fcam/Demosaic.h"
#include "fcam/Demosaic_ARM.h"

#include "benchmark.h"
#include "curved.h"
#include "halide_image.h"
#include "halide_image_io.h"

#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cassert>

using namespace Halide::Tools;

int main(int argc, char **argv) {
    if (argc < 7) {
        printf("Usage: ./process raw.png color_temp gamma contrast timing_iterations output.png\n"
               "e.g. ./process raw.png 3200 2 50 5 output.png");
        return 0;
    }

    Image<uint16_t> input = load_image(argv[1]);
    fprintf(stderr, "%d %d\n", input.width(), input.height());
    Image<uint8_t> output(((input.width() - 32)/32)*32, ((input.height() - 24)/32)*32, 3);

    // These color matrices are for the sensor in the Nokia N900 and are
    // taken from the FCam source.
    float _matrix_3200[][4] = {{ 1.6697f, -0.2693f, -0.4004f, -42.4346f},
                                {-0.3576f,  1.0615f,  1.5949f, -37.1158f},
                                {-0.2175f, -1.8751f,  6.9640f, -26.6970f}};

    float _matrix_7000[][4] = {{ 2.2997f, -0.4478f,  0.1706f, -39.0923f},
                                {-0.3826f,  1.5906f, -0.2080f, -25.4311f},
                                {-0.0888f, -0.7344f,  2.2832f, -20.0826f}};
    Image<float> matrix_3200(4, 3), matrix_7000(4, 3);
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 4; j++) {
            matrix_3200(j, i) = _matrix_3200[i][j];
            matrix_7000(j, i) = _matrix_7000[i][j];
        }
    }

    float color_temp = atof(argv[2]);
    float gamma = atof(argv[3]);
    float contrast = atof(argv[4]);
    int timing_iterations = atoi(argv[5]);

    double best;

    best = benchmark(timing_iterations, 1, [&]() {
        curved(color_temp, gamma, contrast,
               input, matrix_3200, matrix_7000, output);
    });
    fprintf(stderr, "Halide:\t%gus\n", best * 1e6);
    save_image(output, argv[6]);

    best = benchmark(timing_iterations, 1, [&]() {
        FCam::demosaic(input, output, color_temp, contrast, true, 25, gamma);
    });
    fprintf(stderr, "C++:\t%gus\n", best * 1e6);
    save_image(output, "fcam_c.png");

    best = benchmark(timing_iterations, 1, [&]() {;
        FCam::demosaic_ARM(input, output, color_temp, contrast, true, 25, gamma);
    });
    fprintf(stderr, "ASM:\t%gus\n", best * 1e6);
    save_image(output, "fcam_arm.png");

    // Timings on N900 as of SIGGRAPH 2012 camera ready are (best of 10)
    // Halide: 722ms, FCam: 741ms

    return 0;
}
<commit_msg>Avoid accidentally writing correct output images for reference results.<commit_after>#include "fcam/Demosaic.h"
#include "fcam/Demosaic_ARM.h"

#include "benchmark.h"
#include "curved.h"
#include "halide_image.h"
#include "halide_image_io.h"

#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cassert>

using namespace Halide::Tools;

int main(int argc, char **argv) {
    if (argc < 7) {
        printf("Usage: ./process raw.png color_temp gamma contrast timing_iterations output.png\n"
               "e.g. ./process raw.png 3200 2 50 5 output.png");
        return 0;
    }

    Image<uint16_t> input = load_image(argv[1]);
    fprintf(stderr, "%d %d\n", input.width(), input.height());
    Image<uint8_t> output(((input.width() - 32)/32)*32, ((input.height() - 24)/32)*32, 3);

    // These color matrices are for the sensor in the Nokia N900 and are
    // taken from the FCam source.
    float _matrix_3200[][4] = {{ 1.6697f, -0.2693f, -0.4004f, -42.4346f},
                                {-0.3576f,  1.0615f,  1.5949f, -37.1158f},
                                {-0.2175f, -1.8751f,  6.9640f, -26.6970f}};

    float _matrix_7000[][4] = {{ 2.2997f, -0.4478f,  0.1706f, -39.0923f},
                                {-0.3826f,  1.5906f, -0.2080f, -25.4311f},
                                {-0.0888f, -0.7344f,  2.2832f, -20.0826f}};
    Image<float> matrix_3200(4, 3), matrix_7000(4, 3);
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 4; j++) {
            matrix_3200(j, i) = _matrix_3200[i][j];
            matrix_7000(j, i) = _matrix_7000[i][j];
        }
    }

    float color_temp = atof(argv[2]);
    float gamma = atof(argv[3]);
    float contrast = atof(argv[4]);
    int timing_iterations = atoi(argv[5]);

    double best;

    best = benchmark(timing_iterations, 1, [&]() {
        curved(color_temp, gamma, contrast,
               input, matrix_3200, matrix_7000, output);
    });
    fprintf(stderr, "Halide:\t%gus\n", best * 1e6);
    save_image(output, argv[6]);

    Image<uint8_t> output_c(output.width(), output.height(), output.channels());
    best = benchmark(timing_iterations, 1, [&]() {
        FCam::demosaic(input, output_c, color_temp, contrast, true, 25, gamma);
    });
    fprintf(stderr, "C++:\t%gus\n", best * 1e6);
    save_image(output_c, "fcam_c.png");

    Image<uint8_t> output_asm(output.width(), output.height(), output.channels());
    best = benchmark(timing_iterations, 1, [&]() {;
        FCam::demosaic_ARM(input, output_asm, color_temp, contrast, true, 25, gamma);
    });
    fprintf(stderr, "ASM:\t%gus\n", best * 1e6);
    save_image(output_asm, "fcam_arm.png");

    // Timings on N900 as of SIGGRAPH 2012 camera ready are (best of 10)
    // Halide: 722ms, FCam: 741ms

    return 0;
}
<|endoftext|>


<commit_before>AliAnalysisVertexingHF* ConfigVertexingHF() {

  printf("Call to AliAnalysisVertexingHF parameters setting :\n");
  vHF = new AliAnalysisVertexingHF();

  //--- switch-off candidates finding (default: all on)
  //vHF->SetD0toKpiOff();
  vHF->SetJPSItoEleOff();
  //vHF->Set3ProngOff();
  //vHF->SetLikeSignOn(); // like-sign pairs and triplets
  vHF->Set4ProngOff();
  //vHF->SetDstarOff();
  vHF->SetFindVertexForDstar(kFALSE);
  //--- secondary vertex with KF?
  //vHF->SetSecVtxWithKF();
  vHF->SetCascadesOff();
  vHF->SetFindVertexForCascades(kFALSE);

  //--- set cuts for single-track selection
  //     displaced tracks
  AliESDtrackCuts *esdTrackCuts = new AliESDtrackCuts("AliESDtrackCuts","default");
  esdTrackCuts->SetRequireTPCRefit(kTRUE);
  esdTrackCuts->SetMinNClustersTPC(70);
  esdTrackCuts->SetRequireITSRefit(kTRUE);
  //esdTrackCuts->SetMinNClustersITS(4);
  esdTrackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD,
					 AliESDtrackCuts::kAny);
  esdTrackCuts->SetMinDCAToVertexXY(0.0100);
  esdTrackCuts->SetPtRange(0.8,1.e10);
  esdTrackCuts->SetEtaRange(-0.8,+0.8);
  AliAnalysisFilter *trkFilter = new AliAnalysisFilter("trackFilter");
  trkFilter->AddCuts(esdTrackCuts);
  vHF->SetTrackFilter(trkFilter);
  //     D* soft pion tracks
  AliESDtrackCuts *esdTrackCutsSoftPi = new AliESDtrackCuts("AliESDtrackCuts","default");
  esdTrackCutsSoftPi->SetMinNClustersITS(4);
  esdTrackCuts->SetPtRange(0.2,1.e10);
  esdTrackCutsSoftPi->SetEtaRange(-0.8,+0.8);
  AliAnalysisFilter *trkFilterSoftPi = new AliAnalysisFilter("trackFilterSoftPi");
  trkFilterSoftPi->AddCuts(esdTrackCutsSoftPi);
  vHF->SetTrackFilterSoftPi(trkFilterSoftPi);
  //--- set cuts for candidates selection
  AliRDHFCutsD0toKpi *cutsD0toKpi = new AliRDHFCutsD0toKpi("CutsD0toKpi");
  Float_t cutsArrayD0toKpi[9]={0.2,999999.,1.1,0.,0.,999999.,999999.,0.,0.5};
  cutsD0toKpi->SetCuts(9,cutsArrayD0toKpi);
  cutsD0toKpi->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsD0toKpi(cutsD0toKpi);
  AliRDHFCutsJpsitoee *cutsJpsitoee = new AliRDHFCutsJpsitoee("CutsJpsitoee");
  Float_t cutsArrayJpsitoee[9]={0.350,100000.,1.1,0.,0.,100000.,100000.,100000000.,-1.1};
  cutsJpsitoee->SetCuts(9,cutsArrayJpsitoee);
  cutsJpsitoee->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsJpsitoee(cutsJpsitoee);
  AliRDHFCutsDplustoKpipi *cutsDplustoKpipi = new AliRDHFCutsDplustoKpipi("CutsDplustoKpipi");
  Float_t cutsArrayDplustoKpipi[12]={0.2,0.8,0.8,0.,0.,0.01,0.06,0.03,0.,0.85,0.,10000000000.};
  cutsDplustoKpipi->SetCuts(12,cutsArrayDplustoKpipi);
  cutsDplustoKpipi->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsDplustoKpipi(cutsDplustoKpipi);
  AliRDHFCutsDstoKKpi *cutsDstoKKpi = new AliRDHFCutsDstoKKpi("CutsDstoKKpi");
  Float_t cutsArrayDstoKKpi[14]={0.,999.,999.,0.,0.,0.005,0.06,0.,0.,0.7,0.,1000.,0.1,0.1};
  cutsDstoKKpi->SetCuts(14,cutsArrayDstoKKpi);
  cutsDstoKKpi->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsDstoKKpi(cutsDstoKKpi);
  AliRDHFCutsLctopKpi *cutsLctopKpi = new AliRDHFCutsLctopKpi("CutsLctopKpi");
  //Float_t cutsArrayLctopKpi[12]={0.2,0.4,0.4,0.,0.,0.01,0.06,0.02,0.,0.85,0.,10000000000.};
  Float_t cutsArrayLctopKpi[12]={0.,999.,999.,0.,0.,0.01,0.06,0.005,0.7,0.,0.,0.05};
  cutsLctopKpi->SetCuts(12,cutsArrayLctopKpi);
  cutsLctopKpi->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsLctopKpi(cutsLctopKpi);
  AliRDHFCutsD0toKpipipi *cutsD0toKpipipi = new AliRDHFCutsD0toKpipipi("CutsD0toKpipipi");
  Float_t cutsArrayD0toKpipipi[9]={0.2,0.04,0.00,0.01,0.02,0.8,0.,0.1,0.};
  cutsD0toKpipipi->SetCuts(9,cutsArrayD0toKpipipi);
  cutsD0toKpipipi->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsD0toKpipipi(cutsD0toKpipipi);
  AliRDHFCutsDStartoKpipi *cutsDStartoKpipi = new AliRDHFCutsDStartoKpipi("CutsDStartoKpipi");
  Float_t cutsArrayDStartoKpipi[14]={0.15,0.07.,0.85,0.8,0.8,0.06.,0.06.,0.001,0.6,0.15, 0.03, 0.2, 5, 0.5}; // first 9 for D0 from D*, last 5 for D*
  cutsDStartoKpipi->SetCuts(14,cutsArrayDStartoKpipi);
  cutsDStartoKpipi->AddTrackCuts(esdTrackCuts);
  cutsDStartoKpipi->AddTrackCutsSoftPi(esdTrackCutsSoftPi);
  vHF->SetCutsDStartoKpipi(cutsDStartoKpipi);
  AliRDHFCutsLctoV0 *cutsLctoV0 = new AliRDHFCutsLctoV0("CutsLctoV0");
  Float_t cutsArrayLctoV0[9]={4.0,4.0,2.0,2.0,0.0,0.0,0.0,1000.,1000.};
  cutsLctoV0->SetCuts(9,cutsArrayLctoV0);
  cutsLctoV0->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsLctoV0(cutsLctoV0);
  //
  //--- set this if you want to reconstruct primary vertex candidate by
  //    candidate using other tracks in the event (for pp, broad
  //    interaction region)
  //vHF->SetRecoPrimVtxSkippingTrks();
  //--- OR set this if you want to remove the candidate daughters from
  //    the primary vertex, without recostructing it from scratch
  //vHF->SetRmTrksFromPrimVtx();

  //--- check the settings
  vHF->PrintStatus();
  //--- verbose
  //  AliLog::SetClassDebugLevel("AliAnalysisVertexingHF",2);

  return vHF;
}

<commit_msg>Bug fix<commit_after>AliAnalysisVertexingHF* ConfigVertexingHF() {

  printf("Call to AliAnalysisVertexingHF parameters setting :\n");
  vHF = new AliAnalysisVertexingHF();

  //--- switch-off candidates finding (default: all on)
  //vHF->SetD0toKpiOff();
  vHF->SetJPSItoEleOff();
  //vHF->Set3ProngOff();
  //vHF->SetLikeSignOn(); // like-sign pairs and triplets
  vHF->Set4ProngOff();
  //vHF->SetDstarOff();
  vHF->SetFindVertexForDstar(kFALSE);
  //--- secondary vertex with KF?
  //vHF->SetSecVtxWithKF();
  vHF->SetCascadesOff();
  vHF->SetFindVertexForCascades(kFALSE);

  //--- set cuts for single-track selection
  //     displaced tracks
  AliESDtrackCuts *esdTrackCuts = new AliESDtrackCuts("AliESDtrackCuts","default");
  esdTrackCuts->SetRequireTPCRefit(kTRUE);
  esdTrackCuts->SetMinNClustersTPC(70);
  esdTrackCuts->SetRequireITSRefit(kTRUE);
  //esdTrackCuts->SetMinNClustersITS(4);
  esdTrackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD,
					 AliESDtrackCuts::kAny);
  esdTrackCuts->SetMinDCAToVertexXY(0.0100);
  esdTrackCuts->SetPtRange(0.8,1.e10);
  esdTrackCuts->SetEtaRange(-0.8,+0.8);
  AliAnalysisFilter *trkFilter = new AliAnalysisFilter("trackFilter");
  trkFilter->AddCuts(esdTrackCuts);
  vHF->SetTrackFilter(trkFilter);
  //     D* soft pion tracks
  AliESDtrackCuts *esdTrackCutsSoftPi = new AliESDtrackCuts("AliESDtrackCuts","default");
  esdTrackCutsSoftPi->SetMinNClustersITS(4);
  esdTrackCutsSoftPi->SetPtRange(0.2,1.e10);
  esdTrackCutsSoftPi->SetEtaRange(-0.8,+0.8);
  AliAnalysisFilter *trkFilterSoftPi = new AliAnalysisFilter("trackFilterSoftPi");
  trkFilterSoftPi->AddCuts(esdTrackCutsSoftPi);
  vHF->SetTrackFilterSoftPi(trkFilterSoftPi);
  //--- set cuts for candidates selection
  AliRDHFCutsD0toKpi *cutsD0toKpi = new AliRDHFCutsD0toKpi("CutsD0toKpi");
  Float_t cutsArrayD0toKpi[9]={0.2,999999.,1.1,0.,0.,999999.,999999.,0.,0.5};
  cutsD0toKpi->SetCuts(9,cutsArrayD0toKpi);
  cutsD0toKpi->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsD0toKpi(cutsD0toKpi);
  AliRDHFCutsJpsitoee *cutsJpsitoee = new AliRDHFCutsJpsitoee("CutsJpsitoee");
  Float_t cutsArrayJpsitoee[9]={0.350,100000.,1.1,0.,0.,100000.,100000.,100000000.,-1.1};
  cutsJpsitoee->SetCuts(9,cutsArrayJpsitoee);
  cutsJpsitoee->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsJpsitoee(cutsJpsitoee);
  AliRDHFCutsDplustoKpipi *cutsDplustoKpipi = new AliRDHFCutsDplustoKpipi("CutsDplustoKpipi");
  Float_t cutsArrayDplustoKpipi[12]={0.2,0.8,0.8,0.,0.,0.01,0.06,0.03,0.,0.85,0.,10000000000.};
  cutsDplustoKpipi->SetCuts(12,cutsArrayDplustoKpipi);
  cutsDplustoKpipi->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsDplustoKpipi(cutsDplustoKpipi);
  AliRDHFCutsDstoKKpi *cutsDstoKKpi = new AliRDHFCutsDstoKKpi("CutsDstoKKpi");
  Float_t cutsArrayDstoKKpi[14]={0.,999.,999.,0.,0.,0.005,0.06,0.,0.,0.7,0.,1000.,0.1,0.1};
  cutsDstoKKpi->SetCuts(14,cutsArrayDstoKKpi);
  cutsDstoKKpi->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsDstoKKpi(cutsDstoKKpi);
  AliRDHFCutsLctopKpi *cutsLctopKpi = new AliRDHFCutsLctopKpi("CutsLctopKpi");
  //Float_t cutsArrayLctopKpi[12]={0.2,0.4,0.4,0.,0.,0.01,0.06,0.02,0.,0.85,0.,10000000000.};
  Float_t cutsArrayLctopKpi[12]={0.,999.,999.,0.,0.,0.01,0.06,0.005,0.7,0.,0.,0.05};
  cutsLctopKpi->SetCuts(12,cutsArrayLctopKpi);
  cutsLctopKpi->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsLctopKpi(cutsLctopKpi);
  AliRDHFCutsD0toKpipipi *cutsD0toKpipipi = new AliRDHFCutsD0toKpipipi("CutsD0toKpipipi");
  Float_t cutsArrayD0toKpipipi[9]={0.2,0.04,0.00,0.01,0.02,0.8,0.,0.1,0.};
  cutsD0toKpipipi->SetCuts(9,cutsArrayD0toKpipipi);
  cutsD0toKpipipi->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsD0toKpipipi(cutsD0toKpipipi);
  AliRDHFCutsDStartoKpipi *cutsDStartoKpipi = new AliRDHFCutsDStartoKpipi("CutsDStartoKpipi");
  Float_t cutsArrayDStartoKpipi[14]={0.15,0.07.,0.85,0.8,0.8,0.06.,0.06.,0.001,0.6,0.15, 0.03, 0.2, 5, 0.5}; // first 9 for D0 from D*, last 5 for D*
  cutsDStartoKpipi->SetCuts(14,cutsArrayDStartoKpipi);
  cutsDStartoKpipi->AddTrackCuts(esdTrackCuts);
  cutsDStartoKpipi->AddTrackCutsSoftPi(esdTrackCutsSoftPi);
  vHF->SetCutsDStartoKpipi(cutsDStartoKpipi);
  AliRDHFCutsLctoV0 *cutsLctoV0 = new AliRDHFCutsLctoV0("CutsLctoV0");
  Float_t cutsArrayLctoV0[9]={4.0,4.0,2.0,2.0,0.0,0.0,0.0,1000.,1000.};
  cutsLctoV0->SetCuts(9,cutsArrayLctoV0);
  cutsLctoV0->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsLctoV0(cutsLctoV0);
  //
  //--- set this if you want to reconstruct primary vertex candidate by
  //    candidate using other tracks in the event (for pp, broad
  //    interaction region)
  //vHF->SetRecoPrimVtxSkippingTrks();
  //--- OR set this if you want to remove the candidate daughters from
  //    the primary vertex, without recostructing it from scratch
  //vHF->SetRmTrksFromPrimVtx();

  //--- check the settings
  vHF->PrintStatus();
  //--- verbose
  //  AliLog::SetClassDebugLevel("AliAnalysisVertexingHF",2);

  return vHF;
}

<|endoftext|>


<commit_before>//--------------------------------------------------------------------------------------
// Copyright 2015 Intel Corporation
// All Rights Reserved
//
// Permission is granted to use, copy, distribute and prepare derivative works of this
// software for any purpose and without fee, provided, that the above copyright notice
// and this statement appear in all copies.  Intel makes no representations about the
// suitability of this software for any purpose.  THIS SOFTWARE IS PROVIDED "AS IS."
// INTEL SPECIFICALLY DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, AND ALL LIABILITY,
// INCLUDING CONSEQUENTIAL AND OTHER INDIRECT DAMAGES, FOR THE USE OF THIS SOFTWARE,
// INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PROPRIETARY RIGHTS, AND INCLUDING THE
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  Intel does not
// assume any responsibility for any errors which may appear in this software nor any
// responsibility to update it.
//--------------------------------------------------------------------------------------

#include "PresentMon.hpp"
#include "Util.hpp"
#include <algorithm>
#include <numeric>
#include <ctime>
#include <iterator>

#include <windows.h>
#include <psapi.h>
#include <shlwapi.h>

#pragma comment(lib, "psapi.lib")
#pragma comment(lib, "shlwapi.lib")

enum {
    MAX_HISTORY_TIME = 2000,
    MAX_DISPLAYED_HISTORY_TIME = 2000,
    CHAIN_TIMEOUT_THRESHOLD_TICKS = 10000 // 10 sec
};

template <typename Map, typename F>
static void map_erase_if(Map& m, F pred)
{
    typename Map::iterator i = m.begin();
    while ((i = std::find_if(i, m.end(), pred)) != m.end())
        m.erase(i++);
}

static void UpdateProcessInfo(ProcessInfo& info, uint64_t now, uint32_t thisPid)
{
    if (now - info.mLastRefreshTicks > 1000) {
        info.mLastRefreshTicks = now;
        char path[MAX_PATH] = "<error>";
        HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, thisPid);
        if (h) {
            GetModuleFileNameExA(h, NULL, path, sizeof(path) - 1);
            std::string name = PathFindFileNameA(path);
            if (name != info.mModuleName) {
                info.mChainMap.clear();
                info.mModuleName = name;
            }
            CloseHandle(h);
        } else {
            info.mChainMap.clear();
        }
    }
    // remove chains without recent updates
    map_erase_if(info.mChainMap, [now](const std::pair<const uint64_t, SwapChainData>& entry) {
        return now - entry.second.mLastUpdateTicks > CHAIN_TIMEOUT_THRESHOLD_TICKS;
    });
}

const char* PresentModeToString(PresentMode mode)
{
    switch (mode) {
    case PresentMode::Fullscreen: return "Fullscreen";
    case PresentMode::Composed_Flip: return "Windowed Flip";
    case PresentMode::DirectFlip: return "DirectFlip";
    case PresentMode::IndependentFlip: return "IndependentFlip";
    case PresentMode::ImmediateIndependentFlip: return "Immediate iFlip";
    case PresentMode::IndependentFlipMPO: return "iFlip MPO";
    case PresentMode::Fullscreen_Blit: return "Fullscreen Blit";
    case PresentMode::Windowed_Blit: return "Windowed Blit";
    case PresentMode::Legacy_Windowed_Blit: return "VistaBlit";
    case PresentMode::Composition_Buffer: return "Composition Buffer";
    default: return "Other";
    }
}

const char* RuntimeToString(Runtime rt)
{
    switch (rt) {
    case Runtime::DXGI: return "DXGI";
    case Runtime::D3D9: return "D3D9";
    default: return "Other";
    }
}

void PruneDeque(std::deque<PresentEvent> &presentHistory, uint64_t perfFreq, uint32_t msTimeDiff) {
    LARGE_INTEGER now;
    QueryPerformanceCounter(&now);

    while (!presentHistory.empty() &&
           ((double)(now.QuadPart - presentHistory.front().QpcTime) / perfFreq) * 1000 > msTimeDiff) {
        presentHistory.pop_front();
    }

    std::sort(presentHistory.begin(), presentHistory.end(),
              [](PresentEvent const& a, PresentEvent const& b) { return a.QpcTime < b.QpcTime; });
}

void AddPresent(PresentMonData& pm, PresentEvent& p, uint64_t now, uint64_t perfFreq)
{
    auto& proc = pm.mProcessMap[p.ProcessId];
    if (!proc.mLastRefreshTicks) {
        UpdateProcessInfo(proc, now, p.ProcessId);
    }

    if (pm.mArgs->mTargetProcessName && strcmp(pm.mArgs->mTargetProcessName, "*") &&
        _stricmp(pm.mArgs->mTargetProcessName, proc.mModuleName.c_str())) {
        // process name does not match
        return;
    }
    if (pm.mArgs->mTargetPid && p.ProcessId != pm.mArgs->mTargetPid) {
        return;
    }

    auto& chain = proc.mChainMap[p.SwapChainAddress];
    chain.mPresentHistory.push_back(p);

    if (p.FinalState == PresentResult::Presented) {
        PruneDeque(chain.mDisplayedPresentHistory, perfFreq, MAX_DISPLAYED_HISTORY_TIME);
        chain.mDisplayedPresentHistory.push_back(p);
    }

    chain.mLastUpdateTicks = now;
    chain.mRuntime = p.Runtime;
    chain.mLastSyncInterval = p.SyncInterval;
    chain.mLastFlags = p.PresentFlags;
    chain.mLastPresentMode = p.PresentMode;

    if (pm.mOutputFile) {
        auto len = chain.mPresentHistory.size();
        if (len > 2) {
            auto& curr = chain.mPresentHistory[len - 1];
            auto& prev = chain.mPresentHistory[len - 2];
            double deltaMilliseconds = 1000 * double(curr.QpcTime - prev.QpcTime) / perfFreq;
            double deltaReady = curr.ReadyTime == 0 ? 0.0 : (1000 * double(curr.ReadyTime - curr.QpcTime) / perfFreq);
            double deltaDisplayed = curr.ScreenTime == 0 ? 0.0 : (1000 * double(curr.ReadyTime - curr.QpcTime) / perfFreq);
            double timeTakenMilliseconds = 1000 * double(curr.TimeTaken) / perfFreq;
            fprintf(pm.mOutputFile, "%s,%d,0x%016llX,%s,%.3lf,%.3lf,%d,%d,%s,%.3lf,%.3lf,%d\n",
                proc.mModuleName.c_str(), p.ProcessId, p.SwapChainAddress, RuntimeToString(p.Runtime),
                    deltaMilliseconds, timeTakenMilliseconds, curr.SyncInterval, curr.PresentFlags, PresentModeToString(curr.PresentMode),
                    deltaReady, deltaDisplayed, curr.FinalState != PresentResult::Discarded);
        }
    }
}

static double ComputeFps(std::deque<PresentEvent> const& presentHistory, uint64_t qpcFreq)
{
    // TODO: better method
    if (presentHistory.size() < 2) {
        return 0.0;
    }
    auto start = presentHistory.front().QpcTime;
    auto end = presentHistory.back().QpcTime;
    auto count = presentHistory.size() - 1;

    double deltaT = double(end - start) / qpcFreq;
    return count / deltaT;
}

static double ComputeDisplayedFps(SwapChainData& stats, uint64_t qpcFreq)
{
    return ComputeFps(stats.mDisplayedPresentHistory, qpcFreq);
}

static double ComputeFps(SwapChainData& stats, uint64_t qpcFreq)
{
    return ComputeFps(stats.mPresentHistory, qpcFreq);
}

static double ComputeLatency(SwapChainData& stats, uint64_t qpcFreq)
{
    if (stats.mDisplayedPresentHistory.size() < 2) {
        return 0.0;
    }

    uint64_t totalLatency = std::accumulate(stats.mDisplayedPresentHistory.begin(), stats.mDisplayedPresentHistory.end() - 1, 0ull,
                                   [](uint64_t current, PresentEvent const& e) { return current + e.ScreenTime - e.QpcTime; });
    double average = ((double)(totalLatency) / qpcFreq) / (stats.mDisplayedPresentHistory.size() - 1);
    return average;
}

static double ComputeCpuFrameTime(SwapChainData& stats, uint64_t qpcFreq)
{
    if (stats.mPresentHistory.size() < 2) {
        return 0.0;
    }

    uint64_t timeInPresent = std::accumulate(stats.mPresentHistory.begin(), stats.mPresentHistory.end() - 1, 0ull,
                                   [](uint64_t current, PresentEvent const& e) { return current + e.TimeTaken; });
    uint64_t totalTime = stats.mPresentHistory.back().QpcTime - stats.mPresentHistory.front().QpcTime;

    double timeNotInPresent = double(totalTime - timeInPresent) / qpcFreq;
    return timeNotInPresent / (stats.mPresentHistory.size() - 1);
}

void PresentMon_Init(const PresentMonArgs& args, PresentMonData& pm)
{
    pm.mArgs = &args;

    if (args.mOutputFileName) {
        fopen_s(&pm.mOutputFile, args.mOutputFileName, "w");
    } else if (args.mTargetProcessName) {
        struct tm tm;
        time_t time_now = time(NULL);
        localtime_s(&tm, &time_now);
        std::string date = FormatString("%4d-%02d-%02d-%02d-%02d",
            tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
            tm.tm_hour, tm.tm_min, tm.tm_sec);
        std::string path;
        if (strchr(args.mTargetProcessName, '*')) {
            path = FormatString("PresentMon-%s.csv", date.c_str());
        } else {
            path = FormatString("PresentMon-%s-%s.csv", args.mTargetProcessName, date.c_str());
        }
        fopen_s(&pm.mOutputFile, path.c_str(), "w");
    }

    if (pm.mOutputFile) {
        fprintf(pm.mOutputFile, "module,pid,chain,runtime,delta,timeTaken,vsync,flags,mode,deltaReady,deltaDisplayed,displayed\n");
    }
}

void PresentMon_Update(PresentMonData& pm, std::vector<std::shared_ptr<PresentEvent>> presents, uint64_t perfFreq)
{
    std::string display;
    uint64_t now = GetTickCount64();

    // store the new presents into processes
    for (auto& p : presents)
    {
        AddPresent(pm, *p, now, perfFreq);
    }

    // update all processes
    for (auto& proc : pm.mProcessMap)
    {
        UpdateProcessInfo(proc.second, now, proc.first);
        if (proc.second.mModuleName.empty() ||
            proc.second.mChainMap.empty())
        {
            // don't display empty processes
            continue;
        }
        display += FormatString("%s[%d]:\n", proc.second.mModuleName.c_str(),proc.first);
        for (auto& chain : proc.second.mChainMap)
        {
            PruneDeque(chain.second.mPresentHistory, perfFreq, MAX_HISTORY_TIME);
            PruneDeque(chain.second.mDisplayedPresentHistory, perfFreq, MAX_DISPLAYED_HISTORY_TIME);

            double fps = ComputeFps(chain.second, perfFreq);
            double dispFps = ComputeDisplayedFps(chain.second, perfFreq);
            double cpuTime = ComputeCpuFrameTime(chain.second, perfFreq);
            double latency = ComputeLatency(chain.second, perfFreq);
            std::string planeString = "";
            if (chain.second.mLastPresentMode == PresentMode::IndependentFlipMPO) {
                planeString += " Plane ";
                planeString += chain.second.mDisplayedPresentHistory.back().PlaneIndex;
            }
            display += FormatString("\t%016llX (%s): SyncInterval %d | Flags %d | %.2lf ms/frame (%.1lf fps, %.1lf displayed fps, %.2lf ms CPU, %.2lf ms latency) (%s%s)%s\n",
                chain.first, RuntimeToString(chain.second.mRuntime), chain.second.mLastSyncInterval, chain.second.mLastFlags, 1000.0/fps, fps, dispFps, cpuTime * 1000.0, latency * 1000.0,
                PresentModeToString(chain.second.mLastPresentMode),
                planeString.c_str(),
                (now - chain.second.mLastUpdateTicks) > 1000 ? " [STALE]" : "");
        }
    }

    // refresh the console
    ClearConsole();
    printf(display.c_str());
}

void PresentMon_Shutdown(PresentMonData& pm)
{
    if (pm.mOutputFile)
    {
        fclose(pm.mOutputFile);
        pm.mOutputFile = nullptr;
    }
    pm.mProcessMap.clear();
}
<commit_msg>PROCESS_QUERY_INFORMATION -> PROCESS_QUERY_LIMITED_INFORMATION, allows capturing presents from protected processes (e.g. mfpmp).<commit_after>//--------------------------------------------------------------------------------------
// Copyright 2015 Intel Corporation
// All Rights Reserved
//
// Permission is granted to use, copy, distribute and prepare derivative works of this
// software for any purpose and without fee, provided, that the above copyright notice
// and this statement appear in all copies.  Intel makes no representations about the
// suitability of this software for any purpose.  THIS SOFTWARE IS PROVIDED "AS IS."
// INTEL SPECIFICALLY DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, AND ALL LIABILITY,
// INCLUDING CONSEQUENTIAL AND OTHER INDIRECT DAMAGES, FOR THE USE OF THIS SOFTWARE,
// INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PROPRIETARY RIGHTS, AND INCLUDING THE
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  Intel does not
// assume any responsibility for any errors which may appear in this software nor any
// responsibility to update it.
//--------------------------------------------------------------------------------------

#include "PresentMon.hpp"
#include "Util.hpp"
#include <algorithm>
#include <numeric>
#include <ctime>
#include <iterator>

#include <windows.h>
#include <psapi.h>
#include <shlwapi.h>

#pragma comment(lib, "psapi.lib")
#pragma comment(lib, "shlwapi.lib")

enum {
    MAX_HISTORY_TIME = 2000,
    MAX_DISPLAYED_HISTORY_TIME = 2000,
    CHAIN_TIMEOUT_THRESHOLD_TICKS = 10000 // 10 sec
};

template <typename Map, typename F>
static void map_erase_if(Map& m, F pred)
{
    typename Map::iterator i = m.begin();
    while ((i = std::find_if(i, m.end(), pred)) != m.end())
        m.erase(i++);
}

static void UpdateProcessInfo(ProcessInfo& info, uint64_t now, uint32_t thisPid)
{
    if (now - info.mLastRefreshTicks > 1000) {
        info.mLastRefreshTicks = now;
        char path[MAX_PATH] = "<error>";
        HANDLE h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, thisPid);
        if (h) {
            GetModuleFileNameExA(h, NULL, path, sizeof(path) - 1);
            std::string name = PathFindFileNameA(path);
            if (name != info.mModuleName) {
                info.mChainMap.clear();
                info.mModuleName = name;
            }
            CloseHandle(h);
        } else {
            info.mChainMap.clear();
        }
    }
    // remove chains without recent updates
    map_erase_if(info.mChainMap, [now](const std::pair<const uint64_t, SwapChainData>& entry) {
        return now - entry.second.mLastUpdateTicks > CHAIN_TIMEOUT_THRESHOLD_TICKS;
    });
}

const char* PresentModeToString(PresentMode mode)
{
    switch (mode) {
    case PresentMode::Fullscreen: return "Fullscreen";
    case PresentMode::Composed_Flip: return "Windowed Flip";
    case PresentMode::DirectFlip: return "DirectFlip";
    case PresentMode::IndependentFlip: return "IndependentFlip";
    case PresentMode::ImmediateIndependentFlip: return "Immediate iFlip";
    case PresentMode::IndependentFlipMPO: return "iFlip MPO";
    case PresentMode::Fullscreen_Blit: return "Fullscreen Blit";
    case PresentMode::Windowed_Blit: return "Windowed Blit";
    case PresentMode::Legacy_Windowed_Blit: return "VistaBlit";
    case PresentMode::Composition_Buffer: return "Composition Buffer";
    default: return "Other";
    }
}

const char* RuntimeToString(Runtime rt)
{
    switch (rt) {
    case Runtime::DXGI: return "DXGI";
    case Runtime::D3D9: return "D3D9";
    default: return "Other";
    }
}

void PruneDeque(std::deque<PresentEvent> &presentHistory, uint64_t perfFreq, uint32_t msTimeDiff) {
    LARGE_INTEGER now;
    QueryPerformanceCounter(&now);

    while (!presentHistory.empty() &&
           ((double)(now.QuadPart - presentHistory.front().QpcTime) / perfFreq) * 1000 > msTimeDiff) {
        presentHistory.pop_front();
    }

    std::sort(presentHistory.begin(), presentHistory.end(),
              [](PresentEvent const& a, PresentEvent const& b) { return a.QpcTime < b.QpcTime; });
}

void AddPresent(PresentMonData& pm, PresentEvent& p, uint64_t now, uint64_t perfFreq)
{
    auto& proc = pm.mProcessMap[p.ProcessId];
    if (!proc.mLastRefreshTicks) {
        UpdateProcessInfo(proc, now, p.ProcessId);
    }

    if (pm.mArgs->mTargetProcessName && strcmp(pm.mArgs->mTargetProcessName, "*") &&
        _stricmp(pm.mArgs->mTargetProcessName, proc.mModuleName.c_str())) {
        // process name does not match
        return;
    }
    if (pm.mArgs->mTargetPid && p.ProcessId != pm.mArgs->mTargetPid) {
        return;
    }

    auto& chain = proc.mChainMap[p.SwapChainAddress];
    chain.mPresentHistory.push_back(p);

    if (p.FinalState == PresentResult::Presented) {
        PruneDeque(chain.mDisplayedPresentHistory, perfFreq, MAX_DISPLAYED_HISTORY_TIME);
        chain.mDisplayedPresentHistory.push_back(p);
    }

    chain.mLastUpdateTicks = now;
    chain.mRuntime = p.Runtime;
    chain.mLastSyncInterval = p.SyncInterval;
    chain.mLastFlags = p.PresentFlags;
    chain.mLastPresentMode = p.PresentMode;

    if (pm.mOutputFile) {
        auto len = chain.mPresentHistory.size();
        if (len > 2) {
            auto& curr = chain.mPresentHistory[len - 1];
            auto& prev = chain.mPresentHistory[len - 2];
            double deltaMilliseconds = 1000 * double(curr.QpcTime - prev.QpcTime) / perfFreq;
            double deltaReady = curr.ReadyTime == 0 ? 0.0 : (1000 * double(curr.ReadyTime - curr.QpcTime) / perfFreq);
            double deltaDisplayed = curr.ScreenTime == 0 ? 0.0 : (1000 * double(curr.ReadyTime - curr.QpcTime) / perfFreq);
            double timeTakenMilliseconds = 1000 * double(curr.TimeTaken) / perfFreq;
            fprintf(pm.mOutputFile, "%s,%d,0x%016llX,%s,%.3lf,%.3lf,%d,%d,%s,%.3lf,%.3lf,%d\n",
                proc.mModuleName.c_str(), p.ProcessId, p.SwapChainAddress, RuntimeToString(p.Runtime),
                    deltaMilliseconds, timeTakenMilliseconds, curr.SyncInterval, curr.PresentFlags, PresentModeToString(curr.PresentMode),
                    deltaReady, deltaDisplayed, curr.FinalState != PresentResult::Discarded);
        }
    }
}

static double ComputeFps(std::deque<PresentEvent> const& presentHistory, uint64_t qpcFreq)
{
    // TODO: better method
    if (presentHistory.size() < 2) {
        return 0.0;
    }
    auto start = presentHistory.front().QpcTime;
    auto end = presentHistory.back().QpcTime;
    auto count = presentHistory.size() - 1;

    double deltaT = double(end - start) / qpcFreq;
    return count / deltaT;
}

static double ComputeDisplayedFps(SwapChainData& stats, uint64_t qpcFreq)
{
    return ComputeFps(stats.mDisplayedPresentHistory, qpcFreq);
}

static double ComputeFps(SwapChainData& stats, uint64_t qpcFreq)
{
    return ComputeFps(stats.mPresentHistory, qpcFreq);
}

static double ComputeLatency(SwapChainData& stats, uint64_t qpcFreq)
{
    if (stats.mDisplayedPresentHistory.size() < 2) {
        return 0.0;
    }

    uint64_t totalLatency = std::accumulate(stats.mDisplayedPresentHistory.begin(), stats.mDisplayedPresentHistory.end() - 1, 0ull,
                                   [](uint64_t current, PresentEvent const& e) { return current + e.ScreenTime - e.QpcTime; });
    double average = ((double)(totalLatency) / qpcFreq) / (stats.mDisplayedPresentHistory.size() - 1);
    return average;
}

static double ComputeCpuFrameTime(SwapChainData& stats, uint64_t qpcFreq)
{
    if (stats.mPresentHistory.size() < 2) {
        return 0.0;
    }

    uint64_t timeInPresent = std::accumulate(stats.mPresentHistory.begin(), stats.mPresentHistory.end() - 1, 0ull,
                                   [](uint64_t current, PresentEvent const& e) { return current + e.TimeTaken; });
    uint64_t totalTime = stats.mPresentHistory.back().QpcTime - stats.mPresentHistory.front().QpcTime;

    double timeNotInPresent = double(totalTime - timeInPresent) / qpcFreq;
    return timeNotInPresent / (stats.mPresentHistory.size() - 1);
}

void PresentMon_Init(const PresentMonArgs& args, PresentMonData& pm)
{
    pm.mArgs = &args;

    if (args.mOutputFileName) {
        fopen_s(&pm.mOutputFile, args.mOutputFileName, "w");
    } else if (args.mTargetProcessName) {
        struct tm tm;
        time_t time_now = time(NULL);
        localtime_s(&tm, &time_now);
        std::string date = FormatString("%4d-%02d-%02d-%02d-%02d",
            tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
            tm.tm_hour, tm.tm_min, tm.tm_sec);
        std::string path;
        if (strchr(args.mTargetProcessName, '*')) {
            path = FormatString("PresentMon-%s.csv", date.c_str());
        } else {
            path = FormatString("PresentMon-%s-%s.csv", args.mTargetProcessName, date.c_str());
        }
        fopen_s(&pm.mOutputFile, path.c_str(), "w");
    }

    if (pm.mOutputFile) {
        fprintf(pm.mOutputFile, "module,pid,chain,runtime,delta,timeTaken,vsync,flags,mode,deltaReady,deltaDisplayed,displayed\n");
    }
}

void PresentMon_Update(PresentMonData& pm, std::vector<std::shared_ptr<PresentEvent>> presents, uint64_t perfFreq)
{
    std::string display;
    uint64_t now = GetTickCount64();

    // store the new presents into processes
    for (auto& p : presents)
    {
        AddPresent(pm, *p, now, perfFreq);
    }

    // update all processes
    for (auto& proc : pm.mProcessMap)
    {
        UpdateProcessInfo(proc.second, now, proc.first);
        if (proc.second.mModuleName.empty() ||
            proc.second.mChainMap.empty())
        {
            // don't display empty processes
            continue;
        }
        display += FormatString("%s[%d]:\n", proc.second.mModuleName.c_str(),proc.first);
        for (auto& chain : proc.second.mChainMap)
        {
            PruneDeque(chain.second.mPresentHistory, perfFreq, MAX_HISTORY_TIME);
            PruneDeque(chain.second.mDisplayedPresentHistory, perfFreq, MAX_DISPLAYED_HISTORY_TIME);

            double fps = ComputeFps(chain.second, perfFreq);
            double dispFps = ComputeDisplayedFps(chain.second, perfFreq);
            double cpuTime = ComputeCpuFrameTime(chain.second, perfFreq);
            double latency = ComputeLatency(chain.second, perfFreq);
            std::string planeString = "";
            if (chain.second.mLastPresentMode == PresentMode::IndependentFlipMPO) {
                planeString += " Plane ";
                planeString += chain.second.mDisplayedPresentHistory.back().PlaneIndex;
            }
            display += FormatString("\t%016llX (%s): SyncInterval %d | Flags %d | %.2lf ms/frame (%.1lf fps, %.1lf displayed fps, %.2lf ms CPU, %.2lf ms latency) (%s%s)%s\n",
                chain.first, RuntimeToString(chain.second.mRuntime), chain.second.mLastSyncInterval, chain.second.mLastFlags, 1000.0/fps, fps, dispFps, cpuTime * 1000.0, latency * 1000.0,
                PresentModeToString(chain.second.mLastPresentMode),
                planeString.c_str(),
                (now - chain.second.mLastUpdateTicks) > 1000 ? " [STALE]" : "");
        }
    }

    // refresh the console
    ClearConsole();
    printf(display.c_str());
}

void PresentMon_Shutdown(PresentMonData& pm)
{
    if (pm.mOutputFile)
    {
        fclose(pm.mOutputFile);
        pm.mOutputFile = nullptr;
    }
    pm.mProcessMap.clear();
}
<|endoftext|>


<commit_before>void pythia6FastjetExample(Int_t nEvent = 50, Float_t e_cms = 2760, Float_t pthardmin = 10, Float_t pthardmax = 50) {

  // example macro for on-the-fly generation of PYTHIA6 events
  // and analysis with new reader interface and FastJet
  // M. van Leeuwen

  gSystem->Load("libANALYSIS");
  gSystem->Load("libANALYSISalice");
  gSystem->Load("libCGAL");
  gSystem->Load("libfastjet");
  gSystem->Load("libsiscone");
  gSystem->Load("libsiscone_spherical");
  gSystem->Load("libfastjetplugins");
  gSystem->Load("libJETAN");
  gSystem->Load("libFASTJETAN");

  gSystem->Load("libpythia6");
  gSystem->Load("libEGPythia6");
  gSystem->Load("liblhapdf");
  gSystem->Load("libAliPythia6");

  AliPDG::AddParticlesToPdgDataBase(); // to add some PDF codes to TDatabasePDG

  // Create random number generator and set seed
  AliPythiaRndm::SetPythiaRandom(new TRandom3());
  AliPythiaRndm::GetPythiaRandom()->SetSeed(clock()+gSystem->GetPid());

  AliGenPythia *pythia=new AliGenPythia(1);
  pythia->SetProcess(kPyJets);
  pythia->SetPtHard(pthardmin, pthardmax);
  pythia->SetEnergyCMS(e_cms);

  pythia->Init();

  //
  // Jet finder settings go via the FastJetHeader
  //
  AliFastJetHeaderV1 *header = new AliFastJetHeaderV1;
  header->SetBGMode(0);
  //  header->SetRadius(0.4);
  header->SetRparam(0.4);
  //header->SetGhostEtaMax(2);
  //header->SetGhostArea(0.05);
  header->SetAlgorithm(2); // antikt_algorithm = 2, kt = 0 (see fastjet/fastjet/JetDefinition.hh

  AliFastJetFinder *FastJet = new AliFastJetFinder;
  FastJet->SetJetHeader(header);

  // Infrastructure needed for AliGenPythia
  AliStack *stack = new AliStack();
  // There is a big mess with the connection between runloader, AliRun and the gAlice pointer.
  // This order of things seems to work...
  AliRunLoader *dummyrl = new AliRunLoader("dummyEvtFolder");
  dummyrl->MakeHeader();
  dummyrl->SetEventNumber(0);
  gAlice->SetRunLoader(dummyrl);
  pythia->SetStack(stack);

  // Set up dummy AOD event for JETAN output
  AliAODEvent *aod = new AliAODEvent();
  aod->CreateStdContent();
  FastJet->ConnectAOD(aod);

  // Set up input structures for FastJet
  AliJetCalTrkEvent JetFinderEvent(0,1);
  TClonesArray aliplist("AliMCParticle",1000);

  for (Int_t iEvent = 0; iEvent < nEvent; iEvent++) {

    TProcessID::SetObjectCount(0); // Needed for TRefs in AliCalTrkTrack and AliAODJet

    pythia->Generate();

    aliplist.Clear();
    JetFinderEvent.Clear();

    Int_t n_part = stack->GetNtrack();
    for (Int_t i_part = 0; i_part < n_part; i_part++) {
      part=(TParticle*) stack->Particle(i_part);

      if (part->GetStatusCode() >= 10)  // Not a final state particle
	continue;

      new (aliplist[i_part]) AliMCParticle(part);

      JetFinderEvent.AddCalTrkTrackKine((AliMCParticle*)aliplist[i_part],1,1);
    }

    aod->ClearStd();
    FastJet->Reset();
    FastJet->SetCalTrkEvent(JetFinderEvent);
    FastJet->ProcessEvent();
    if (aod->GetNJets() > 0) {
      cout << "event " << iEvent << " " << aod->GetNJets() << " jets found" << endl;
      for (Int_t iJet = 0; iJet < aod->GetNJets(); iJet++) {
	jet = aod->GetJet(iJet);
	cout << "\t jet " << iJet << " pt " << jet->Pt() << " eta " << jet->Eta() << " phi " << jet->Phi() << endl;
      }
    }
  }
}

// kept for backward compatibility; this was the old function name
void run(Int_t nEvent = 50, Float_t e_cms = 2760) {
  pythia6FastjetExample(nEvent, e_cms);
}
<commit_msg>Add stack->Reset()<commit_after>void pythia6FastjetExample(Int_t nEvent = 50, Float_t e_cms = 2760, Float_t pthardmin = 10, Float_t pthardmax = 50) {

  // example macro for on-the-fly generation of PYTHIA6 events
  // and analysis with new reader interface and FastJet
  // M. van Leeuwen

  gSystem->Load("libANALYSIS");
  gSystem->Load("libANALYSISalice");
  gSystem->Load("libCGAL");
  gSystem->Load("libfastjet");
  gSystem->Load("libsiscone");
  gSystem->Load("libsiscone_spherical");
  gSystem->Load("libfastjetplugins");
  gSystem->Load("libJETAN");
  gSystem->Load("libFASTJETAN");

  gSystem->Load("libpythia6");
  gSystem->Load("libEGPythia6");
  gSystem->Load("liblhapdf");
  gSystem->Load("libAliPythia6");

  AliPDG::AddParticlesToPdgDataBase(); // to add some PDF codes to TDatabasePDG

  // Create random number generator and set seed
  AliPythiaRndm::SetPythiaRandom(new TRandom3());
  AliPythiaRndm::GetPythiaRandom()->SetSeed(clock()+gSystem->GetPid());

  AliGenPythia *pythia=new AliGenPythia(1);
  pythia->SetProcess(kPyJets);
  pythia->SetPtHard(pthardmin, pthardmax);
  pythia->SetEnergyCMS(e_cms);

  pythia->Init();

  //
  // Jet finder settings go via the FastJetHeader
  //
  AliFastJetHeaderV1 *header = new AliFastJetHeaderV1;
  header->SetBGMode(0);
  //  header->SetRadius(0.4);
  header->SetRparam(0.4);
  //header->SetGhostEtaMax(2);
  //header->SetGhostArea(0.05);
  header->SetAlgorithm(2); // antikt_algorithm = 2, kt = 0 (see fastjet/fastjet/JetDefinition.hh

  AliFastJetFinder *FastJet = new AliFastJetFinder;
  FastJet->SetJetHeader(header);

  // Infrastructure needed for AliGenPythia
  AliStack *stack = new AliStack();
  // There is a big mess with the connection between runloader, AliRun and the gAlice pointer.
  // This order of things seems to work...
  AliRunLoader *dummyrl = new AliRunLoader("dummyEvtFolder");
  dummyrl->MakeHeader();
  dummyrl->SetEventNumber(0);
  gAlice->SetRunLoader(dummyrl);
  pythia->SetStack(stack);

  // Set up dummy AOD event for JETAN output
  AliAODEvent *aod = new AliAODEvent();
  aod->CreateStdContent();
  FastJet->ConnectAOD(aod);

  // Set up input structures for FastJet
  AliJetCalTrkEvent JetFinderEvent(0,1);
  TClonesArray aliplist("AliMCParticle",1000);

  for (Int_t iEvent = 0; iEvent < nEvent; iEvent++) {

    TProcessID::SetObjectCount(0); // Needed for TRefs in AliCalTrkTrack and AliAODJet

    stack->Reset();
    pythia->Generate();

    aliplist.Clear();
    JetFinderEvent.Clear();

    Int_t n_part = stack->GetNtrack();
    for (Int_t i_part = 0; i_part < n_part; i_part++) {
      part=(TParticle*) stack->Particle(i_part);

      if (part->GetStatusCode() >= 10)  // Not a final state particle
	continue;

      new (aliplist[i_part]) AliMCParticle(part);

      JetFinderEvent.AddCalTrkTrackKine((AliMCParticle*)aliplist[i_part],1,1);
    }

    aod->ClearStd();
    FastJet->Reset();
    FastJet->SetCalTrkEvent(JetFinderEvent);
    FastJet->ProcessEvent();
    if (aod->GetNJets() > 0) {
      cout << "event " << iEvent << " " << aod->GetNJets() << " jets found" << endl;
      for (Int_t iJet = 0; iJet < aod->GetNJets(); iJet++) {
	jet = aod->GetJet(iJet);
	cout << "\t jet " << iJet << " pt " << jet->Pt() << " eta " << jet->Eta() << " phi " << jet->Phi() << endl;
      }
    }
  }
}

// kept for backward compatibility; this was the old function name
void run(Int_t nEvent = 50, Float_t e_cms = 2760) {
  pythia6FastjetExample(nEvent, e_cms);
}
<|endoftext|>


<commit_before>/**
    @file UIText.cpp
    @brief Methods that sets UI messages, its positions and colors.
    @copyright LGPL. MIT License.
*/

#include "Components/UIText.hpp"

/**
    @brief Initializes UIText instance.
    @param[in] GameObject *owner - owns the component.
    @param[in] C_DRAW - physics component.
    @param[in] message - A string of the message that will be displayed.
    @param[in] fontPath - The path of the font that will be used.
    @param[in] size - The size of the character's sequence of the message.
    @param[in] r - The red component of the pixel in the range 0-255, type unsigned 8-bit integer.
    @param[in] g - The green component of the pixel in the range 0-255, type unsigned 8-bit integer.
    @param[in] b - The blue component of the pixel in the range 0-255, type unsigned 8-bit integer.
    @param[in] a - The alpha component of the pixel in the range 0-255, type unsigned 8-bit integer.
    @param[in] mode - The surface mode.
*/
UIText::UIText(GameObject *owner, string message, string fontPath, int size,
               Uint8 r, Uint8 g, Uint8 b, Uint8 a, Uint8 mode)
    : Component(owner, C_DRAW) {
    m_message = message;

    // Sets the x, y, width and height positions in a rectangle with the origin at the upper left.
    m_rect.x = owner->GetPosition()->m_x;
    m_rect.y = owner->GetPosition()->m_y;
    m_rect.w = owner->GetWidth();
    m_rect.h = owner->GetHeight();

    /*
        Sets the font based on a font file and create a font of the specified point size.
        Sets its color and background color.
    */
    m_font = TTF_OpenFont(fontPath.c_str(), size);
    if (!m_font)
        SDL_TTF_ERROR("Font could not be loaded");
    m_color = {r, g, b, a};

    m_background = {0, 0, 0, 0};

    m_mode = mode;

    OnPropertyChange();
}

void UIText::Start() {}

/**
    @brief Sets the UIText offset. Offset is the mean value of a wave,
    that creates periodic effect.
    @param[in] offset vector reference.
*/
void UIText::SetOffset(Vector &offset){
    m_offset = offset;
}

/**
    @brief Updates the position of the component that holds the text.
*/
void UIText::ComponentUpdate() {

    /*
        Sets the x, y, width and height positions of the rectangle component.
        Positions x and y are updated with the offset values.
        The new positions are used with the texture value to render the draw.
    */
    m_rect.x = GetOwner()->GetPosition()->m_x + m_offset.m_x;
    m_rect.y = GetOwner()->GetPosition()->m_y + m_offset.m_y;
    m_rect.w = GetOwner()->GetWidth();
    m_rect.h = GetOwner()->GetHeight();

    GraphicsSystem::GetInstance()->DrawText(m_texture, &m_rect);
}

/**
    @brief Updates the position of a fixed component.
*/
void UIText::FixedComponentUpdate() {}

/**
    @brief Sets the type of the surface of the UIText, and creates a texture from it.
*/
void UIText::OnPropertyChange() {
    m_surface = nullptr;

    // Sets the surface type based on the mode, to render the appropriated texture.
    switch (m_mode) {
    case 0:
        m_surface = TTF_RenderText_Solid(m_font, m_message.c_str(), m_color);
        break;
    case 1:
        m_surface = TTF_RenderText_Blended(m_font, m_message.c_str(), m_color);
        break;
    case 2:
        m_surface =
              TTF_RenderText_Shaded(m_font, m_message.c_str(), m_color, m_background);
  }

    m_texture = SDL_CreateTextureFromSurface(
        SDLSystem::GetInstance()->GetRenderer(), m_surface);

    SDL_FreeSurface(m_surface);
}

/**
    @brief Sets the text of the message that will be displayed.
    @param[in] text - A string of the message.
*/
void UIText::SetText(string text) {
    m_message = text;
    OnPropertyChange();
}

/**
    @brief Sets the color of the text.
    @param[in] r - The red component of the pixel in the range 0-255, type unsigned 8-bit integer.
    @param[in] g - The green component of the pixel in the range 0-255, type unsigned 8-bit integer.
    @param[in] b - The blue component of the pixel in the range 0-255, type unsigned 8-bit integer.
    @param[in] a - The alpha component of the pixel in the range 0-255, type unsigned 8-bit integer.

*/
void UIText::SetColor(Uint8 r, Uint8 g, Uint8 b, Uint8 a) {
    m_color = {r, g, b, a};
    OnPropertyChange();
}
<commit_msg>First comment control application: UIText     - Comment on control structe<commit_after>/**
    @file UIText.cpp
    @brief Methods that sets UI messages, its positions and colors.
    @copyright LGPL. MIT License.
*/

#include "Components/UIText.hpp"

/**
    @brief Initializes UIText instance.
    @param[in] GameObject *owner - owns the component.
    @param[in] C_DRAW - physics component.
    @param[in] message - A string of the message that will be displayed.
    @param[in] fontPath - The path of the font that will be used.
    @param[in] size - The size of the character's sequence of the message.
    @param[in] r - The red component of the pixel in the range 0-255, type unsigned 8-bit integer.
    @param[in] g - The green component of the pixel in the range 0-255, type unsigned 8-bit integer.
    @param[in] b - The blue component of the pixel in the range 0-255, type unsigned 8-bit integer.
    @param[in] a - The alpha component of the pixel in the range 0-255, type unsigned 8-bit integer.
    @param[in] mode - The surface mode.
*/
UIText::UIText(GameObject *owner, string message, string fontPath, int size,
               Uint8 r, Uint8 g, Uint8 b, Uint8 a, Uint8 mode)
    : Component(owner, C_DRAW) {
    m_message = message;

    // Sets the x, y, width and height positions in a rectangle with the origin at the upper left.
    m_rect.x = owner->GetPosition()->m_x;
    m_rect.y = owner->GetPosition()->m_y;
    m_rect.w = owner->GetWidth();
    m_rect.h = owner->GetHeight();

    /*
        Sets the font based on a font file and create a font of the specified point size.
        Sets its color and background color.
    */
    m_font = TTF_OpenFont(fontPath.c_str(), size);

    // Check if there is something diferent of the font and if is diferent print a error message.
    if (!m_font)
        SDL_TTF_ERROR("Font could not be loaded");
    m_color = {r, g, b, a};

    m_background = {0, 0, 0, 0};

    m_mode = mode;

    OnPropertyChange();
}

void UIText::Start() {}

/**
    @brief Sets the UIText offset. Offset is the mean value of a wave,
    that creates periodic effect.
    @param[in] offset vector reference.
*/
void UIText::SetOffset(Vector &offset){
    m_offset = offset;
}

/**
    @brief Updates the position of the component that holds the text.
*/
void UIText::ComponentUpdate() {

    /*
        Sets the x, y, width and height positions of the rectangle component.
        Positions x and y are updated with the offset values.
        The new positions are used with the texture value to render the draw.
    */
    m_rect.x = GetOwner()->GetPosition()->m_x + m_offset.m_x;
    m_rect.y = GetOwner()->GetPosition()->m_y + m_offset.m_y;
    m_rect.w = GetOwner()->GetWidth();
    m_rect.h = GetOwner()->GetHeight();

    GraphicsSystem::GetInstance()->DrawText(m_texture, &m_rect);
}

/**
    @brief Updates the position of a fixed component.
*/
void UIText::FixedComponentUpdate() {}

/**
    @brief Sets the type of the surface of the UIText, and creates a texture from it.
*/
void UIText::OnPropertyChange() {
    m_surface = nullptr;

    // Sets the surface type based on the mode, to render the appropriated texture.
    switch (m_mode) {
    case 0:
        m_surface = TTF_RenderText_Solid(m_font, m_message.c_str(), m_color);
        break;
    case 1:
        m_surface = TTF_RenderText_Blended(m_font, m_message.c_str(), m_color);
        break;
    case 2:
        m_surface =
              TTF_RenderText_Shaded(m_font, m_message.c_str(), m_color, m_background);
  }

    m_texture = SDL_CreateTextureFromSurface(
        SDLSystem::GetInstance()->GetRenderer(), m_surface);

    SDL_FreeSurface(m_surface);
}

/**
    @brief Sets the text of the message that will be displayed.
    @param[in] text - A string of the message.
*/
void UIText::SetText(string text) {
    m_message = text;
    OnPropertyChange();
}

/**
    @brief Sets the color of the text.
    @param[in] r - The red component of the pixel in the range 0-255, type unsigned 8-bit integer.
    @param[in] g - The green component of the pixel in the range 0-255, type unsigned 8-bit integer.
    @param[in] b - The blue component of the pixel in the range 0-255, type unsigned 8-bit integer.
    @param[in] a - The alpha component of the pixel in the range 0-255, type unsigned 8-bit integer.

*/
void UIText::SetColor(Uint8 r, Uint8 g, Uint8 b, Uint8 a) {
    m_color = {r, g, b, a};
    OnPropertyChange();
}
<|endoftext|>


<commit_before><commit_msg>Create 1564 - Brazil World Cup.cpp<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <hdf5.h>
#include <pandora/DataSet.hpp>

#include <cmath>

namespace pandora {

DataSet::DataSet(H5::DataSet dset)
	: h5dset(dset)
{
}

DataSet DataSet::create(const H5::CommonFG &parent,
	const std::string &name,
	DataType dtype,
	const PSize &size,
	const PSize *maxsize,
	const PSize *chunks)
{
	H5::DataType fileType = data_type_to_h5_filetype(dtype);
	H5::DataSpace space;

	if (size.size() > 0) {
		int rank = static_cast<int>(size.size());
		const hsize_t *maxdims = maxsize != nullptr ? &(*maxsize)[0] : nullptr;
		space = H5::DataSpace(rank, &size[0], maxdims);
	}

	H5::DSetCreatPropList plcreate = H5::DSetCreatPropList::DEFAULT;

	if (chunks != nullptr) {
		int rank = static_cast<int>(chunks->size());
		plcreate.setChunk(rank, &(*chunks)[0]);
	}

	H5::DataSet dset = parent.createDataSet(name, fileType, space);
	return DataSet(dset);
}

double psize_product(const PSize &dims)
{
	double product = 1;
	std::for_each(dims.begin(), dims.end(), [&](hsize_t val) {
		product *= val;
	});

	return product;
}

#define CHUNK_BASE   16*1024
#define CHUNK_MIN     8*1024
#define CHUNK_MAX  1024*1024

/**
 * Infer the chunk size from the supplied size information
 *
 * @param dims    Size information to base the guessing on
 * @param dtype   The type of the data to guess the chunks for
 *
 * This function is a port of the guess_chunk() function from h5py
 * low-level Python interface to the HDF5 library.\n
 * http://h5py.alfven.org\n
 *
 * @copyrigh 2008 - 2013 Andrew Collette & contributers\n
 * @license BSD 3-clause (see LICENSE.h5py)\n
 *
 * @return An (maybe not at all optimal) guess for chunk size
 */
PSize DataSet::guessChunking(PSize dims, DataType dtype)
{
	// original source:
	//    https://github.com/h5py/h5py/blob/2.1.3/h5py/_hl/filters.py

	if(dims.size() == 0) {
		throw 1;
	}

	PSize chunks(dims);
	const size_t type_size = data_type_to_size(dtype);
	double product = 1;
	std::for_each(dims.begin(), dims.end(), [&](hsize_t &val) {
		//todo: check for +infinity
		if (val == 0)
			val = 1024;

		product *= val;
	});

	product *= type_size;

	double target_size = CHUNK_BASE * pow(2, log10(product/(1024.0L * 1024.0L)));
	if (target_size > CHUNK_MAX)
		target_size = CHUNK_MAX;
	else if (target_size < CHUNK_MIN)
		target_size = CHUNK_MIN;

	size_t i = 0;
	while(true) {

		double csize = psize_product(chunks);
		if (csize == 1.0) {
			break;
		}

		double cbytes = csize * type_size;
		if ((cbytes < target_size || (abs(cbytes - target_size) / target_size) < 0.5)
			&& cbytes < CHUNK_MAX) {
			break;
		}

		//not done yet, one more iteration
		size_t idx = i % chunks.size();
		chunks[idx] = chunks[idx] >> 1; //divide by two
		i++;
	}

	return chunks;
}

void DataSet::extend(const PSize &dims)
{
	//FIXME check for same rank
	h5dset.extend(&dims[0]);
}

} //namespace pandora
<commit_msg>Fix typo in @copyright<commit_after>#include <iostream>
#include <hdf5.h>
#include <pandora/DataSet.hpp>

#include <cmath>

namespace pandora {

DataSet::DataSet(H5::DataSet dset)
	: h5dset(dset)
{
}

DataSet DataSet::create(const H5::CommonFG &parent,
	const std::string &name,
	DataType dtype,
	const PSize &size,
	const PSize *maxsize,
	const PSize *chunks)
{
	H5::DataType fileType = data_type_to_h5_filetype(dtype);
	H5::DataSpace space;

	if (size.size() > 0) {
		int rank = static_cast<int>(size.size());
		const hsize_t *maxdims = maxsize != nullptr ? &(*maxsize)[0] : nullptr;
		space = H5::DataSpace(rank, &size[0], maxdims);
	}

	H5::DSetCreatPropList plcreate = H5::DSetCreatPropList::DEFAULT;

	if (chunks != nullptr) {
		int rank = static_cast<int>(chunks->size());
		plcreate.setChunk(rank, &(*chunks)[0]);
	}

	H5::DataSet dset = parent.createDataSet(name, fileType, space);
	return DataSet(dset);
}

double psize_product(const PSize &dims)
{
	double product = 1;
	std::for_each(dims.begin(), dims.end(), [&](hsize_t val) {
		product *= val;
	});

	return product;
}

#define CHUNK_BASE   16*1024
#define CHUNK_MIN     8*1024
#define CHUNK_MAX  1024*1024

/**
 * Infer the chunk size from the supplied size information
 *
 * @param dims    Size information to base the guessing on
 * @param dtype   The type of the data to guess the chunks for
 *
 * This function is a port of the guess_chunk() function from h5py
 * low-level Python interface to the HDF5 library.\n
 * http://h5py.alfven.org\n
 *
 * @copyright Copyright 2008 - 2013 Andrew Collette & contributers\n
 * License: BSD 3-clause (see LICENSE.h5py)\n
 *
 * @return An (maybe not at all optimal) guess for chunk size
 */
PSize DataSet::guessChunking(PSize dims, DataType dtype)
{
	// original source:
	//    https://github.com/h5py/h5py/blob/2.1.3/h5py/_hl/filters.py

	if(dims.size() == 0) {
		throw 1;
	}

	PSize chunks(dims);
	const size_t type_size = data_type_to_size(dtype);
	double product = 1;
	std::for_each(dims.begin(), dims.end(), [&](hsize_t &val) {
		//todo: check for +infinity
		if (val == 0)
			val = 1024;

		product *= val;
	});

	product *= type_size;

	double target_size = CHUNK_BASE * pow(2, log10(product/(1024.0L * 1024.0L)));
	if (target_size > CHUNK_MAX)
		target_size = CHUNK_MAX;
	else if (target_size < CHUNK_MIN)
		target_size = CHUNK_MIN;

	size_t i = 0;
	while(true) {

		double csize = psize_product(chunks);
		if (csize == 1.0) {
			break;
		}

		double cbytes = csize * type_size;
		if ((cbytes < target_size || (abs(cbytes - target_size) / target_size) < 0.5)
			&& cbytes < CHUNK_MAX) {
			break;
		}

		//not done yet, one more iteration
		size_t idx = i % chunks.size();
		chunks[idx] = chunks[idx] >> 1; //divide by two
		i++;
	}

	return chunks;
}

void DataSet::extend(const PSize &dims)
{
	//FIXME check for same rank
	h5dset.extend(&dims[0]);
}

} //namespace pandora
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015 WinT 3794 <http://wint3794.org>
 *
 * 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.
 */

#include "LibDS/Core/ProtocolBase.h"

DS_ProtocolBase::DS_ProtocolBase() {
    m_team = 0;
    m_resetCount = 0;
    m_sentPackets = 0;
    m_robotCode = false;
    m_useFallbackAddress = false;
    m_communicationStatus = kFailing;
    m_alliance = kAllianceRed1;
    m_robotAddress = QString ("");
    m_controlMode = kControlNoCommunication;

    m_joysticks = new QList<DS_Joystick*>;

    connect (&m_watchdog, SIGNAL (timeout()), this, SLOT (reset()));
    connect (this, SIGNAL (packetReceived()), &m_watchdog, SLOT (restart()));
    connect (&m_pingSocket, SIGNAL (stateChanged   (QAbstractSocket::SocketState)),
             this,          SLOT   (onStateChanged (QAbstractSocket::SocketState)));
}

DS_ProtocolBase::~DS_ProtocolBase() {
    m_pingSocket.abort();
    delete m_joysticks;
}

int DS_ProtocolBase::team() const {
    return m_team;
}

int DS_ProtocolBase::status() const {
    return m_status;
}

bool DS_ProtocolBase::robotCode() const {
    return m_robotCode;
}

int DS_ProtocolBase::sentPackets() const {
    return m_sentPackets;
}

bool DS_ProtocolBase::isConnected() const {
    return communicationStatus() == kFull;
}

bool DS_ProtocolBase::sendDateTime() const {
    return m_sendDateTime;
}

DS_Alliance DS_ProtocolBase::alliance() const {
    return m_alliance;
}

DS_ControlMode DS_ProtocolBase::controlMode() const {
    return m_controlMode;
}

DS_CommunicationStatus DS_ProtocolBase::communicationStatus() const {
    return m_communicationStatus;
}

QList<DS_Joystick*>* DS_ProtocolBase::joysticks() const {
    return m_joysticks;
}

QString DS_ProtocolBase::radioAddress() {
    return m_radioAddress.isEmpty() ? defaultRadioAddress() : m_radioAddress;
}

QString DS_ProtocolBase::robotAddress() {
    if (m_robotAddress.isEmpty())
        return m_useFallbackAddress ? DS_GetStaticIp (team(),
                2) : defaultRobotAddress();

    return m_robotAddress;
}

QByteArray DS_ProtocolBase::getClientPacket() {
    m_sentPackets += 1;
    return generateClientPacket();
}

void DS_ProtocolBase::reset() {
    resetProtocol();

    updateVoltage (0, 0);
    updateRobotCode (false);
    updateSendDateTime (false);
    updateCommunications (kFailing);

    /* Toggle the usage of the fallback robot address every 5 resets */
    m_resetCount += 1;
    if (m_resetCount >= 5) {
        m_resetCount = 0;
        m_useFallbackAddress = !m_useFallbackAddress;
    }

    /* Figure out the robot address and ping the robot */
    emit robotAddressChanged (robotAddress());
    m_discovery.getIp (robotAddress(), this, SLOT (onIpFound (QString, QString)));
}

void DS_ProtocolBase::setTeamNumber (int team) {
    m_team = team;
    emit robotAddressChanged (robotAddress());
}

void DS_ProtocolBase::setRobotAddress (QString address) {
    m_robotAddress = address;
    emit robotAddressChanged (robotAddress());
}

void DS_ProtocolBase::setAlliance (DS_Alliance alliance) {
    m_alliance = alliance;
}

void DS_ProtocolBase::setControlMode (DS_ControlMode mode) {
    if (m_controlMode != kControlEmergencyStop) {
        m_controlMode = isConnected() ? mode : kControlNoCommunication;
        emit controlModeChanged (controlMode());
    }
}

void DS_ProtocolBase::setJoysticks (QList<DS_Joystick*>* joysticks) {
    m_joysticks = joysticks;
}

void DS_ProtocolBase::readRobotPacket (QByteArray data) {
    if (!data.isEmpty())
        readRobotData (data);
}

QByteArray DS_ProtocolBase::bitsToBytes (QBitArray bits) {
    QByteArray bytes (bits.count() / 8, 0);

    for (int i = 0; i < bits.count(); ++i)
        bytes [i / 8] = (bytes.at (i / 8) | ((bits [i] ? 1 : 0) << (i % 8)));

    return bytes;
}

void DS_ProtocolBase::updateStatus (int status) {
    m_status = status;
}

void DS_ProtocolBase::updateRobotCode (bool available) {
    m_robotCode = available;
    emit codeChanged (m_robotCode);
}

void DS_ProtocolBase::updateSendDateTime (bool sendDT) {
    m_sendDateTime = sendDT;
}

void DS_ProtocolBase::updateCommunications (DS_CommunicationStatus status) {
    m_communicationStatus = status;
    emit communicationsChanged (m_communicationStatus);
}

void DS_ProtocolBase::updateVoltage (char major, char minor) {
    QString maj = QString::number (major);
    QString min = QString::number (minor);

    maj = maj.replace ("-", "");
    min = min.replace ("-", "");

    if (min.length() == 1)
        min = QString ("0%1").arg (min);

    else if (min.length() > 2)
        min = QString (min.at (0)) + QString (min.at (1));

    emit voltageChanged (QString ("%1.%2").arg (maj, min));
}

void DS_ProtocolBase::pingRobot() {
    m_pingSocket.abort();
    m_pingSocket.connectToHost (robotAddress(), 80, QTcpSocket::ReadOnly);
}

void DS_ProtocolBase::onIpFound (QString address, QString ip) {
    if (address.toLower() == robotAddress().toLower())
        emit robotAddressChanged (ip);

    pingRobot();
}

void DS_ProtocolBase::onStateChanged (QAbstractSocket::SocketState state) {
    if (communicationStatus() == kFailing
            && state == QAbstractSocket::ConnectedState)
        updateCommunications (kPartial);
}
<commit_msg>Update ProtocolBase.cpp<commit_after>/*
 * Copyright (c) 2015 WinT 3794 <http://wint3794.org>
 *
 * 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.
 */

#include "LibDS/Core/ProtocolBase.h"

DS_ProtocolBase::DS_ProtocolBase() {
    m_team = 0;
    m_resetCount = 0;
    m_sentPackets = 0;
    m_robotCode = false;
    m_useFallbackAddress = false;
    m_communicationStatus = kFailing;
    m_alliance = kAllianceRed1;
    m_robotAddress = QString ("");
    m_controlMode = kControlNoCommunication;

    m_joysticks = new QList<DS_Joystick*>;

    connect (&m_watchdog, SIGNAL (timeout()), this, SLOT (reset()));
    connect (this, SIGNAL (packetReceived()), &m_watchdog, SLOT (restart()));
    connect (&m_pingSocket, SIGNAL (stateChanged   (QAbstractSocket::SocketState)),
             this,          SLOT   (onStateChanged (QAbstractSocket::SocketState)));
}

DS_ProtocolBase::~DS_ProtocolBase() {
    m_pingSocket.abort();
    delete m_joysticks;
}

int DS_ProtocolBase::team() const {
    return m_team;
}

int DS_ProtocolBase::status() const {
    return m_status;
}

bool DS_ProtocolBase::robotCode() const {
    return m_robotCode;
}

int DS_ProtocolBase::sentPackets() const {
    return m_sentPackets;
}

bool DS_ProtocolBase::isConnected() const {
    return communicationStatus() == kFull;
}

bool DS_ProtocolBase::sendDateTime() const {
    return m_sendDateTime;
}

DS_Alliance DS_ProtocolBase::alliance() const {
    return m_alliance;
}

DS_ControlMode DS_ProtocolBase::controlMode() const {
    return m_controlMode;
}

DS_CommunicationStatus DS_ProtocolBase::communicationStatus() const {
    return m_communicationStatus;
}

QList<DS_Joystick*>* DS_ProtocolBase::joysticks() const {
    return m_joysticks;
}

QString DS_ProtocolBase::radioAddress() {
    return m_radioAddress.isEmpty() ? defaultRadioAddress() : m_radioAddress;
}

QString DS_ProtocolBase::robotAddress() {
    if (m_robotAddress.isEmpty()) {
        if (m_useFallbackAddress)
            return DS_GetStaticIp (team(), 2);
        else
            return defaultRobotAddress();
    }

    return m_robotAddress;
}

QByteArray DS_ProtocolBase::getClientPacket() {
    m_sentPackets += 1;
    return generateClientPacket();
}

void DS_ProtocolBase::reset() {
    resetProtocol();

    updateVoltage (0, 0);
    updateRobotCode (false);
    updateSendDateTime (false);
    updateCommunications (kFailing);

    /* Toggle the usage of the fallback robot address every 5 resets */
    m_resetCount += 1;
    if (m_resetCount >= 5) {
        m_resetCount = 0;
        m_useFallbackAddress = !m_useFallbackAddress;
    }

    /* Figure out the robot address and ping the robot */
    emit robotAddressChanged (robotAddress());
    m_discovery.getIp (robotAddress(), this, SLOT (onIpFound (QString, QString)));
}

void DS_ProtocolBase::setTeamNumber (int team) {
    m_team = team;
    emit robotAddressChanged (robotAddress());
}

void DS_ProtocolBase::setRobotAddress (QString address) {
    m_robotAddress = address;
    emit robotAddressChanged (robotAddress());
}

void DS_ProtocolBase::setAlliance (DS_Alliance alliance) {
    m_alliance = alliance;
}

void DS_ProtocolBase::setControlMode (DS_ControlMode mode) {
    if (m_controlMode != kControlEmergencyStop) {
        m_controlMode = isConnected() ? mode : kControlNoCommunication;
        emit controlModeChanged (controlMode());
    }
}

void DS_ProtocolBase::setJoysticks (QList<DS_Joystick*>* joysticks) {
    m_joysticks = joysticks;
}

void DS_ProtocolBase::readRobotPacket (QByteArray data) {
    if (!data.isEmpty())
        readRobotData (data);
}

QByteArray DS_ProtocolBase::bitsToBytes (QBitArray bits) {
    QByteArray bytes (bits.count() / 8, 0);

    for (int i = 0; i < bits.count(); ++i)
        bytes [i / 8] = (bytes.at (i / 8) | ((bits [i] ? 1 : 0) << (i % 8)));

    return bytes;
}

void DS_ProtocolBase::updateStatus (int status) {
    m_status = status;
}

void DS_ProtocolBase::updateRobotCode (bool available) {
    m_robotCode = available;
    emit codeChanged (m_robotCode);
}

void DS_ProtocolBase::updateSendDateTime (bool sendDT) {
    m_sendDateTime = sendDT;
}

void DS_ProtocolBase::updateCommunications (DS_CommunicationStatus status) {
    m_communicationStatus = status;
    emit communicationsChanged (m_communicationStatus);
}

void DS_ProtocolBase::updateVoltage (char major, char minor) {
    QString maj = QString::number (major);
    QString min = QString::number (minor);

    maj = maj.replace ("-", "");
    min = min.replace ("-", "");

    if (min.length() == 1)
        min = QString ("0%1").arg (min);

    else if (min.length() > 2)
        min = QString (min.at (0)) + QString (min.at (1));

    emit voltageChanged (QString ("%1.%2").arg (maj, min));
}

void DS_ProtocolBase::pingRobot() {
    m_pingSocket.abort();
    m_pingSocket.connectToHost (robotAddress(), 80, QTcpSocket::ReadOnly);
}

void DS_ProtocolBase::onIpFound (QString address, QString ip) {
    if (address.toLower() == robotAddress().toLower())
        emit robotAddressChanged (ip);

    pingRobot();
}

void DS_ProtocolBase::onStateChanged (QAbstractSocket::SocketState state) {
    if (communicationStatus() == kFailing
            && state == QAbstractSocket::ConnectedState)
        updateCommunications (kPartial);
}
<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2014 Torus Knot Software Ltd

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.
-----------------------------------------------------------------------------
*/

#include "OgreCgPlugin.h"
#include "OgreRoot.h"
#include "OgreHighLevelGpuProgram.h"
#include "OgreHighLevelGpuProgramManager.h"
#include "OgreCgFxScriptLoader.h"
#include "OgreCgProgramFactory.h"
#include "OgreLogManager.h"

namespace Ogre
{
    const String sPluginName = "Cg Program Manager";
    //---------------------------------------------------------------------
    CgPlugin::CgPlugin()
        :mCgProgramFactory(0)
    {

    }
    //---------------------------------------------------------------------
    const String& CgPlugin::getName() const
    {
        return sPluginName;
    }
    //---------------------------------------------------------------------
    void CgPlugin::install()
    {
    }
    //---------------------------------------------------------------------
    void CgPlugin::initialise()
    {
        // Cg is also not supported on OpenGL 3+
        if(Root::getSingletonPtr()->getRenderSystem()->getName().find("OpenGL 3+") != String::npos)
        {
            LogManager::getSingleton().logMessage("Disabling Cg Plugin for GL3+");
            return;
        }

        // Check for gles2 by the glsles factory (this plugin is not supported on embedded systems for now)
        if (HighLevelGpuProgramManager::getSingleton().isLanguageSupported("glsles") == false)

        {
            // Create new factory
            mCgProgramFactory = OGRE_NEW CgProgramFactory();

            // Register
            HighLevelGpuProgramManager::getSingleton().addFactory(mCgProgramFactory);

            OGRE_NEW CgFxScriptLoader();
        }
    }
    //---------------------------------------------------------------------
    void CgPlugin::shutdown()
    {
        // nothing to do
    }
    //---------------------------------------------------------------------
    void CgPlugin::uninstall()
    {
        if (mCgProgramFactory)
        {
            OGRE_DELETE CgFxScriptLoader::getSingletonPtr();

            // Remove from manager safely
            if (HighLevelGpuProgramManager::getSingletonPtr())
                HighLevelGpuProgramManager::getSingleton().removeFactory(mCgProgramFactory);
            OGRE_DELETE mCgProgramFactory;
            mCgProgramFactory = 0;
        }
    }
}
<commit_msg>CgPlugin: allow loading on GL3Plus<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2014 Torus Knot Software Ltd

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.
-----------------------------------------------------------------------------
*/

#include "OgreCgPlugin.h"
#include "OgreRoot.h"
#include "OgreHighLevelGpuProgram.h"
#include "OgreHighLevelGpuProgramManager.h"
#include "OgreCgFxScriptLoader.h"
#include "OgreCgProgramFactory.h"
#include "OgreLogManager.h"

namespace Ogre
{
    const String sPluginName = "Cg Program Manager";
    //---------------------------------------------------------------------
    CgPlugin::CgPlugin()
        :mCgProgramFactory(0)
    {

    }
    //---------------------------------------------------------------------
    const String& CgPlugin::getName() const
    {
        return sPluginName;
    }
    //---------------------------------------------------------------------
    void CgPlugin::install()
    {
    }
    //---------------------------------------------------------------------
    void CgPlugin::initialise()
    {
        // Check for gles2 by the glsles factory (this plugin is not supported on embedded systems for now)
        if (HighLevelGpuProgramManager::getSingleton().isLanguageSupported("glsles") == false)

        {
            // Create new factory
            mCgProgramFactory = OGRE_NEW CgProgramFactory();

            // Register
            HighLevelGpuProgramManager::getSingleton().addFactory(mCgProgramFactory);

            OGRE_NEW CgFxScriptLoader();
        }
    }
    //---------------------------------------------------------------------
    void CgPlugin::shutdown()
    {
        // nothing to do
    }
    //---------------------------------------------------------------------
    void CgPlugin::uninstall()
    {
        if (mCgProgramFactory)
        {
            OGRE_DELETE CgFxScriptLoader::getSingletonPtr();

            // Remove from manager safely
            if (HighLevelGpuProgramManager::getSingletonPtr())
                HighLevelGpuProgramManager::getSingleton().removeFactory(mCgProgramFactory);
            OGRE_DELETE mCgProgramFactory;
            mCgProgramFactory = 0;
        }
    }
}
<|endoftext|>