<commit_before>
#include "GateFinder.h"

GateFinder::GateFinder()
{
}

GateFinder::~GateFinder()
{
}

extern void drawLine(cv::Mat & img, cv::Mat & img2, cv::Vec4f line, int thickness, CvScalar color, bool nightVision = false);

bool GateFinder::Locate(cv::Mat &imgThresholded, cv::Mat &frameHSV, cv::Mat &frameBGR, cv::Point &center, cv::Point2f *bounds, std::vector<cv::Point2i> &notGates) {
	int smallestGateArea = 1;
	double growGateHeight = 1.2;
	center = cv::Point(-1, -1);
	//cv::Mat imgThresholded = HSVRanges[target]; // reference counted, I think
	if (imgThresholded.rows == 0) return false;

	cv::Mat dst(imgThresholded.rows, imgThresholded.cols, CV_8U, cv::Scalar::all(0));

	cv::Scalar color(0, 0, 0);
	cv::Scalar color2(255, 255, 255);

	//biggest area calculation
	std::vector<std::vector<cv::Point>> contours; // Vector for storing contour
	std::vector<cv::Vec4i> hierarchy;

	findContours(imgThresholded, contours, hierarchy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE); // Find the contours in the image
	if (contours.size() == 0){
		return false;
	}

	double largest_area = 0;
	double area = 0;
	size_t sec_largest_contour_index = 0;
	size_t largest_contour_index = 0;

	for (size_t i = 0; i < contours.size(); i++)
	{
		area = cv::contourArea(contours[i], false);
		if (area > largest_area){
			notGates.push_back(getCenterFromContour(contours[i]));
			largest_area = area;
			sec_largest_contour_index = largest_contour_index;
			largest_contour_index = i;  //Store the index of largest contour
		}
	}

	//validate gate area
	if (largest_area < smallestGateArea){
		return false;
	}

	if (contours.size() <= largest_contour_index) {
		assert(false);
	}

	std::vector<cv::Point> merged_contour_points;
	//merge two contours if they are close
	if (contours.size() > sec_largest_contour_index &&
		(cv::norm(getCenterFromContour(contours[largest_contour_index]) -
			getCenterFromContour(contours[sec_largest_contour_index])) < 500))
	{
		for (int i = 0; i < contours[largest_contour_index].size(); i++) {
			merged_contour_points.push_back(contours[largest_contour_index][i]);
		}
		for (int j = 0; j < contours[sec_largest_contour_index].size(); j++) {
			merged_contour_points.push_back(contours[sec_largest_contour_index][j]);
		}

	}
	else {
		merged_contour_points = contours[largest_contour_index];
	}

	if (merged_contour_points.size() > 0) {
		center = getCenterFromContour(merged_contour_points);
		cv::RotatedRect bounding_rect2 = cv::minAreaRect(merged_contour_points);
		bounding_rect2.points(bounds);

		for (int j = 0; j < 4; j++) {
			line(frameBGR, bounds[j], bounds[(j + 1) % 4], color, 1, 8);
		}
	}
	else {
		return false;
	}

	return true;
}

cv::Point2i GateFinder::getCenterFromContour(std::vector<cv::Point> contour) {
	cv::Moments M = cv::moments(contour);
	return cv::Point2i((int)(M.m10 / M.m00), (int)(M.m01 / M.m00));
}
<commit_msg>fixed merge gates<commit_after>
#include "GateFinder.h"

GateFinder::GateFinder()
{
}

GateFinder::~GateFinder()
{
}

extern void drawLine(cv::Mat & img, cv::Mat & img2, cv::Vec4f line, int thickness, CvScalar color, bool nightVision = false);

bool GateFinder::Locate(cv::Mat &imgThresholded, cv::Mat &frameHSV, cv::Mat &frameBGR, cv::Point &center, cv::Point2f *bounds, std::vector<cv::Point2i> &notGates) {
	int smallestGateArea = 1;
	double growGateHeight = 1.2;
	center = cv::Point(-1, -1);
	//cv::Mat imgThresholded = HSVRanges[target]; // reference counted, I think
	if (imgThresholded.rows == 0) return false;

	cv::Mat dst(imgThresholded.rows, imgThresholded.cols, CV_8U, cv::Scalar::all(0));

	cv::Scalar color(0, 0, 0);
	cv::Scalar color2(255, 255, 255);

	//biggest area calculation
	std::vector<std::vector<cv::Point>> contours; // Vector for storing contour
	std::vector<cv::Vec4i> hierarchy;

	findContours(imgThresholded, contours, hierarchy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE); // Find the contours in the image
	if (contours.size() == 0){
		return false;
	}

	for (size_t i = 0; i < contours.size(); i++)
	{
		notGates.push_back(getCenterFromContour(contours[i]));
	}

	std::sort(contours.begin(), contours.end(), [](std::vector<cv::Point> a, std::vector<cv::Point> b)
	{
		return cv::contourArea(a, false) > cv::contourArea(b, false);
	});

	int largestArea = cv::contourArea(contours[0], false);
	//validate gate area
	if (largestArea < smallestGateArea){
		return false;
	}

	std::vector<cv::Point> merged_contour_points;
	//merge two contours if they are close
	if (contours.size() > 1 &&
		(cv::norm(getCenterFromContour(contours[0]) -
			getCenterFromContour(contours[1])) < 500))
	{
		for (int i = 0; i < contours[0].size(); i++) {
			merged_contour_points.push_back(contours[0][i]);
		}
		for (int j = 0; j < contours[1].size(); j++) {
			merged_contour_points.push_back(contours[1][j]);
		}
	}
	else {
		merged_contour_points = contours[0];
	}

	if (merged_contour_points.size() > 0) {
		center = getCenterFromContour(merged_contour_points);
		cv::RotatedRect bounding_rect2 = cv::minAreaRect(merged_contour_points);
		bounding_rect2.points(bounds);

		for (int j = 0; j < 4; j++) {
			line(frameBGR, bounds[j], bounds[(j + 1) % 4], color, 1, 8);
		}
	}
	else {
		return false;
	}

	return true;
}

cv::Point2i GateFinder::getCenterFromContour(std::vector<cv::Point> contour) {
	cv::Moments M = cv::moments(contour);
	return cv::Point2i((int)(M.m10 / M.m00), (int)(M.m01 / M.m00));
}
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef RULE_HPP
#define RULE_HPP
// mapnik
#include <mapnik/line_symbolizer.hpp>
#include <mapnik/line_pattern_symbolizer.hpp>
#include <mapnik/polygon_symbolizer.hpp>
#include <mapnik/polygon_pattern_symbolizer.hpp>
#include <mapnik/point_symbolizer.hpp>
#include <mapnik/raster_symbolizer.hpp>
#include <mapnik/shield_symbolizer.hpp>
#include <mapnik/text_symbolizer.hpp>
#include <mapnik/markers_symbolizer.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/expression_grammar.hpp>

// boost
#include <boost/shared_ptr.hpp>
#include <boost/variant.hpp>
// stl
#include <string>
#include <vector>

namespace mapnik
{
   inline bool operator==(point_symbolizer const& lhs,
                          point_symbolizer const& rhs)
   {
      return (&lhs == &rhs);
   }
   inline bool operator==(line_symbolizer const& lhs,
                          line_symbolizer const& rhs)
   {
      return (&lhs == &rhs);
   }
   inline bool operator==(line_pattern_symbolizer const& lhs,
                          line_pattern_symbolizer const& rhs)
   {
      return (&lhs == &rhs);
   }

   inline bool operator==(polygon_symbolizer const& lhs,
                          polygon_symbolizer const& rhs)
   {
      return (&lhs == &rhs);
   }

   inline bool operator==(polygon_pattern_symbolizer const& lhs,
                          polygon_pattern_symbolizer const& rhs)
   {
      return (&lhs == &rhs);
   }

   inline bool operator==(raster_symbolizer const& lhs,
                          raster_symbolizer const& rhs)
   {
      return (&lhs == &rhs);
   }

   inline bool operator==(text_symbolizer const& lhs,
                          text_symbolizer const& rhs)
   {
      return (&lhs == &rhs);
   }

   inline bool operator==(shield_symbolizer const& lhs,
                          shield_symbolizer const& rhs)
   {
      return (&lhs == &rhs);
   }

   inline bool operator==(building_symbolizer const& lhs,
                          building_symbolizer const& rhs)
   {
      return (&lhs == &rhs);
   }

   inline bool operator==(markers_symbolizer const& lhs,
                          markers_symbolizer const& rhs)
   {
      return (&lhs == &rhs);
   }
   typedef boost::variant<point_symbolizer,
                          line_symbolizer,
                          line_pattern_symbolizer,
                          polygon_symbolizer,
                          polygon_pattern_symbolizer,
                          raster_symbolizer,
                          shield_symbolizer,
                          text_symbolizer,
                          building_symbolizer,
                          markers_symbolizer> symbolizer;

template <typename FeatureT>
class rule
{
public:
    typedef std::vector<symbolizer> symbolizers;
private:

    std::string name_;
    std::string title_;
    std::string abstract_;
    double min_scale_;
    double max_scale_;
    symbolizers syms_;
    expression_ptr filter_;
    bool else_filter_;
public:
    rule()
	: name_(),
	  title_(),
	  abstract_(),
	  min_scale_(0),
	  max_scale_(std::numeric_limits<double>::infinity()),
	  syms_(),
	  filter_(new mapnik::expr_node(true)),
	  else_filter_(false) {}

    rule(const std::string& name,
	 const std::string& title="",
	 double min_scale_denominator=0,
	 double max_scale_denominator=std::numeric_limits<double>::infinity())
	: name_(name),
	  title_(title),
	  min_scale_(min_scale_denominator),
	  max_scale_(max_scale_denominator),
	  syms_(),
	  filter_(new mapnik::expr_node(true)),
	  else_filter_(false) {}

    rule(const rule& rhs)
	: name_(rhs.name_),
	  title_(rhs.title_),
	  abstract_(rhs.abstract_),
	  min_scale_(rhs.min_scale_),
	  max_scale_(rhs.max_scale_),
	  syms_(rhs.syms_),
	  filter_(rhs.filter_),
	  else_filter_(rhs.else_filter_) {}

    rule& operator=(rule const& rhs)
    {
	rule tmp(rhs);
	swap(tmp);
	return *this;
    }
    bool operator==(rule const& other)
    {
	return  (this == &other);
    }

    void set_max_scale(double scale)
    {
	max_scale_=scale;
    }

    double get_max_scale() const
    {
	return max_scale_;
    }

    void set_min_scale(double scale)
    {
	min_scale_=scale;
    }

    double get_min_scale() const
    {
	return min_scale_;
    }

    void set_name(std::string const& name)
    {
	name_=name;
    }

    std::string const& get_name() const
    {
	return name_;
    }

    std::string const& get_title() const
    {
	return  title_;
    }

    void set_title(std::string const& title)
    {
	title_=title;
    }

    void set_abstract(std::string const& abstract)
    {
	abstract_=abstract;
    }

    std::string const& get_abstract() const
    {
	return abstract_;
    }

    void append(const symbolizer& sym)
    {
	syms_.push_back(sym);
    }

    void remove_at(size_t index)
    {
	if (index < syms_.size())
	{
	    syms_.erase(syms_.begin()+index);
	}
    }

    const symbolizers& get_symbolizers() const
    {
	return syms_;
    }

    symbolizers::const_iterator begin() const
    {
	return syms_.begin();
    }

    symbolizers::const_iterator end() const
    {
	return syms_.end();
    }

    symbolizers::iterator begin()
    {
	return syms_.begin();
    }

    symbolizers::iterator end()
    {
	return syms_.end();
    }

    void set_filter(const expression_ptr& filter)
    {
	filter_=filter;
    }

    expression_ptr const& get_filter() const
    {
	return filter_;
    }

    void set_else(bool else_filter)
    {
	else_filter_=else_filter;
    }

    bool has_else_filter() const
    {
	return else_filter_;
    }

    bool active(double scale) const
    {
	return ( scale >= min_scale_ - 1e-6 && scale < max_scale_ + 1e-6);
    }

private:

    void swap(rule& rhs) throw()
    {
	name_=rhs.name_;
	title_=rhs.title_;
	abstract_=rhs.abstract_;
	min_scale_=rhs.min_scale_;
	max_scale_=rhs.max_scale_;
	syms_=rhs.syms_;
	filter_=rhs.filter_;
	else_filter_=rhs.else_filter_;
    }
};

typedef rule<Feature> rule_type;

}

#endif //RULE_HPP
<commit_msg>fix formatting<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef RULE_HPP
#define RULE_HPP
// mapnik
#include <mapnik/line_symbolizer.hpp>
#include <mapnik/line_pattern_symbolizer.hpp>
#include <mapnik/polygon_symbolizer.hpp>
#include <mapnik/polygon_pattern_symbolizer.hpp>
#include <mapnik/point_symbolizer.hpp>
#include <mapnik/raster_symbolizer.hpp>
#include <mapnik/shield_symbolizer.hpp>
#include <mapnik/text_symbolizer.hpp>
#include <mapnik/markers_symbolizer.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/expression_grammar.hpp>

// boost
#include <boost/shared_ptr.hpp>
#include <boost/variant.hpp>
// stl
#include <string>
#include <vector>

namespace mapnik
{
   inline bool operator==(point_symbolizer const& lhs,
                          point_symbolizer const& rhs)
   {
      return (&lhs == &rhs);
   }
   inline bool operator==(line_symbolizer const& lhs,
                          line_symbolizer const& rhs)
   {
      return (&lhs == &rhs);
   }
   inline bool operator==(line_pattern_symbolizer const& lhs,
                          line_pattern_symbolizer const& rhs)
   {
      return (&lhs == &rhs);
   }

   inline bool operator==(polygon_symbolizer const& lhs,
                          polygon_symbolizer const& rhs)
   {
      return (&lhs == &rhs);
   }

   inline bool operator==(polygon_pattern_symbolizer const& lhs,
                          polygon_pattern_symbolizer const& rhs)
   {
      return (&lhs == &rhs);
   }

   inline bool operator==(raster_symbolizer const& lhs,
                          raster_symbolizer const& rhs)
   {
      return (&lhs == &rhs);
   }

   inline bool operator==(text_symbolizer const& lhs,
                          text_symbolizer const& rhs)
   {
      return (&lhs == &rhs);
   }

   inline bool operator==(shield_symbolizer const& lhs,
                          shield_symbolizer const& rhs)
   {
      return (&lhs == &rhs);
   }

   inline bool operator==(building_symbolizer const& lhs,
                          building_symbolizer const& rhs)
   {
      return (&lhs == &rhs);
   }

   inline bool operator==(markers_symbolizer const& lhs,
                          markers_symbolizer const& rhs)
   {
      return (&lhs == &rhs);
   }
   typedef boost::variant<point_symbolizer,
                          line_symbolizer,
                          line_pattern_symbolizer,
                          polygon_symbolizer,
                          polygon_pattern_symbolizer,
                          raster_symbolizer,
                          shield_symbolizer,
                          text_symbolizer,
                          building_symbolizer,
                          markers_symbolizer> symbolizer;

template <typename FeatureT>
class rule
{
public:
    typedef std::vector<symbolizer> symbolizers;
private:

    std::string name_;
    std::string title_;
    std::string abstract_;
    double min_scale_;
    double max_scale_;
    symbolizers syms_;
    expression_ptr filter_;
    bool else_filter_;
public:
    rule()
        : name_(),
          title_(),
          abstract_(),
          min_scale_(0),
          max_scale_(std::numeric_limits<double>::infinity()),
          syms_(),
          filter_(new mapnik::expr_node(true)),
          else_filter_(false) {}

    rule(const std::string& name,
         const std::string& title="",
         double min_scale_denominator=0,
         double max_scale_denominator=std::numeric_limits<double>::infinity())
        : name_(name),
          title_(title),
          min_scale_(min_scale_denominator),
          max_scale_(max_scale_denominator),
          syms_(),
          filter_(new mapnik::expr_node(true)),
          else_filter_(false) {}

    rule(const rule& rhs)
        : name_(rhs.name_),
          title_(rhs.title_),
          abstract_(rhs.abstract_),
          min_scale_(rhs.min_scale_),
          max_scale_(rhs.max_scale_),
          syms_(rhs.syms_),
          filter_(rhs.filter_),
          else_filter_(rhs.else_filter_) {}

    rule& operator=(rule const& rhs)
    {
        rule tmp(rhs);
        swap(tmp);
        return *this;
    }
    bool operator==(rule const& other)
    {
        return  (this == &other);
    }

    void set_max_scale(double scale)
    {
        max_scale_=scale;
    }

    double get_max_scale() const
    {
        return max_scale_;
    }

    void set_min_scale(double scale)
    {
        min_scale_=scale;
    }

    double get_min_scale() const
    {
        return min_scale_;
    }

    void set_name(std::string const& name)
    {
        name_=name;
    }

    std::string const& get_name() const
    {
        return name_;
    }

    std::string const& get_title() const
    {
        return  title_;
    }

    void set_title(std::string const& title)
    {
        title_=title;
    }

    void set_abstract(std::string const& abstract)
    {
        abstract_=abstract;
    }

    std::string const& get_abstract() const
    {
        return abstract_;
    }

    void append(const symbolizer& sym)
    {
        syms_.push_back(sym);
    }

    void remove_at(size_t index)
    {
        if (index < syms_.size())
        {
            syms_.erase(syms_.begin()+index);
        }
    }

    const symbolizers& get_symbolizers() const
    {
        return syms_;
    }

    symbolizers::const_iterator begin() const
    {
        return syms_.begin();
    }

    symbolizers::const_iterator end() const
    {
        return syms_.end();
    }

    symbolizers::iterator begin()
    {
        return syms_.begin();
    }

    symbolizers::iterator end()
    {
        return syms_.end();
    }

    void set_filter(const expression_ptr& filter)
    {
        filter_=filter;
    }

    expression_ptr const& get_filter() const
    {
        return filter_;
    }

    void set_else(bool else_filter)
    {
        else_filter_=else_filter;
    }

    bool has_else_filter() const
    {
        return else_filter_;
    }

    bool active(double scale) const
    {
        return ( scale >= min_scale_ - 1e-6 && scale < max_scale_ + 1e-6);
    }

private:

    void swap(rule& rhs) throw()
    {
        name_=rhs.name_;
        title_=rhs.title_;
        abstract_=rhs.abstract_;
        min_scale_=rhs.min_scale_;
        max_scale_=rhs.max_scale_;
        syms_=rhs.syms_;
        filter_=rhs.filter_;
        else_filter_=rhs.else_filter_;
    }
};

typedef rule<Feature> rule_type;

}

#endif //RULE_HPP
<|endoftext|>


<commit_before>#ifndef SIGMA_WORLD_HPP
#define SIGMA_WORLD_HPP

#include <sigma/entity.hpp>
#include <sigma/util/variadic.hpp>

#include <array>
#include <bitset>
#include <cassert>
#include <vector>

namespace sigma {
template <class... Components>
struct component_set {
    using component_mask_type = std::bitset<sizeof...(Components)>;

    template <class Component>
    static size_t index_of()
    {
        return index<Component, Components...>::value;
    }

    template <class... SubComponents>
    static component_mask_type mask_for()
    {
        component_mask_type m;
        auto l = { m |= (1 << index_of<SubComponents>())... };
        (void)l;
        return m;
    }
};

struct component_storage {
    std::vector<char*> chunks;
    size_t count_per_chunk = 256;

    ~component_storage()
    {
        for (char* chunk : chunks) {
            if (chunk)
                delete[] chunk;
        }
    }

    template <class T>
    T* get(size_t index)
    {
        auto chunk_index = index / count_per_chunk;
        auto chunk_offset = index % count_per_chunk;

        assert(chunk_index < chunks.size());

        return ((T*)chunks[chunk_index]) + chunk_offset;
    }

    template <class T, class... Arguments>
    T* add(size_t index, Arguments&&... args)
    {
        auto chunk_index = index / count_per_chunk;
        if (chunk_index >= chunks.size())
            create_chunk<T>(chunk_index);

        return new (get<T>(index)) T{ std::forward<Arguments>(args)... };
    }

    template <class T>
    void remove(size_t index)
    {
        // TODO free chunk when last component is removed from it.
        get<T>(index)->~T();
    }

    template <class T>
    void create_chunk(size_t index)
    {
        if (index >= chunks.size())
            chunks.resize(index + 1, nullptr);

        if (chunks[index] == nullptr)
            chunks[index] = new char[sizeof(T) * count_per_chunk];
    }
};

template <class... Components>
struct world {
    using component_set_type = component_set<Components...>;
    using component_mask_type = typename component_set<Components...>::component_mask_type;

    world() = default;
    world(world<Components...>&&) = default;
    world<Components...>& operator=(world<Components...>&&) = default;

    entity create()
    {
        if (free_entities.empty()) {
            entity e{ std::uint32_t(entities.size()), 0 };
            entities.push_back(e);
            entity_masks.push_back(0);
            return e;
        } else {
            auto index = free_entities.back();
            free_entities.pop_back();
            entities[index].index = index;
            entities[index].version++;
            entity_masks[index] = 0;
            return entities[index];
        }
    }

    ~world()
    {
        for (auto e : entities) {
            if (is_alive(e))
                remove_components(e);
        }
    }

    bool is_alive(entity e) const
    {
        if (!e.is_valid() || e.index >= entities.size())
            return false;
        return entities[e.index] == e;
    }

    template <class Component, class... Arguments>
    Component* add(entity e, Arguments&&... args)
    {
        assert(is_alive(e));
        assert(!has<Component>(e));

        entity_masks[e.index] |= component_mask_type(1 << component_set_type::template index_of<Component>());

        component_storage& data = component_data[component_set_type::template index_of<Component>()];
        return data.template add<Component>(e.index, std::forward<Arguments>(args)...);
    }

    template <class Component>
    bool has(entity e)
    {
        if (!is_alive(e))
            return false;
        auto comp_mask = component_set_type::template mask_for<Component>();
        return (entity_masks[e.index] & comp_mask) == comp_mask;
    }

    template <class Component>
    Component* get(entity e)
    {
        assert(is_alive(e));
        assert(has<Component>(e));
        component_storage& data = component_data[component_set_type::template index_of<Component>()];
        return data.template get<Component>(e.index);
    }

    template <class Component>
    void remove(entity e)
    {
        assert(is_alive(e));
        if (has<Component>(e)) {
            entity_masks[e.index] &= ~component_mask_type(1 << component_set_type::template index_of<Component>());
            component_storage& data = component_data[component_set_type::template index_of<Component>()];
            data.template remove<Component>(e.index);
        }
    }

    void remove_components(entity e)
    {
        using expand_type = int[];
        expand_type{ (world::template remove<Components>(e), 0)... };
    }

    void destroy(entity e)
    {
        if (!is_alive(e) || e.index >= entities.size())
            return;
        remove_components(e);
        free_entities.push_back(entities[e.index].index);
        entities[e.index].index = std::uint32_t(-1);
    }

    template <class... SubComponents, class F>
    void for_each(F f)
    {
        // TODO this still loops over entities that are dead.
        auto mask = component_set_type::template mask_for<SubComponents...>();
        auto count = entities.size();
        for (std::size_t i = 0; i < count; ++i) {
            auto e = entities[i];
            if (is_alive(e) && (entity_masks[e.index] & mask) == mask)
                f(e, *(SubComponents*)(component_data[component_set_type::template index_of<SubComponents>()].template get<SubComponents>(e.index))...);
        }
    }

private:
    world(const world<Components...>&) = delete;
    world<Components...>& operator=(const world<Components...>&) = delete;

    std::vector<entity> entities;
    std::vector<std::uint32_t> free_entities;
    std::vector<component_mask_type> entity_masks;
    std::array<component_storage, sizeof...(Components)> component_data;
};
}

#endif // SIGMA_WORLD_HPP
<commit_msg>Refactored component storage into component sets.<commit_after>#ifndef SIGMA_WORLD_HPP
#define SIGMA_WORLD_HPP

#include <sigma/entity.hpp>
#include <sigma/util/variadic.hpp>

#include <array>
#include <bitset>
#include <cassert>
#include <vector>

namespace sigma {
struct component_storage {
    std::vector<char*> chunks;
    size_t count_per_chunk = 256;

    ~component_storage()
    {
        for (char* chunk : chunks) {
            if (chunk)
                delete[] chunk;
        }
    }

    template <class T>
    T* get(size_t index)
    {
        auto chunk_index = index / count_per_chunk;
        auto chunk_offset = index % count_per_chunk;

        assert(chunk_index < chunks.size());

        return ((T*)chunks[chunk_index]) + chunk_offset;
    }

    template <class T, class... Arguments>
    T* add(size_t index, Arguments&&... args)
    {
        auto chunk_index = index / count_per_chunk;
        if (chunk_index >= chunks.size())
            create_chunk<T>(chunk_index);

        return new (get<T>(index)) T{ std::forward<Arguments>(args)... };
    }

    template <class T>
    void remove(size_t index)
    {
        // TODO free chunk when last component is removed from it.
        get<T>(index)->~T();
    }

    template <class T>
    void create_chunk(size_t index)
    {
        if (index >= chunks.size())
            chunks.resize(index + 1, nullptr);

        if (chunks[index] == nullptr)
            chunks[index] = new char[sizeof(T) * count_per_chunk];
    }
};

template <class... Components>
struct component_set {
    using component_mask_type = std::bitset<sizeof...(Components)>;

    template <class Component>
    static size_t index_of()
    {
        return index<Component, Components...>::value;
    }

    template <class... SubComponents>
    static component_mask_type mask_for()
    {
        component_mask_type m;
        auto l = { m |= (1 << index_of<SubComponents>())... };
        (void)l;
        return m;
    }

    template <class Component, class... Arguments>
    Component* add(entity e, Arguments&&... args)
    {
        if (e.index >= entity_masks.size())
            entity_masks.resize(e.index + 1);

        entity_masks[e.index] |= component_mask_type(1 << index_of<Component>());

        component_storage& data = component_data[index_of<Component>()];
        return data.template add<Component>(e.index, std::forward<Arguments>(args)...);
    }

    template <class Component>
    bool has(entity e) const
    {
        auto comp_mask = mask_for<Component>();
        return e.index < entity_masks.size() && ((entity_masks[e.index] & comp_mask) == comp_mask);
    }

    template <class... SubComponents>
    void update_mask(entity e, std::bitset<sizeof...(SubComponents)>& mask) const
    {
        if (e.index < entity_masks.size()) {
            auto l = { (mask[component_set<SubComponents...>::template index_of<SubComponents>()] = entity_masks[e.index][index_of<SubComponents>()])... };
            (void)l;
        }
    }

    template <class Component>
    Component* get(entity e)
    {
        assert(e.index < entity_masks.size());
        assert(has<Component>(e));

        component_storage& data = component_data[index_of<Component>()];
        return data.template get<Component>(e.index);
    }

    template <class Component>
    void remove(entity e)
    {
        if (has<Component>(e)) {
            entity_masks[e.index] &= ~component_mask_type(1 << index_of<Component>());
            component_storage& data = component_data[index_of<Component>()];
            data.template remove<Component>(e.index);
        }
    }

    void remove_components(entity e)
    {
        using expand_type = int[];
        expand_type{ (remove<Components>(e), 0)... };
    }

    std::vector<component_mask_type> entity_masks;
    std::array<component_storage, sizeof...(Components)> component_data;
};

template <class... Components>
struct world : public component_set<Components...> {

    world() = default;
    world(world<Components...>&&) = default;
    world<Components...>& operator=(world<Components...>&&) = default;

    entity create()
    {
        if (free_entities.empty()) {
            entity e{ std::uint32_t(entities.size()), 0 };
            entities.push_back(e);
            return e;
        } else {
            auto index = free_entities.back();
            free_entities.pop_back();
            entities[index].index = index;
            entities[index].version++;
            return entities[index];
        }
    }

    ~world()
    {
        for (auto e : entities) {
            if (is_alive(e))
                remove_components(e);
        }
    }

    bool is_alive(entity e) const
    {
        if (!e.is_valid() || e.index >= entities.size())
            return false;
        return entities[e.index] == e;
    }

    template <class Component, class... Arguments>
    Component* add(entity e, Arguments&&... args)
    {
        assert(is_alive(e));
        assert(!has<Component>(e));

        return component_set<Components...>::template add<Component>(e, std::forward<Arguments>(args)...);
    }

    template <class Component>
    bool has(entity e)
    {
        if (!is_alive(e))
            return false;
        return component_set<Components...>::template has<Component>(e);
    }

    template <class Component>
    Component* get(entity e)
    {
        assert(is_alive(e));
        assert(has<Component>(e));
        return component_set<Components...>::template get<Component>(e);
    }

    template <class Component>
    void remove(entity e)
    {
        assert(is_alive(e));
        if (has<Component>(e)) {
            component_set<Components...>::template remove<Component>(e);
        }
    }

    void remove_components(entity e)
    {
        component_set<Components...>::remove_components(e);
    }

    void destroy(entity e)
    {
        if (!is_alive(e) || e.index >= entities.size())
            return;
        remove_components(e);
        free_entities.push_back(entities[e.index].index);
        entities[e.index].index = std::uint32_t(-1);
    }

    template <class... SubComponents>
    bool has_all(entity e) const
    {
        std::bitset<sizeof...(SubComponents)> mask;
        component_set<Components...>::template update_mask<SubComponents...>(e, mask);
        return mask.all();
    }

    template <class... SubComponents, class F>
    void for_each(F f)
    {
        // TODO this still loops over entities that are dead.
        auto count = entities.size();
        for (std::size_t i = 0; i < count; ++i) {
            auto e = entities[i];
            if (is_alive(e) && has_all<SubComponents...>(e))
                f(e, *get<SubComponents>(e)...);
        }
    }

private:
    world(const world<Components...>&) = delete;
    world<Components...>& operator=(const world<Components...>&) = delete;

    std::vector<entity> entities;
    std::vector<std::uint32_t> free_entities;
};
}

#endif // SIGMA_WORLD_HPP
<|endoftext|>


<commit_before>#ifndef SIMPLE_XDMF_HPP_INCLUDED
#define SIMPLE_XDMF_HPP_INCLUDED

#include <array>
#include <string>
#include <fstream>

class SimpleXdmf {
    private:
        const std::string header = R"(
<?xml version="1.0" ?>
<!DOCTYPE Xdmf SYSTEM "Xdmf.dtd" []>
)";
        std::string content;
        std::string version;
        std::string newLine;
        std::string indent;

        unsigned int currentIndentation = 0;
        bool endEdit = false;

        void addIndent() {
            ++currentIndentation;
        }

        void backIndent() {
            if (currentIndentation > 0) --currentIndentation;
        }

        void insertIndent() {
            for(unsigned int i = 0; i < currentIndentation; ++i) {
                content += indent;
            }
        }

        void beginElement() {
            addIndent();
            insertIndent();
        }

        void endElement() {
            backIndent();
        }

        // for checking valid types
        static constexpr int dataItemTypeLength = 6;
        static constexpr int gridTypeLength = 4;
        static constexpr int topologyTypeLength = 6;
        static constexpr int geometryTypeLength = 6;
        static constexpr int attributeTypeLength = 5;
        static constexpr int attributeCenterLength = 5;
        static constexpr int setTypeLength = 4;
        static constexpr int timeTypeLength = 4;
        static constexpr int formatTypeLength = 3;
        static constexpr int numberTypeLength = 5;
        static constexpr int precisionTypeLength = 4;

        std::array<std::string, dataItemTypeLength> DataItemType {"Uniform", "Collection", "Tree", "HyperSlab", "Coordinates", "Function"};
        std::array<std::string, gridTypeLength> GridType {"Uniform", "Collection", "Tree", "Subset"};
        std::array<std::string, topologyTypeLength> TopologyType {"2DSMesh", "2DRectMesh", "2DCoRectMesh", "3DSMesh", "3DRectMesh", "3DCoRectMesh"};
        std::array<std::string, geometryTypeLength> GeometryType {"XYZ", "XY", "X_Y_Z", "VXVYVZ", "ORIGIN_DXDYDZ", "ORIGIN_DXDY"};
        std::array<std::string, attributeTypeLength> AttributeType {"Scalar", "Vector", "Tensor", "Tensor6", "Matrix"};
        std::array<std::string, attributeCenterLength> AttributeCenter {"Node", "Edge", "Face", "Cell", "Grid"};
        std::array<std::string, setTypeLength> SetType {"Node", "Edge", "Face", "Cell"};
        std::array<std::string, timeTypeLength> TimeType {"Single", "HyperSlab", "List", "Range"};
        std::array<std::string, formatTypeLength> FormatType {"XML", "HDF", "Binary"};
        std::array<std::string, numberTypeLength> NumberType {"Float", "Int", "UInt", "Char", "UChar"};
        std::array<std::string, precisionTypeLength> PrecisionType {"1", "2", "4", "8"};

        template<int N>
        bool checkIsValidType(const std::array<std::string, N>& valid_types, const std::string& specified_type) {
            bool is_valid = false;

            for(const auto& t : valid_types) {
                if (t == specified_type) {
                    is_valid = true;
                }
            }

            return is_valid;
        }

    public:
        SimpleXdmf(const std::string& _version = "3.0") {
            version = _version;
            setNewLineCode();
            setIndent();
            beginXdmf();
        }

        void setIndent(const int size = 4) {
            if (size == 0) {
                indent = '\t';
                return;
            }

            for (int i = 0; i < size; ++i) {
                indent += ' ';
            }
        }

        void setNewLineCode() {
            const char CR = '\r';
            const char LF = '\n';
            const char* CRLF = "\r\n";

            newLine = LF;
        }

        void generate(const std::string file_name) {
            if(!endEdit) endXdmf();

            std::ofstream ofs(file_name, std::ios::out);
            ofs << content << std::endl;
        }

        void beginXdmf() {
            endEdit = false;
            content = header + "<Xdmf Version=\"" + version + "\">" + newLine;
        }

        void endXdmf() {
            content += "</Xdmf>";
            endEdit = true;
        }

        void beginDomain() {
            beginElement();
            content += "<Domain>" + newLine;
        };

        void endDomain() {
            insertIndent();
            content += "</Domain>" + newLine;
            endElement();
        };

        void beginGrid(const std::string& type = "Uniform") {
            beginElement();

            if (checkIsValidType<gridTypeLength>(GridType, type)) {
                content += "<Grid GridType=\"" + type + "\">" + newLine;
            } else {
                std::string error_message = "Invalid Grid type = " + type + " is passed to beginGrid().";
                throw std::invalid_argument(error_message);
            }
        }

        void endGrid() {
            insertIndent();
            content += "</Grid>" + newLine;
            endElement();
        }

        void beginTopology(const std::string& type = "2DCoRectMesh") {
            beginElement();

            if (checkIsValidType<topologyTypeLength>(TopologyType, type)) {
                content += "<Topology TopologyType=\"" + type + "\">" + newLine;
            } else {
                std::string error_message = "Invalid Topology type = " + type + " is passed to beginTopology().";
                throw std::invalid_argument(error_message);
            }
        }

        void endTopology() {
            insertIndent();
            content += "</Topology>" + newLine;
            endElement();
        }

        void beginGeometory(const std::string& type = "XYZ"){
            beginElement();

            if (checkIsValidType<geometryTypeLength>(GeometryType, type)) {
                content += "<Geometry GeometryType=\"" + type + "\">" + newLine;
            } else {
                std::string error_message = "Invalid Geometry type = " + type + " is passed to beginGeometry().";
                throw std::invalid_argument(error_message);
            }
        }

        void endGeometory(){
            insertIndent();
            content += "</Geometry>" + newLine;
            endElement();
        }

        void beginDataItem(const std::string& type = "Uniform") {
            beginElement();

            if (checkIsValidType<dataItemTypeLength>(DataItemType, type)) {
                content += "<DataItem ItemType=\"" + type + "\">" + newLine;
            } else {
                std::string error_message = "Invalid DataItem type = " + type + " is passed to beginDataItem().";
                throw std::invalid_argument(error_message);
            }
        }

        void endDataItem() {
            insertIndent();
            content += "</DataItem>" + newLine;
            endElement();
        }
};

#endif<commit_msg>Changed tag insert method to buffer based.<commit_after>#ifndef SIMPLE_XDMF_HPP_INCLUDED
#define SIMPLE_XDMF_HPP_INCLUDED

#include <array>
#include <string>
#include <fstream>

class SimpleXdmf {
    private:
        const std::string header = R"(
<?xml version="1.0" ?>
<!DOCTYPE Xdmf SYSTEM "Xdmf.dtd" []>
)";
        std::string content;
        std::string buffer;
        std::string version;
        std::string newLine;
        std::string indent;

        unsigned int currentIndentation = 0;
        bool endEdit = false;

        void addIndent() {
            ++currentIndentation;
        }

        void backIndent() {
            if (currentIndentation > 0) --currentIndentation;
        }

        void insertIndent() {
            for(unsigned int i = 0; i < currentIndentation; ++i) {
                buffer += indent;
            }
        }

        void beginElement(const std::string& tag) {
            if (buffer != "") {
                commitBuffer();
            }
            addIndent();
            insertIndent();
            buffer += "<" + tag;
        }

        void endElement(const std::string& tag) {
            if (buffer != "") {
                commitBuffer();
            }
            insertIndent();
            buffer += "</" + tag;
            commitBuffer();
            backIndent();
        }

        void commitBuffer() {
            content += buffer + ">" + newLine;
            buffer.clear();
        }

        // for checking valid types
        static constexpr int dataItemTypeLength = 6;
        static constexpr int gridTypeLength = 4;
        static constexpr int topologyTypeLength = 6;
        static constexpr int geometryTypeLength = 6;
        static constexpr int attributeTypeLength = 5;
        static constexpr int attributeCenterLength = 5;
        static constexpr int setTypeLength = 4;
        static constexpr int timeTypeLength = 4;
        static constexpr int formatTypeLength = 3;
        static constexpr int numberTypeLength = 5;
        static constexpr int precisionTypeLength = 4;

        std::array<std::string, dataItemTypeLength> DataItemType {"Uniform", "Collection", "Tree", "HyperSlab", "Coordinates", "Function"};
        std::array<std::string, gridTypeLength> GridType {"Uniform", "Collection", "Tree", "Subset"};
        std::array<std::string, topologyTypeLength> TopologyType {"2DSMesh", "2DRectMesh", "2DCoRectMesh", "3DSMesh", "3DRectMesh", "3DCoRectMesh"};
        std::array<std::string, geometryTypeLength> GeometryType {"XYZ", "XY", "X_Y_Z", "VXVYVZ", "ORIGIN_DXDYDZ", "ORIGIN_DXDY"};
        std::array<std::string, attributeTypeLength> AttributeType {"Scalar", "Vector", "Tensor", "Tensor6", "Matrix"};
        std::array<std::string, attributeCenterLength> AttributeCenter {"Node", "Edge", "Face", "Cell", "Grid"};
        std::array<std::string, setTypeLength> SetType {"Node", "Edge", "Face", "Cell"};
        std::array<std::string, timeTypeLength> TimeType {"Single", "HyperSlab", "List", "Range"};
        std::array<std::string, formatTypeLength> FormatType {"XML", "HDF", "Binary"};
        std::array<std::string, numberTypeLength> NumberType {"Float", "Int", "UInt", "Char", "UChar"};
        std::array<std::string, precisionTypeLength> PrecisionType {"1", "2", "4", "8"};

        template<int N>
        bool checkIsValidType(const std::array<std::string, N>& valid_types, const std::string& specified_type) {
            bool is_valid = false;

            for(const auto& t : valid_types) {
                if (t == specified_type) {
                    is_valid = true;
                }
            }

            return is_valid;
        }

        // Adding Valid Attributes
        void addType(const std::string& prefix, const std::string& type) {
            buffer += " " + prefix + "Type=\"" + type + "\"";
        }

        std::string addFormat() {
            return "Format=\"XML\"";
        }

        std::string addDimensions() {
            return "Dimensions=\"1 1 2\"";
        }

    public:
        SimpleXdmf(const std::string& _version = "3.0") {
            version = _version;
            setNewLineCode();
            setIndent();
            beginXdmf();
        }

        void setIndent(const int size = 4) {
            if (size == 0) {
                indent = '\t';
                return;
            }

            for (int i = 0; i < size; ++i) {
                indent += ' ';
            }
        }

        void setNewLineCode() {
            const char CR = '\r';
            const char LF = '\n';
            const char* CRLF = "\r\n";

            newLine = LF;
        }

        void generate(const std::string file_name) {
            if(!endEdit) endXdmf();

            std::ofstream ofs(file_name, std::ios::out);
            ofs << content << std::endl;
        }

        void beginXdmf() {
            endEdit = false;
            content = header + "<Xdmf Version=\"" + version + "\">" + newLine;
        }

        void endXdmf() {
            content += "</Xdmf>";
            endEdit = true;
        }

        void beginDomain() {
            beginElement("Domain");
        };

        void endDomain() {
            endElement("Domain");
        };

        void beginGrid(const std::string& type = "Uniform") {
            beginElement("Grid");

            if (checkIsValidType<gridTypeLength>(GridType, type)) {
                addType("Grid", type);
            } else {
                std::string error_message = "Invalid Grid type = " + type + " is passed to beginGrid().";
                throw std::invalid_argument(error_message);
            }
        }

        void endGrid() {
            endElement("Grid");
        }

        void beginTopology(const std::string& type = "2DCoRectMesh") {
            beginElement("Topology");

            if (checkIsValidType<topologyTypeLength>(TopologyType, type)) {
                addType("Topology", type);
            } else {
                std::string error_message = "Invalid Topology type = " + type + " is passed to beginTopology().";
                throw std::invalid_argument(error_message);
            }
        }

        void endTopology() {
            endElement("Topology");
        }

        void beginGeometory(const std::string& type = "XYZ"){
            beginElement("Geometry");

            if (checkIsValidType<geometryTypeLength>(GeometryType, type)) {
                addType("Geometry", type);
            } else {
                std::string error_message = "Invalid Geometry type = " + type + " is passed to beginGeometry().";
                throw std::invalid_argument(error_message);
            }
        }

        void endGeometory(){
            endElement("Geomerry");
        }

        void beginDataItem(const std::string& type = "Uniform") {
            beginElement("DataItem");

            if (checkIsValidType<dataItemTypeLength>(DataItemType, type)) {
                addType("DataItem", type);
            } else {
                std::string error_message = "Invalid DataItem type = " + type + " is passed to beginDataItem().";
                throw std::invalid_argument(error_message);
            }
        }

        void endDataItem() {
            endElement("DataItem");
        }
};

#endif<|endoftext|>


<commit_before>#include <iostream>
#include "UnitTest++.h"

#include "wrm_van_genuchten.hh"
#include "wrm_implicit_permafrost_model.hh"
#include "pc_ice_water.hh"
#include "math.h"

TEST(implicitPermafrost) {
  using namespace Amanzi::Flow::FlowRelations;

  double m = 0.8;
  double alpha = 1.5e-4;
  double sr = 0.;
  double p_atm = 101325.;

  Teuchos::ParameterList plist;
  plist.set("van Genuchten m", m);
  plist.set("van Genuchten alpha", alpha);
  plist.set("van Genuchten residual saturation", sr);
  plist.set("van Genuchten smoothing interval width", 0.0);
  Teuchos::RCP<WRMVanGenuchten> wrm = Teuchos::rcp(new WRMVanGenuchten(plist));

  Teuchos::ParameterList plist3;
  PCIceWater pcice(plist3);
  double rho = 1000.;

  Teuchos::ParameterList plist2;
  WRMImplicitPermafrostModel p1(plist2, wrm);

  double sats[3];
  double sats2[3];
  double sats3[3];

  // unsaturated, above freezing
  // -- value
  double pc_ice = pcice.CapillaryPressure(275., rho);
  double pc_liq = p_atm - 100000.;
  p1.saturations(pc_liq, pc_ice, sats);
  CHECK_CLOSE(sats[1], wrm->saturation(pc_liq), 1.e-8);

  // -- derivatives

  // -- derivatives
  double eps = 1.e-3;
  p1.saturations(pc_liq+eps, pc_ice, sats2);
  p1.saturations(pc_liq-eps, pc_ice, sats3);
  sats2[0] = (sats2[0] - sats3[0])/(2*eps);
  sats2[1] = (sats2[1] - sats3[1])/(2*eps);
  sats2[2] = (sats2[2] - sats3[2])/(2*eps);
  p1.dsaturations_dpc_liq(pc_liq, pc_ice, sats);
  CHECK_CLOSE(sats[0], sats2[0], std::abs(sats[0])/1.e3);
  CHECK_CLOSE(sats[1], sats2[1], std::abs(sats[1])/1.e3);
  CHECK_CLOSE(sats[2], sats2[2], std::abs(sats[2])/1.e3);

  // saturated, above freezing
  // -- value
  pc_liq = -1000.;
  p1.saturations(pc_liq, pc_ice, sats);
  CHECK_CLOSE(sats[1], wrm->saturation(pc_liq), 1.e-8);

  // -- derivatives
  p1.saturations(pc_liq+eps, pc_ice, sats2);
  p1.saturations(pc_liq-eps, pc_ice, sats3);
  sats2[0] = (sats2[0] - sats3[0])/(2*eps);
  sats2[1] = (sats2[1] - sats3[1])/(2*eps);
  sats2[2] = (sats2[2] - sats3[2])/(2*eps);
  p1.dsaturations_dpc_liq(pc_liq, pc_ice, sats);
  CHECK_CLOSE(sats[0], sats2[0], std::abs(sats[0])/1.e3);
  CHECK_CLOSE(sats[1], sats2[1], std::abs(sats[1])/1.e3);
  CHECK_CLOSE(sats[2], sats2[2], std::abs(sats[2])/1.e3);

  // saturated, below freezing
  // -- value
  pc_ice = pcice.CapillaryPressure(273.1, rho);
  pc_liq = p_atm - 100000.;
  p1.saturations(pc_liq, pc_ice, sats);
  CHECK_CLOSE(sats[0], 1.5017949979397578e-09, 1.e-12);
  CHECK_CLOSE(sats[1], 6.0533870998262555e-06, 1.e-12);
  CHECK_CLOSE(sats[2], 0.9999939451111052, 1.e-8);

  // -- derivatives
  p1.saturations(pc_liq+eps, pc_ice, sats2);
  p1.saturations(pc_liq-eps, pc_ice, sats3);
  sats2[0] = (sats2[0] - sats3[0])/(2*eps);
  sats2[1] = (sats2[1] - sats3[1])/(2*eps);
  sats2[2] = (sats2[2] - sats3[2])/(2*eps);
  p1.dsaturations_dpc_liq(pc_liq, pc_ice, sats);
  CHECK_CLOSE(sats[0], sats2[0], std::abs(sats[0])/1.e3 + 1.e-10);
  CHECK_CLOSE(sats[1], sats2[1], std::abs(sats[1])/1.e3 + 1.e-10);
  CHECK_CLOSE(sats[2], sats2[2], std::abs(sats[2])/1.e3 + 1.e-10);

  p1.saturations(pc_liq, pc_ice+eps, sats2);
  p1.saturations(pc_liq, pc_ice-eps, sats3);
  sats2[0] = (sats2[0] - sats3[0])/(2.*eps);
  sats2[1] = (sats2[1] - sats3[1])/(2.*eps);
  sats2[2] = (sats2[2] - sats3[2])/(2.*eps);
  p1.dsaturations_dpc_ice(pc_liq, pc_ice, sats);
  CHECK_CLOSE(sats[0], sats2[0], std::abs(sats[0])/1.e3 + 1.e-10);
  CHECK_CLOSE(sats[1], sats2[1], std::abs(sats[1])/1.e3 + 1.e-10);
  CHECK_CLOSE(sats[2], sats2[2], std::abs(sats[2])/1.e3 + 1.e-10);

  // unsaturated, below freezing
  // -- value
  pc_liq = p_atm - (-200000);
  p1.saturations(pc_liq, pc_ice, sats);
  CHECK_CLOSE(sats[0], 0.9999974629297762, 1.e-8);
  CHECK_CLOSE(sats[1], 2.3960358028349194e-07, 1.e-12);
  CHECK_CLOSE(sats[2], 2.2974666434445524e-06, 1.e-10);

  // -- derivatives
  p1.saturations(pc_liq+eps, pc_ice, sats2);
  p1.saturations(pc_liq-eps, pc_ice, sats3);
  sats2[0] = (sats2[0] - sats3[0])/(2*eps);
  sats2[1] = (sats2[1] - sats3[1])/(2*eps);
  sats2[2] = (sats2[2] - sats3[2])/(2*eps);
  p1.dsaturations_dpc_liq(pc_liq, pc_ice, sats);
  CHECK_CLOSE(sats[0], sats2[0], std::abs(sats[0])/1.e3);
  CHECK_CLOSE(sats[1], sats2[1], std::abs(sats[1])/1.e3);
  CHECK_CLOSE(sats[2], sats2[2], std::abs(sats[2])/1.e3);

  p1.saturations(pc_liq, pc_ice+eps, sats2);
  p1.saturations(pc_liq, pc_ice-eps, sats3);
  sats2[0] = (sats2[0] - sats3[0])/(2*eps);
  sats2[1] = (sats2[1] - sats3[1])/(2*eps);
  sats2[2] = (sats2[2] - sats3[2])/(2*eps);
  p1.dsaturations_dpc_ice(pc_liq, pc_ice, sats);
  CHECK_CLOSE(sats[0], sats2[0], std::abs(sats[0])/1.e3);
  CHECK_CLOSE(sats[1], sats2[1], std::abs(sats[1])/1.e3);
  CHECK_CLOSE(sats[2], sats2[2], std::abs(sats[2])/1.e3);

}
<commit_msg>tweak to test tolerances for WRM permafrost models<commit_after>#include <iostream>
#include "UnitTest++.h"

#include "wrm_van_genuchten.hh"
#include "wrm_implicit_permafrost_model.hh"
#include "pc_ice_water.hh"
#include "math.h"

TEST(implicitPermafrost) {
  using namespace Amanzi::Flow::FlowRelations;

  double m = 0.8;
  double alpha = 1.5e-4;
  double sr = 0.;
  double p_atm = 101325.;

  Teuchos::ParameterList plist;
  plist.set("van Genuchten m", m);
  plist.set("van Genuchten alpha", alpha);
  plist.set("van Genuchten residual saturation", sr);
  plist.set("van Genuchten smoothing interval width", 0.0);
  Teuchos::RCP<WRMVanGenuchten> wrm = Teuchos::rcp(new WRMVanGenuchten(plist));

  Teuchos::ParameterList plist3;
  PCIceWater pcice(plist3);
  double rho = 1000.;

  Teuchos::ParameterList plist2;
  WRMImplicitPermafrostModel p1(plist2, wrm);

  double sats[3];
  double sats2[3];
  double sats3[3];

  // unsaturated, above freezing
  // -- value
  double pc_ice = pcice.CapillaryPressure(275., rho);
  double pc_liq = p_atm - 100000.;
  p1.saturations(pc_liq, pc_ice, sats);
  CHECK_CLOSE(sats[1], wrm->saturation(pc_liq), 1.e-8);

  // -- derivatives

  // -- derivatives
  double eps = 1.e-3;
  p1.saturations(pc_liq+eps, pc_ice, sats2);
  p1.saturations(pc_liq-eps, pc_ice, sats3);
  sats2[0] = (sats2[0] - sats3[0])/(2*eps);
  sats2[1] = (sats2[1] - sats3[1])/(2*eps);
  sats2[2] = (sats2[2] - sats3[2])/(2*eps);
  p1.dsaturations_dpc_liq(pc_liq, pc_ice, sats);
  CHECK_CLOSE(sats[0], sats2[0], std::abs(sats[0])/1.e3);
  CHECK_CLOSE(sats[1], sats2[1], std::abs(sats[1])/1.e3);
  CHECK_CLOSE(sats[2], sats2[2], std::abs(sats[2])/1.e3);

  // saturated, above freezing
  // -- value
  pc_liq = -1000.;
  p1.saturations(pc_liq, pc_ice, sats);
  CHECK_CLOSE(sats[1], wrm->saturation(pc_liq), 1.e-8);

  // -- derivatives
  p1.saturations(pc_liq+eps, pc_ice, sats2);
  p1.saturations(pc_liq-eps, pc_ice, sats3);
  sats2[0] = (sats2[0] - sats3[0])/(2*eps);
  sats2[1] = (sats2[1] - sats3[1])/(2*eps);
  sats2[2] = (sats2[2] - sats3[2])/(2*eps);
  p1.dsaturations_dpc_liq(pc_liq, pc_ice, sats);
  CHECK_CLOSE(sats[0], sats2[0], std::abs(sats[0])/1.e3);
  CHECK_CLOSE(sats[1], sats2[1], std::abs(sats[1])/1.e3);
  CHECK_CLOSE(sats[2], sats2[2], std::abs(sats[2])/1.e3);

  // saturated, below freezing
  // -- value
  pc_ice = pcice.CapillaryPressure(273.1, rho);
  pc_liq = p_atm - 100000.;
  p1.saturations(pc_liq, pc_ice, sats);
  CHECK_CLOSE(sats[0], 1.5017949979397578e-09, 1.e-12);
  CHECK_CLOSE(sats[1], 6.0533870998262555e-06, 1.e-12);
  CHECK_CLOSE(sats[2], 0.9999939451111052, 1.e-8);

  // -- derivatives
  p1.saturations(pc_liq+eps, pc_ice, sats2);
  p1.saturations(pc_liq-eps, pc_ice, sats3);
  sats2[0] = (sats2[0] - sats3[0])/(2*eps);
  sats2[1] = (sats2[1] - sats3[1])/(2*eps);
  sats2[2] = (sats2[2] - sats3[2])/(2*eps);
  p1.dsaturations_dpc_liq(pc_liq, pc_ice, sats);
  CHECK_CLOSE(sats[0], sats2[0], std::abs(sats[0])/1.e3 + 1.e-10);
  CHECK_CLOSE(sats[1], sats2[1], std::abs(sats[1])/1.e3 + 1.e-10);
  CHECK_CLOSE(sats[2], sats2[2], std::abs(sats[2])/1.e3 + 1.e-10);

  p1.saturations(pc_liq, pc_ice+eps, sats2);
  p1.saturations(pc_liq, pc_ice-eps, sats3);
  sats2[0] = (sats2[0] - sats3[0])/(2.*eps);
  sats2[1] = (sats2[1] - sats3[1])/(2.*eps);
  sats2[2] = (sats2[2] - sats3[2])/(2.*eps);
  p1.dsaturations_dpc_ice(pc_liq, pc_ice, sats);
  CHECK_CLOSE(sats[0], sats2[0], std::abs(sats[0])/1.e3 + 1.e-10);
  CHECK_CLOSE(sats[1], sats2[1], std::abs(sats[1])/1.e3 + 1.e-10);
  CHECK_CLOSE(sats[2], sats2[2], std::abs(sats[2])/1.e3 + 1.e-10);

  // unsaturated, below freezing
  // -- value
  pc_liq = p_atm - (-200000);
  p1.saturations(pc_liq, pc_ice, sats);
  CHECK_CLOSE(sats[0], 0.9999974629297762, 1.e-8);
  CHECK_CLOSE(sats[1], 2.3960358028349194e-07, 1.e-12);
  CHECK_CLOSE(sats[2], 2.2974666434445524e-06, 1.e-10);

  // -- derivatives
  p1.saturations(pc_liq+eps, pc_ice, sats2);
  p1.saturations(pc_liq-eps, pc_ice, sats3);
  sats2[0] = (sats2[0] - sats3[0])/(2*eps);
  sats2[1] = (sats2[1] - sats3[1])/(2*eps);
  sats2[2] = (sats2[2] - sats3[2])/(2*eps);
  p1.dsaturations_dpc_liq(pc_liq, pc_ice, sats);
  CHECK_CLOSE(sats[0], sats2[0], std::abs(sats[0])/1.e3 + 1.e-10);
  CHECK_CLOSE(sats[1], sats2[1], std::abs(sats[1])/1.e3 + 1.e-10);
  CHECK_CLOSE(sats[2], sats2[2], std::abs(sats[2])/1.e3 + 1.e-10);

  p1.saturations(pc_liq, pc_ice+eps, sats2);
  p1.saturations(pc_liq, pc_ice-eps, sats3);
  sats2[0] = (sats2[0] - sats3[0])/(2*eps);
  sats2[1] = (sats2[1] - sats3[1])/(2*eps);
  sats2[2] = (sats2[2] - sats3[2])/(2*eps);
  p1.dsaturations_dpc_ice(pc_liq, pc_ice, sats);
  CHECK_CLOSE(sats[0], sats2[0], std::abs(sats[0])/1.e3 + 1.e-10);
  CHECK_CLOSE(sats[1], sats2[1], std::abs(sats[1])/1.e3 + 1.e-10);
  CHECK_CLOSE(sats[2], sats2[2], std::abs(sats[2])/1.e3 + 1.e-10);

}
<|endoftext|>


<commit_before>/** @addtogroup Util
 *  @{
 *  \copyright TU Dresden ZIH. All rights reserved.
 *  \authors Martin Flehmig, Marc Hartung, Marcus Walther
 *  \date Oct 2015
 */

#ifndef INCLUDE_UTIL_LOGGER_HPP_
#define INCLUDE_UTIL_LOGGER_HPP_

#ifdef USE_LOGGER
#define LOGGER_WRITE(message,category,level) Util::Logger::write(message,category,level)
#define LOGGER_WRITE_TUPLE(message,categoryLevel) Util::Logger::write(message,categoryLevel)
#else
#define LOGGER_WRITE(x,y,z)
#define LOGGER_WRITE_TUPLE(x,y)
#endif //USE_LOGGER

#include "Stdafx.hpp"

namespace Util
{
    enum LogCategory
    {
        LC_LOADER = 0,
        LC_SYS = 1,
        LC_SOLVER = 2,
        LC_EVT = 3,
        LC_OTHER = 4
    };
    enum LogLevel
    {
        LL_ERROR = 0,
        LL_WARNING = 1,
        LL_INFO = 2,
        LL_DEBUG = 3
    };

    /**
     * A container to store the configuration settings of the logger.
     */
    struct LogSettings
    {
        /**
         * An array that stores the level of the logger for all known categories.
         */
        vector<LogLevel> modes;

        /**
         * Create a new object for logger settings. All categories are set to the warning level by default.
         */
        LogSettings()
        {
            modes = vector<LogLevel>(5, LL_DEBUG);
        }
        /**
         * Set all categories at once to the given level.
         * @param level The new level for all categories.
         */
        void setAll(LogLevel level)
        {
            for (unsigned i = 0; i < modes.size(); ++i)
                modes[i] = level;
        }
    };

    /**
     * This is the base class for all logger instances. It is implemented as singleton and will write all messages
     * to the error stream.
     */
    class Logger
    {
     public:
        /**
         * Destroy the logger object.
         */
        virtual ~Logger();

        /**
         * Get the singleton instance.
         * @return The internal instance of the logger that should be used.
         */
        static Logger& getInstance()
        {
            if (instance == nullptr)
                initialize(LogSettings());

            return *instance;
        }

        /**
         * Initialize a new logger instance configured by the given settings.
         * @param settings
         */
        static void initialize(LogSettings settings)
        {
            if (instance != nullptr)
                instance.reset();

            instance = std::shared_ptr<Logger>(new Logger(settings, true));
        }

        /**
         * Initialize an instance of the default logger and store it as internal instance.
         */
        static void initialize()
        {
            initialize(LogSettings());
        }

        /**
         * This function will write the given message with the category and level information to the output of the
         * logger-instance.
         * @param message The message that should be written.
         * @param category The category of the message.
         * @param level The significance of the given message.
         */
        static inline void write(string_type  message, LogCategory category, LogLevel level)
        {
            Logger& instance = getInstance();
            if (instance.isEnabled())
                instance.writeInternal(message, category, level);
        }

        /**
         * This function will write the given message with the category and level information to the output of the
         * logger-instance.
         * @param message The message that should be written.
         * @param mode The category and significance indicator encapsulated as one pair.
         */
        static inline void write(string_type  message, std::pair<LogCategory, LogLevel> mode)
        {
            write(message, mode.first, mode.second);
        }

        /**
         * Enable or disable the logger.
         * @param enabled True if the logger should be enabled.
         */
        static void setEnabled(bool_type enabled)
        {
            getInstance().setEnabledInternal(enabled);
        }

        /**
         * Check if the logger is enabled.
         * @return True if the logger is enabled.
         */
        static bool_type isEnabled()
        {
            return getInstance().isEnabledInternal();
        }

        /**
         * Check if a message with the given level, belonging the give category will be written through the logger.
         * @param category The category that should be checked.
         * @param level The level that should be checked.
         * @return True if the message would not be filtered and written to the output.
         */
        bool_type isOutput(LogCategory category, LogLevel level) const;
        /**
         * Check if a message with the given level, belonging the give category will be written through the logger.
         * @param mode The category and level that should be checked.
         * @return True if the message would not be filtered and written to the output.
         */
        bool_type isOutput(std::pair<LogCategory, LogLevel> mode) const;

     protected:
        /**
         * Create a new logger instance with the given settings.
         * @attention There should be just one logger-instance, so take care about the singleton.
         * @param settings The settings of the logger.
         * @param enabled True if the logger should be enabled.
         */
        Logger(LogSettings settings, bool_type enabled);
        /**
         * Create a new logger instance with default settings.
         * @attention There should be just one logger-instance, so take care about the singleton.
         * @param enabled True if the logger should be enabled.
         */
        Logger(bool_type enabled);
        /**
         * Write the message with the given category and level information to the output.
         * @note This function should be overwritten by concrete logger implementation.
         * @param message The message that should be written.
         * @param category The category of the message.
         * @param level The significance of the given message.
         */
        virtual void writeInternal(string_type  message, LogCategory category, LogLevel level);
        /**
         * Enable or disable the logger.
         * @param enabled True if the logger should be enabled.
         * @note This function can be overwritten by concrete logger implementations.
         */
        virtual void setEnabledInternal(bool_type enabled);
        /**
         * Check if the logger is enabled.
         * @return True if the logger is enabled.
         * @note This function can be overwritten by concrete logger implementations.
         */
        virtual bool_type isEnabledInternal();
        /**
         * Get a prefix text decoration for a message of the given category and level.
         * @param category The category of the message.
         * @param level The level of the message.
         * @return The prefix that contains color information.
         */
        string_type  getPrefix(LogCategory category, LogLevel level) const;
        /**
         * Get a suffix text decoration for a message of the given category and level.
         * @param category The category of the message.
         * @param level The level of the message.
         * @return The suffix that contains color and category information.
         */
        string_type  getSuffix(LogCategory category, LogLevel level) const;
        /**
         * Convert the given log category to string.
         * @param category The category that should be converted.
         * @return The result string.
         */
        string_type  logCategoryToString(LogCategory category) const;
        /**
         * Convert the given log level to string.
         * @param level The level that should be converted.
         * @return The result string.
         */
        string_type  logLevelToString(LogLevel level) const;
        /**
         * The static logger singleton instance. This should be set by the initialize method of the concrete logger
         * implementation.
         */
        static std::shared_ptr<Logger> instance;

     private:
        LogSettings _settings;
        vector<std::tuple<string_type , string_type > > _textDecorator;
        bool_type _isEnabled;
    };

} /* namespace Util */

#endif /* INCLUDE_UTIL_LOGGER_HPP_ */
/**
 * @}
 */
<commit_msg>Use a initializer list to initialize members<commit_after>/** @addtogroup Util
 *  @{
 *  \copyright TU Dresden ZIH. All rights reserved.
 *  \authors Martin Flehmig, Marc Hartung, Marcus Walther
 *  \date Oct 2015
 */

#ifndef INCLUDE_UTIL_LOGGER_HPP_
#define INCLUDE_UTIL_LOGGER_HPP_

#ifdef USE_LOGGER
#define LOGGER_WRITE(message,category,level) Util::Logger::write(message,category,level)
#define LOGGER_WRITE_TUPLE(message,categoryLevel) Util::Logger::write(message,categoryLevel)
#else
#define LOGGER_WRITE(x,y,z)
#define LOGGER_WRITE_TUPLE(x,y)
#endif //USE_LOGGER

#include "Stdafx.hpp"

namespace Util
{
    enum LogCategory
    {
        LC_LOADER = 0,
        LC_SYS = 1,
        LC_SOLVER = 2,
        LC_EVT = 3,
        LC_OTHER = 4
    };
    enum LogLevel
    {
        LL_ERROR = 0,
        LL_WARNING = 1,
        LL_INFO = 2,
        LL_DEBUG = 3
    };

    /**
     * A container to store the configuration settings of the logger.
     */
    struct LogSettings
    {
        /**
         * An array that stores the level of the logger for all known categories.
         */
        vector<LogLevel> modes;

        /**
         * Create a new object for logger settings. All categories are set to the warning level by default.
         */
        LogSettings()
                : modes(vector<LogLevel>(5, LL_DEBUG))
        {
        }

        /**
         * Set all categories at once to the given level.
         * @param level The new level for all categories.
         */
        void setAll(LogLevel level)
        {
            for (unsigned i = 0; i < modes.size(); ++i)
                modes[i] = level;
        }
    };

    /**
     * This is the base class for all logger instances. It is implemented as singleton and will write all messages
     * to the error stream.
     */
    class Logger
    {
     public:
        /**
         * Destroy the logger object.
         */
        virtual ~Logger();

        /**
         * Get the singleton instance.
         * @return The internal instance of the logger that should be used.
         */
        static Logger& getInstance()
        {
            if (instance == nullptr)
                initialize(LogSettings());

            return *instance;
        }

        /**
         * Initialize a new logger instance configured by the given settings.
         * @param settings
         */
        static void initialize(LogSettings settings)
        {
            if (instance != nullptr)
                instance.reset();

            instance = std::shared_ptr<Logger>(new Logger(settings, true));
        }

        /**
         * Initialize an instance of the default logger and store it as internal instance.
         */
        static void initialize()
        {
            initialize(LogSettings());
        }

        /**
         * This function will write the given message with the category and level information to the output of the
         * logger-instance.
         * @param message The message that should be written.
         * @param category The category of the message.
         * @param level The significance of the given message.
         */
        static inline void write(string_type message, LogCategory category, LogLevel level)
        {
            Logger& instance = getInstance();
            if (instance.isEnabled())
                instance.writeInternal(message, category, level);
        }

        /**
         * This function will write the given message with the category and level information to the output of the
         * logger-instance.
         * @param message The message that should be written.
         * @param mode The category and significance indicator encapsulated as one pair.
         */
        static inline void write(string_type message, std::pair<LogCategory, LogLevel> mode)
        {
            write(message, mode.first, mode.second);
        }

        /**
         * Enable or disable the logger.
         * @param enabled True if the logger should be enabled.
         */
        static void setEnabled(bool_type enabled)
        {
            getInstance().setEnabledInternal(enabled);
        }

        /**
         * Check if the logger is enabled.
         * @return True if the logger is enabled.
         */
        static bool_type isEnabled()
        {
            return getInstance().isEnabledInternal();
        }

        /**
         * Check if a message with the given level, belonging the give category will be written through the logger.
         * @param category The category that should be checked.
         * @param level The level that should be checked.
         * @return True if the message would not be filtered and written to the output.
         */
        bool_type isOutput(LogCategory category, LogLevel level) const;
        /**
         * Check if a message with the given level, belonging the give category will be written through the logger.
         * @param mode The category and level that should be checked.
         * @return True if the message would not be filtered and written to the output.
         */
        bool_type isOutput(std::pair<LogCategory, LogLevel> mode) const;

     protected:
        /**
         * Create a new logger instance with the given settings.
         * @attention There should be just one logger-instance, so take care about the singleton.
         * @param settings The settings of the logger.
         * @param enabled True if the logger should be enabled.
         */
        Logger(LogSettings settings, bool_type enabled);
        /**
         * Create a new logger instance with default settings.
         * @attention There should be just one logger-instance, so take care about the singleton.
         * @param enabled True if the logger should be enabled.
         */
        Logger(bool_type enabled);
        /**
         * Write the message with the given category and level information to the output.
         * @note This function should be overwritten by concrete logger implementation.
         * @param message The message that should be written.
         * @param category The category of the message.
         * @param level The significance of the given message.
         */
        virtual void writeInternal(string_type message, LogCategory category, LogLevel level);
        /**
         * Enable or disable the logger.
         * @param enabled True if the logger should be enabled.
         * @note This function can be overwritten by concrete logger implementations.
         */
        virtual void setEnabledInternal(bool_type enabled);
        /**
         * Check if the logger is enabled.
         * @return True if the logger is enabled.
         * @note This function can be overwritten by concrete logger implementations.
         */
        virtual bool_type isEnabledInternal();
        /**
         * Get a prefix text decoration for a message of the given category and level.
         * @param category The category of the message.
         * @param level The level of the message.
         * @return The prefix that contains color information.
         */
        string_type getPrefix(LogCategory category, LogLevel level) const;
        /**
         * Get a suffix text decoration for a message of the given category and level.
         * @param category The category of the message.
         * @param level The level of the message.
         * @return The suffix that contains color and category information.
         */
        string_type getSuffix(LogCategory category, LogLevel level) const;
        /**
         * Convert the given log category to string.
         * @param category The category that should be converted.
         * @return The result string.
         */
        string_type logCategoryToString(LogCategory category) const;
        /**
         * Convert the given log level to string.
         * @param level The level that should be converted.
         * @return The result string.
         */
        string_type logLevelToString(LogLevel level) const;
        /**
         * The static logger singleton instance. This should be set by the initialize method of the concrete logger
         * implementation.
         */
        static std::shared_ptr<Logger> instance;

     private:
        LogSettings _settings;
        vector<std::tuple<string_type, string_type> > _textDecorator;
        bool_type _isEnabled;
    };

} /* namespace Util */

#endif /* INCLUDE_UTIL_LOGGER_HPP_ */
/**
 * @}
 */
<|endoftext|>


<commit_before>/******************************************************************************
 * This file is part of the Gluon Development Platform
 * Copyright (C) 2008 Sacha Schutz <istdasklar@free.fr>
 * Copyright (C) 2010 Kim Jung Nissen <jungnissen@gmail.com>
 * Copyright (C) 2010 Laszlo Papp <djszapi@archlinux.us>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "detectwin.h"

#include "inputthread.h"

#include <core/debughelper.h>

#include <QtCore/QDir>
#include <QtCore/QCoreApplication>
#include <QtGui/QMessageBox>
#include <QtCore/QDebug>

using namespace GluonInput;

class DetectWin::DetectWinPrivate
{
    public:
        QList<InputDevice*> inputList;
        QList<Keyboard*> keyboardList;
        QList<Mouse*> mouseList;
        QList<Joystick*> joystickList;
        QList<Touch*> touchList;
        QList<InputDevice*> unknownList;
};

DetectWin::DetectWin( QObject* parent )
    : Detect( parent )
    , d( new DetectWinPrivate )
{
}

DetectWin::~DetectWin()
{
}

bool DetectWin::isReadable()
{
}

void DetectWin::detectDevices()
{
}

void DetectWin::setAllEnabled( bool enable )
{
    foreach( InputDevice * input, inputList() )
    {
        input->setEnabled( enable );
    }
}

void DetectWin::clear()
{
    d->inputList.clear();
    d->keyboardList.clear();
    d->mouseList.clear();
    d->joystickList.clear();
    d->touchList.clear();
    d->unknownList.clear();
}

void DetectWin::addInput( InputDevice* i )
{
    d->inputList.append( i );
}

void DetectWin::addKeyboard( Keyboard* keybd )
{
    d->keyboardList.append( keybd );
}

void DetectWin::addMouse( Mouse* mouse )
{
    d->mouseList.append( mouse );
}

void DetectWin::addJoystick( Joystick* joystick )
{
    d->joystickList.append( joystick );
}

void DetectWin::addTouch( Touch* touch )
{
    d->touchList.append( touch );
}

void DetectWin::addUnknown( InputDevice* i )
{
    d->unknownList.append( i );
}

QList<InputDevice*> DetectWin::inputList()
{
    return d->inputList;
}

QList<Keyboard*> DetectWin::keyboardList()
{
    return d->keyboardList;
}

QList<Mouse*> DetectWin::mouseList()
{
    return d->mouseList;
}

QList<Joystick*> DetectWin::joystickList()
{
    return d->joystickList;
}

QList<Touch*> DetectWin::touchList()
{
    return d->touchList;
}

QList<InputDevice*> DetectWin::unknownDeviceList()
{
    return d->unknownList;
}
<commit_msg>Return Readable - false value for now on Windows at the input detection.<commit_after>/******************************************************************************
 * This file is part of the Gluon Development Platform
 * Copyright (C) 2008 Sacha Schutz <istdasklar@free.fr>
 * Copyright (C) 2010 Kim Jung Nissen <jungnissen@gmail.com>
 * Copyright (C) 2010 Laszlo Papp <djszapi@archlinux.us>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "detectwin.h"

#include "inputthread.h"

#include <core/debughelper.h>

#include <QtCore/QDir>
#include <QtCore/QCoreApplication>
#include <QtGui/QMessageBox>
#include <QtCore/QDebug>

using namespace GluonInput;

class DetectWin::DetectWinPrivate
{
    public:
        QList<InputDevice*> inputList;
        QList<Keyboard*> keyboardList;
        QList<Mouse*> mouseList;
        QList<Joystick*> joystickList;
        QList<Touch*> touchList;
        QList<InputDevice*> unknownList;
};

DetectWin::DetectWin( QObject* parent )
    : Detect( parent )
    , d( new DetectWinPrivate )
{
}

DetectWin::~DetectWin()
{
}

bool DetectWin::isReadable()
{
    return false;
}

void DetectWin::detectDevices()
{
}

void DetectWin::setAllEnabled( bool enable )
{
    foreach( InputDevice * input, inputList() )
    {
        input->setEnabled( enable );
    }
}

void DetectWin::clear()
{
    d->inputList.clear();
    d->keyboardList.clear();
    d->mouseList.clear();
    d->joystickList.clear();
    d->touchList.clear();
    d->unknownList.clear();
}

void DetectWin::addInput( InputDevice* i )
{
    d->inputList.append( i );
}

void DetectWin::addKeyboard( Keyboard* keybd )
{
    d->keyboardList.append( keybd );
}

void DetectWin::addMouse( Mouse* mouse )
{
    d->mouseList.append( mouse );
}

void DetectWin::addJoystick( Joystick* joystick )
{
    d->joystickList.append( joystick );
}

void DetectWin::addTouch( Touch* touch )
{
    d->touchList.append( touch );
}

void DetectWin::addUnknown( InputDevice* i )
{
    d->unknownList.append( i );
}

QList<InputDevice*> DetectWin::inputList()
{
    return d->inputList;
}

QList<Keyboard*> DetectWin::keyboardList()
{
    return d->keyboardList;
}

QList<Mouse*> DetectWin::mouseList()
{
    return d->mouseList;
}

QList<Joystick*> DetectWin::joystickList()
{
    return d->joystickList;
}

QList<Touch*> DetectWin::touchList()
{
    return d->touchList;
}

QList<InputDevice*> DetectWin::unknownDeviceList()
{
    return d->unknownList;
}
<|endoftext|>


<commit_before>// Copyright 2010-2012 RethinkDB, all rights reserved.
#include "compatibility/boost.hpp"

#if BOOST_VERSION >= 104200
boost::program_options::validation_error::kind_t boost_program_options_validation_error_type_to_kind(
     enum boost_program_options_validation_error_type input
) {
    // This function converts from the internal enum to the boost enum.
    switch(input) {
        case multiple_values_not_allowed:
             return boost::program_options::validation_error::multiple_values_not_allowed;
             break ;
        case at_least_one_value_required:
             return boost::program_options::validation_error::at_least_one_value_required;
             break;
        case invalid_bool_value:
             return boost::program_options::validation_error::invalid_bool_value;
             break;
        case invalid_option_value:
             return boost::program_options::validation_error::invalid_option_value;
             break;
        case invalid_option:
             return boost::program_options::validation_error::invalid_option;
             break;
        default:
             // This seems a decent if not desirable fallback.
             return boost::program_options::validation_error::invalid_option;
             break;
    }
    // We have a return value here so as to help older compilers to figure things out.
    return boost::program_options::validation_error::invalid_option;
}
#endif

std::string boost_program_options_validation_error_type_to_string(
    enum boost_program_options_validation_error_type input
) {
    // This function converts from the internal enum to a string.
    switch(input) {
        case multiple_values_not_allowed:
            return STR_multiple_values_not_allowed;
            break;
        case at_least_one_value_required:
            return STR_at_least_one_value_required;
            break;
        case invalid_bool_value:
            return STR_invalid_bool_value;
            break ;
        case invalid_option_value:
            return STR_invalid_option_value;
            break;
        case invalid_option:
            return STR_invalid_option;
            break;
        default:
            return "Unknown error";
            break;
    }
    return "Error handling error";
}

void boost_program_options_validation_error_wrap(
    enum boost_program_options_validation_error_type error_type,
    std::string error_item
) {
#if BOOST_VERSION >= 104200
    throw boost::program_options::validation_error(
        boost_program_options_validation_error_type_to_kind(error_type),
        error_item ) ;
#else
    throw boost::program_options::validation_error(
        boost_program_options_validation_error_type_to_string( error_type )+
        ": "+
        error_item);
#endif
}

<commit_msg>More formatting.<commit_after>// Copyright 2010-2012 RethinkDB, all rights reserved.
#include "compatibility/boost.hpp"

#if BOOST_VERSION >= 104200
boost::program_options::validation_error::kind_t boost_program_options_validation_error_type_to_kind(
     enum boost_program_options_validation_error_type input
) {
    // This function converts from the internal enum to the boost enum.
    switch(input) {
        case multiple_values_not_allowed:
             return boost::program_options::validation_error::multiple_values_not_allowed;
             break;
        case at_least_one_value_required:
             return boost::program_options::validation_error::at_least_one_value_required;
             break;
        case invalid_bool_value:
             return boost::program_options::validation_error::invalid_bool_value;
             break;
        case invalid_option_value:
             return boost::program_options::validation_error::invalid_option_value;
             break;
        case invalid_option:
             return boost::program_options::validation_error::invalid_option;
             break;
        default:
             // This seems a decent if not desirable fallback.
             return boost::program_options::validation_error::invalid_option;
             break;
    }
    // We have a return value here so as to help older compilers to figure things out.
    return boost::program_options::validation_error::invalid_option;
}
#endif

std::string boost_program_options_validation_error_type_to_string(
    enum boost_program_options_validation_error_type input
) {
    // This function converts from the internal enum to a string.
    switch(input) {
        case multiple_values_not_allowed:
            return STR_multiple_values_not_allowed;
            break;
        case at_least_one_value_required:
            return STR_at_least_one_value_required;
            break;
        case invalid_bool_value:
            return STR_invalid_bool_value;
            break ;
        case invalid_option_value:
            return STR_invalid_option_value;
            break;
        case invalid_option:
            return STR_invalid_option;
            break;
        default:
            return "Unknown error";
            break;
    }
    return "Error handling error";
}

void boost_program_options_validation_error_wrap(
    enum boost_program_options_validation_error_type error_type,
    std::string error_item
) {
#if BOOST_VERSION >= 104200
    throw boost::program_options::validation_error(
        boost_program_options_validation_error_type_to_kind(error_type),
        error_item );
#else
    throw boost::program_options::validation_error(
        boost_program_options_validation_error_type_to_string( error_type )+
        ": "+
        error_item);
#endif
}

<|endoftext|>


<commit_before>// RUN: %clangxx -fsanitize=integer-divide-by-zero -DDIVIDEND=0 %s -o %t && %run %t 2>&1 | FileCheck %s
// RUN: %clangxx -fsanitize=integer-divide-by-zero -DDIVIDEND=1U %s -o %t && %run %t 2>&1 | FileCheck %s
// RUN: %clangxx -fsanitize=integer-divide-by-zero -DDIVIDEND='intmax(123)' %s -o %t && %run %t 2>&1 | FileCheck %s

#if defined(__SIZEOF_INT128__) && !defined(_WIN32)
typedef __int128 intmax;
#else
typedef long long intmax;
#endif

int main() {
  // CHECK: div-zero.cpp:[[@LINE+1]]:12: runtime error: division by zero
  DIVIDEND / 0;
}
<commit_msg>[ubsan][test] Restore float-divide-by-zero test<commit_after>// RUN: %clangxx -fsanitize=integer-divide-by-zero -DDIVIDEND=0 %s -o %t && %run %t 2>&1 | FileCheck %s
// RUN: %clangxx -fsanitize=integer-divide-by-zero -DDIVIDEND=1U %s -o %t && %run %t 2>&1 | FileCheck %s
// RUN: %clangxx -fsanitize=integer-divide-by-zero -DDIVIDEND='intmax(123)' %s -o %t && %run %t 2>&1 | FileCheck %s
// RUN: %clangxx -fsanitize=float-divide-by-zero -DDIVIDEND=1.5 %s -o %t && %run %t 2>&1 | FileCheck %s

#if defined(__SIZEOF_INT128__) && !defined(_WIN32)
typedef __int128 intmax;
#else
typedef long long intmax;
#endif

int main() {
  // CHECK: div-zero.cpp:[[@LINE+1]]:12: runtime error: division by zero
  DIVIDEND / 0;
}
<|endoftext|>