<commit_before>#ifndef UTIL_RECT_H__
#define UTIL_RECT_H__

#include <sstream>
#include <iostream>

#include "point.hpp"

namespace util {

template <typename T>
struct rect {

	/**
	 * Default constructor.
	 */
	rect() {};

	template <typename S>
	rect(const rect<S>& other) :
		minX(other.minX),
		minY(other.minY),
		maxX(other.maxX),
		maxY(other.maxY) {};

	rect(const T& minX_, const T& minY_, const T& maxX_, const T& maxY_) :
		minX(minX_),
		minY(minY_),
		maxX(maxX_),
		maxY(maxY_) {};

	T minX;
	T minY;
	T maxX;
	T maxY;

	T width() const {

		return maxX - minX;
	}

	T height() const {

		return maxY - minY;
	}

	point<T> upperLeft() const {

		return point<T>(minX, minY);
	}

	point<T> lowerRight() const {

		return point<T>(maxX, maxY);
	}

	point<T> upperRight() const {

		return point<T>(maxX, minY);
	}

	point<T> lowerLeft() const {

		return point<T>(minX, maxY);
	}

	point<T> center() const {

		return point<T>((minX + maxX)/2, (minY + maxY)/2);
	}

	template <typename S>
	bool intersects(const rect<S>& other) const {

		// empty rectangles do not intersect
		if (area() <= 0 || other.area() <= 0)
			return false;

		// two non-intersecting rectanlges are separated by a line parallel to
		// either x or y

		// separated by x-line
		if (maxX <= other.minX || minX >= other.maxX)
			return false;

		// separated by y-line
		if (maxY <= other.minY || minY >= other.maxY)
			return false;

		return true;
	}

	template <typename S>
	rect<T> intersection(const rect<S>& other) const {

		rect<T> result(0, 0, 0, 0);

		if (!intersects(other))
			return result;

		result.minX = std::max(minX, other.minX);
		result.minY = std::max(minY, other.minY);
		result.maxX = std::min(maxX, other.maxX);
		result.maxY = std::min(maxY, other.maxY);

		return result;
	}

	bool contains(const point<T>& point) const {

		return minX <= point.x && minY <= point.y && maxX > point.x && maxY > point.y;
	}

	bool contains(const rect<T>& other) const {

		return minX <= other.minX && minY <= other.minY && maxX >= other.maxX && maxY >= other.maxY;
	}

	/**
	 * Extend this rect, such that it fits the given point.
	 */
	void fit(const point<T>& point) {

		if (isZero()) {

			minX = point.x;
			maxX = point.x;
			minY = point.y;
			maxY = point.y;
			return;
		}

		minX = std::min(point.x, minX);
		minY = std::min(point.y, minY);
		maxX = std::max(point.x, maxX);
		maxY = std::max(point.y, maxY);
	}

	/**
	 * Extend this rect, such that it fits the given rect.
	 */
	void fit(const rect<T>& rect) {

		if (isZero()) {

			*this = rect;
			return;
		}

		minX = std::min(rect.minX, minX);
		minY = std::min(rect.minY, minY);
		maxX = std::max(rect.maxX, maxX);
		maxY = std::max(rect.maxY, maxY);
	}

	T area() const {

		return width()*height();
	}

	bool isZero() const {

		return minX == 0 && minY == 0 && maxX == 0 && maxY == 0;
	}

	template <typename S>
	rect<T>& operator+=(const point<S>& other) {

		minX += other.x;
		maxX += other.x;
		minY += other.y;
		maxY += other.y;

		return *this;
	}

	template <typename S>
	rect<T>& operator-=(const point<S>& other) {

		minX -= other.x;
		maxX -= other.x;
		minY -= other.y;
		maxY -= other.y;

		return *this;
	}

	template <typename S>
	rect<T>& operator*=(const S& s) {

		minX *= s;
		maxX *= s;
		minY *= s;
		maxY *= s;

		return *this;
	}

	template <typename S>
	rect<T>& operator/=(const S& s) {

		minX /= s;
		maxX /= s;
		minY /= s;
		maxY /= s;

		return *this;
	}

	template <typename S>
	rect<T>& operator*=(const point<S>& p) {

		minX *= p.x;
		maxX *= p.x;
		minY *= p.y;
		maxY *= p.y;

		return *this;
	}

	template <typename S>
	rect<T>& operator/=(const point<S>& p) {

		minX /= p.x;
		maxX /= p.x;
		minY /= p.y;
		maxY /= p.y;

		return *this;
	}

	template <typename S>
	bool operator==(const rect<S>& other) const {

		return minX == other.minX &&
		       minY == other.minY &&
		       maxX == other.maxX &&
		       maxY == other.maxY;
	}

	template <typename S>
	bool operator!=(const rect<S>& other) const {

		return !(*this == other);
	}
};

} // namespace util

template <typename T, typename S>
util::rect<T> operator+(const util::rect<T>& p, const util::point<S>& o) {

	util::rect<T> result(p);

	return result += o;
}

template <typename T, typename S>
util::rect<T> operator-(const util::rect<T>& p, const util::point<S>& o) {

	util::rect<T> result(p);

	return result -= o;
}

template <typename T, typename S>
util::rect<T> operator*(const util::rect<T>& p, const S& s) {

	util::rect<T> result(p);

	return result *= s;
}

template <typename T, typename S>
util::rect<S> operator*(const S& s, const util::rect<T>& p) {

	util::rect<S> result(p);

	return result *= s;
}

template <typename T, typename S>
util::rect<T> operator/(const util::rect<T>& p, const S& s) {

	util::rect<T> result(p);

	return result /= s;
}

template <typename T>
std::ostream& operator<<(std::ostream& os, const util::rect<T>& rect) {

	os << "[" << rect.minX << ", " << rect.minY
	   << ", " << rect.maxX << ", " << rect.maxY << "]";

	return os;
}

#endif // UTIL_RECT_H__

<commit_msg>rect<T>: default constructor initializes with 0<commit_after>#ifndef UTIL_RECT_H__
#define UTIL_RECT_H__

#include <sstream>
#include <iostream>

#include "point.hpp"

namespace util {

template <typename T>
struct rect {

	/**
	 * Default constructor.
	 */
	rect() : minX(0), minY(0), maxX(0), maxY(0) {};

	template <typename S>
	rect(const rect<S>& other) :
		minX(other.minX),
		minY(other.minY),
		maxX(other.maxX),
		maxY(other.maxY) {};

	rect(const T& minX_, const T& minY_, const T& maxX_, const T& maxY_) :
		minX(minX_),
		minY(minY_),
		maxX(maxX_),
		maxY(maxY_) {};

	T minX;
	T minY;
	T maxX;
	T maxY;

	T width() const {

		return maxX - minX;
	}

	T height() const {

		return maxY - minY;
	}

	point<T> upperLeft() const {

		return point<T>(minX, minY);
	}

	point<T> lowerRight() const {

		return point<T>(maxX, maxY);
	}

	point<T> upperRight() const {

		return point<T>(maxX, minY);
	}

	point<T> lowerLeft() const {

		return point<T>(minX, maxY);
	}

	point<T> center() const {

		return point<T>((minX + maxX)/2, (minY + maxY)/2);
	}

	template <typename S>
	bool intersects(const rect<S>& other) const {

		// empty rectangles do not intersect
		if (area() <= 0 || other.area() <= 0)
			return false;

		// two non-intersecting rectanlges are separated by a line parallel to
		// either x or y

		// separated by x-line
		if (maxX <= other.minX || minX >= other.maxX)
			return false;

		// separated by y-line
		if (maxY <= other.minY || minY >= other.maxY)
			return false;

		return true;
	}

	template <typename S>
	rect<T> intersection(const rect<S>& other) const {

		rect<T> result(0, 0, 0, 0);

		if (!intersects(other))
			return result;

		result.minX = std::max(minX, other.minX);
		result.minY = std::max(minY, other.minY);
		result.maxX = std::min(maxX, other.maxX);
		result.maxY = std::min(maxY, other.maxY);

		return result;
	}

	bool contains(const point<T>& point) const {

		return minX <= point.x && minY <= point.y && maxX > point.x && maxY > point.y;
	}

	bool contains(const rect<T>& other) const {

		return minX <= other.minX && minY <= other.minY && maxX >= other.maxX && maxY >= other.maxY;
	}

	/**
	 * Extend this rect, such that it fits the given point.
	 */
	void fit(const point<T>& point) {

		if (isZero()) {

			minX = point.x;
			maxX = point.x;
			minY = point.y;
			maxY = point.y;
			return;
		}

		minX = std::min(point.x, minX);
		minY = std::min(point.y, minY);
		maxX = std::max(point.x, maxX);
		maxY = std::max(point.y, maxY);
	}

	/**
	 * Extend this rect, such that it fits the given rect.
	 */
	void fit(const rect<T>& rect) {

		if (isZero()) {

			*this = rect;
			return;
		}

		minX = std::min(rect.minX, minX);
		minY = std::min(rect.minY, minY);
		maxX = std::max(rect.maxX, maxX);
		maxY = std::max(rect.maxY, maxY);
	}

	T area() const {

		return width()*height();
	}

	bool isZero() const {

		return minX == 0 && minY == 0 && maxX == 0 && maxY == 0;
	}

	template <typename S>
	rect<T>& operator+=(const point<S>& other) {

		minX += other.x;
		maxX += other.x;
		minY += other.y;
		maxY += other.y;

		return *this;
	}

	template <typename S>
	rect<T>& operator-=(const point<S>& other) {

		minX -= other.x;
		maxX -= other.x;
		minY -= other.y;
		maxY -= other.y;

		return *this;
	}

	template <typename S>
	rect<T>& operator*=(const S& s) {

		minX *= s;
		maxX *= s;
		minY *= s;
		maxY *= s;

		return *this;
	}

	template <typename S>
	rect<T>& operator/=(const S& s) {

		minX /= s;
		maxX /= s;
		minY /= s;
		maxY /= s;

		return *this;
	}

	template <typename S>
	rect<T>& operator*=(const point<S>& p) {

		minX *= p.x;
		maxX *= p.x;
		minY *= p.y;
		maxY *= p.y;

		return *this;
	}

	template <typename S>
	rect<T>& operator/=(const point<S>& p) {

		minX /= p.x;
		maxX /= p.x;
		minY /= p.y;
		maxY /= p.y;

		return *this;
	}

	template <typename S>
	bool operator==(const rect<S>& other) const {

		return minX == other.minX &&
		       minY == other.minY &&
		       maxX == other.maxX &&
		       maxY == other.maxY;
	}

	template <typename S>
	bool operator!=(const rect<S>& other) const {

		return !(*this == other);
	}
};

} // namespace util

template <typename T, typename S>
util::rect<T> operator+(const util::rect<T>& p, const util::point<S>& o) {

	util::rect<T> result(p);

	return result += o;
}

template <typename T, typename S>
util::rect<T> operator-(const util::rect<T>& p, const util::point<S>& o) {

	util::rect<T> result(p);

	return result -= o;
}

template <typename T, typename S>
util::rect<T> operator*(const util::rect<T>& p, const S& s) {

	util::rect<T> result(p);

	return result *= s;
}

template <typename T, typename S>
util::rect<S> operator*(const S& s, const util::rect<T>& p) {

	util::rect<S> result(p);

	return result *= s;
}

template <typename T, typename S>
util::rect<T> operator/(const util::rect<T>& p, const S& s) {

	util::rect<T> result(p);

	return result /= s;
}

template <typename T>
std::ostream& operator<<(std::ostream& os, const util::rect<T>& rect) {

	os << "[" << rect.minX << ", " << rect.minY
	   << ", " << rect.maxX << ", " << rect.maxY << "]";

	return os;
}

#endif // UTIL_RECT_H__

<|endoftext|>


<commit_before>#ifndef UTIL_RECT_H__
#define UTIL_RECT_H__

#include <sstream>
#include <iostream>

#include "point.hpp"

namespace util {

template <typename T>
struct rect {

	/**
	 * Default constructor.
	 */
	rect() {};

	template <typename S>
	rect(const rect<S>& other) :
		minX(other.minX),
		minY(other.minY),
		maxX(other.maxX),
		maxY(other.maxY) {};

	rect(const T& minX_, const T& minY_, const T& maxX_, const T& maxY_) :
		minX(minX_),
		minY(minY_),
		maxX(maxX_),
		maxY(maxY_) {};

	T minX;
	T minY;
	T maxX;
	T maxY;

	T width() const {

		return maxX - minX;
	}

	T height() const {

		return maxY - minY;
	}

	point<T> upperLeft() const {

		return point<T>(minX, minY);
	}

	point<T> lowerRight() const {

		return point<T>(maxX, maxY);
	}

	bool intersects(const rect<T>& other) const {

		// two non-intersecting rectanlges are separated by a line parallel to
		// either x or y

		// separated by x-line
		if (maxX < other.minX || minX > other.maxX)
			return false;

		// separated by y-line
		if (maxY < other.minY || minY > other.maxY)
			return false;

		return true;
	}

	bool contains(const point<T>& point) const {

		return minX <= point.x && minY <= point.y && maxX > point.x && maxY > point.y;
	}

	T area() const {

		return width()*height();
	}

	template <typename S>
	rect<T>& operator+=(const point<S>& other) {

		minX += other.x;
		maxX += other.x;
		minY += other.y;
		maxY += other.y;

		return *this;
	}

	template <typename S>
	rect<T>& operator-=(const point<S>& other) {

		minX -= other.x;
		maxX -= other.x;
		minY -= other.y;
		maxY -= other.y;

		return *this;
	}

	template <typename S>
	rect<T>& operator*=(const S& s) {

		minX *= s;
		maxX *= s;
		minY *= s;
		maxY *= s;

		return *this;
	}

	template <typename S>
	rect<T>& operator/=(const S& s) {

		minX /= s;
		maxX /= s;
		minY /= s;
		maxY /= s;

		return *this;
	}

	template <typename S>
	rect<T>& operator*=(const point<S>& p) {

		minX *= p.x;
		maxX *= p.x;
		minY *= p.y;
		maxY *= p.y;

		return *this;
	}

	template <typename S>
	rect<T>& operator/=(const point<S>& p) {

		minX /= p.x;
		maxX /= p.x;
		minY /= p.y;
		maxY /= p.y;

		return *this;
	}

	template <typename S>
	bool operator==(const rect<S>& other) const {

		return minX == other.minX &&
		       minY == other.minY &&
		       maxX == other.maxX &&
		       maxY == other.maxY;
	}

	template <typename S>
	bool operator!=(const rect<S>& other) const {

		return !(*this == other);
	}
};

} // namespace util

template <typename T, typename S>
util::rect<T> operator+(const util::rect<T>& p, const util::point<S>& o) {

	util::rect<T> result(p);

	return result += o;
}

template <typename T, typename S>
util::rect<T> operator-(const util::rect<T>& p, const util::point<S>& o) {

	util::rect<T> result(p);

	return result -= o;
}

template <typename T, typename S>
util::rect<T> operator*(const util::rect<T>& p, const S& s) {

	util::rect<T> result(p);

	return result *= s;
}

template <typename T, typename S>
util::rect<T> operator*(const S& s, const util::rect<T>& p) {

	util::rect<T> result(p);

	return result *= s;
}

template <typename T, typename S>
util::rect<T> operator/(const util::rect<T>& p, const S& s) {

	util::rect<T> result(p);

	return result /= s;
}

template <typename T>
std::ostream& operator<<(std::ostream& os, const util::rect<T>& rect) {

	os << "[" << rect.minX << ", " << rect.minY
	   << ", " << rect.maxX << ", " << rect.maxY << "]";

	return os;
}

#endif // UTIL_RECT_H__

<commit_msg>added center() method to rect<commit_after>#ifndef UTIL_RECT_H__
#define UTIL_RECT_H__

#include <sstream>
#include <iostream>

#include "point.hpp"

namespace util {

template <typename T>
struct rect {

	/**
	 * Default constructor.
	 */
	rect() {};

	template <typename S>
	rect(const rect<S>& other) :
		minX(other.minX),
		minY(other.minY),
		maxX(other.maxX),
		maxY(other.maxY) {};

	rect(const T& minX_, const T& minY_, const T& maxX_, const T& maxY_) :
		minX(minX_),
		minY(minY_),
		maxX(maxX_),
		maxY(maxY_) {};

	T minX;
	T minY;
	T maxX;
	T maxY;

	T width() const {

		return maxX - minX;
	}

	T height() const {

		return maxY - minY;
	}

	point<T> upperLeft() const {

		return point<T>(minX, minY);
	}

	point<T> lowerRight() const {

		return point<T>(maxX, maxY);
	}

	point<T> center() const {

		return point<T>((minX + maxX)/2, (minY + maxY)/2);
	}

	bool intersects(const rect<T>& other) const {

		// two non-intersecting rectanlges are separated by a line parallel to
		// either x or y

		// separated by x-line
		if (maxX < other.minX || minX > other.maxX)
			return false;

		// separated by y-line
		if (maxY < other.minY || minY > other.maxY)
			return false;

		return true;
	}

	bool contains(const point<T>& point) const {

		return minX <= point.x && minY <= point.y && maxX > point.x && maxY > point.y;
	}

	T area() const {

		return width()*height();
	}

	template <typename S>
	rect<T>& operator+=(const point<S>& other) {

		minX += other.x;
		maxX += other.x;
		minY += other.y;
		maxY += other.y;

		return *this;
	}

	template <typename S>
	rect<T>& operator-=(const point<S>& other) {

		minX -= other.x;
		maxX -= other.x;
		minY -= other.y;
		maxY -= other.y;

		return *this;
	}

	template <typename S>
	rect<T>& operator*=(const S& s) {

		minX *= s;
		maxX *= s;
		minY *= s;
		maxY *= s;

		return *this;
	}

	template <typename S>
	rect<T>& operator/=(const S& s) {

		minX /= s;
		maxX /= s;
		minY /= s;
		maxY /= s;

		return *this;
	}

	template <typename S>
	rect<T>& operator*=(const point<S>& p) {

		minX *= p.x;
		maxX *= p.x;
		minY *= p.y;
		maxY *= p.y;

		return *this;
	}

	template <typename S>
	rect<T>& operator/=(const point<S>& p) {

		minX /= p.x;
		maxX /= p.x;
		minY /= p.y;
		maxY /= p.y;

		return *this;
	}

	template <typename S>
	bool operator==(const rect<S>& other) const {

		return minX == other.minX &&
		       minY == other.minY &&
		       maxX == other.maxX &&
		       maxY == other.maxY;
	}

	template <typename S>
	bool operator!=(const rect<S>& other) const {

		return !(*this == other);
	}
};

} // namespace util

template <typename T, typename S>
util::rect<T> operator+(const util::rect<T>& p, const util::point<S>& o) {

	util::rect<T> result(p);

	return result += o;
}

template <typename T, typename S>
util::rect<T> operator-(const util::rect<T>& p, const util::point<S>& o) {

	util::rect<T> result(p);

	return result -= o;
}

template <typename T, typename S>
util::rect<T> operator*(const util::rect<T>& p, const S& s) {

	util::rect<T> result(p);

	return result *= s;
}

template <typename T, typename S>
util::rect<T> operator*(const S& s, const util::rect<T>& p) {

	util::rect<T> result(p);

	return result *= s;
}

template <typename T, typename S>
util::rect<T> operator/(const util::rect<T>& p, const S& s) {

	util::rect<T> result(p);

	return result /= s;
}

template <typename T>
std::ostream& operator<<(std::ostream& os, const util::rect<T>& rect) {

	os << "[" << rect.minX << ", " << rect.minY
	   << ", " << rect.maxX << ", " << rect.maxY << "]";

	return os;
}

#endif // UTIL_RECT_H__

<|endoftext|>


<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, ELM Library Project
// 3-clause BSD License
//
//M*/
#include "elm/layers/layergraph_impl.h"

#include <boost/graph/topological_sort.hpp>

//#include "elm/core/debug_utils.h"
#include "elm/core/boost/ptree_utils_inl.h"
#include "elm/core/exception.h"
#include "elm/core/stl/stl_inl.h"

using namespace std;
using namespace boost;
using namespace elm;

LayerGraph_Impl::LayerGraph_Impl() {
}

void LayerGraph_Impl::Add(const VtxName &name,
                     const LayerShared &layer_ptr,
                     const LayerConfig &cfg,
                     const LayerIONames &io) {

    VtxColor color = genVtxColor(name, cfg, io);

    VtxDescriptor vtx = add_vertex(color, g_);

    // Property accessors
    property_map<GraphLayerType, vertex_color_t>::type
            vtx_color_lut = get(vertex_color, g_);
    vtx_color_lut[vtx] = color;

    property_map<GraphLayerType, vertex_name_t>::type
            vtx_name_lut = get(vertex_name, g_);
    vtx_name_lut[vtx] = name;

    property_map<GraphLayerType, vertex_index1_t>::type
            vtx_layer_lut = get(vertex_index1, g_);

    LayerVertex layer_vtx;
    layer_vtx.Set(cfg, io, layer_ptr);
    vtx_layer_lut[vtx] = layer_vtx;

    // inputs
    VecS inputs = elm::Values(io.InputMap());
    VecS outputs = elm::Values(io.OutputMap());

    for (auto const& input : inputs) {

        GraphLayerTraits::vertex_iterator v, end;
        for(tie(v, end) = vertices(g_); v != end; ++v) {

            LayerIONames vtx_io = vtx_layer_lut[*v].io;
            VecS vtx_outs = elm::Values(vtx_io.OutputMap());

            VecS::const_iterator itr;
            itr = std::find(vtx_outs.begin(), vtx_outs.end(), input);

            if(itr != vtx_outs.end()) {

                EdgeProp edge_prop = *itr;

                add_edge(*v, vtx, edge_prop, g_);
            }
        } // vertices
    } // inputs

    for (auto const& output : outputs) {

        GraphLayerTraits::vertex_iterator v, end;
        for(tie(v, end) = vertices(g_); v != end; ++v) {

            LayerIONames vtx_io = vtx_layer_lut[*v].io;
            VecS vtx_ins = elm::Values(vtx_io.InputMap());

            VecS::const_iterator itr;
            itr = std::find(vtx_ins.begin(), vtx_ins.end(), output);

            if(itr != vtx_ins.end()) {

                EdgeProp edge_prop = *itr;
                add_edge(vtx, *v, edge_prop, g_);
            }
        } // vertices
    } // outputs
}

void LayerGraph_Impl::ClearActive() {

    property_map<GraphLayerType, vertex_index1_t>::type
            vtx_layer_lut = get(vertex_index1, g_);

    GraphLayerTraits::vertex_iterator v, end;
    for(tie(v, end) = vertices(g_); v != end; ++v) {

        vtx_layer_lut[*v].is_active = false;
    }
}

void LayerGraph_Impl::findParents(const VtxDescriptor &child,
                                  std::vector<VtxDescriptor> &parents) const {

    GraphLayerType::inv_adjacency_iterator itr, end;
    for(tie(itr, end) = inv_adjacent_vertices(child, g_);
        itr != end;
        ++itr) {

        VtxDescriptor parent = *itr;
        parents.push_back(parent);
        findParents(parent, parents);
    }
}

void LayerGraph_Impl::Sequence(std::vector<LayerShared> &layer_seq) {

    std::vector<VtxDescriptor > q;
    Toposort(q);

    property_map<GraphLayerType, vertex_index1_t>::type
            vtx_layer_lut = get(vertex_index1, g_);

    for (std::vector<VtxDescriptor >::reverse_iterator itr=q.rbegin();
         itr != q.rend();
         ++itr ) {

        if(vtx_layer_lut[*itr].is_active) {

            layer_seq.push_back(vtx_layer_lut[*itr].ptr);
        }
    }
}

void LayerGraph_Impl::Configure() {

    property_map<GraphLayerType, vertex_index1_t>::type
            vtx_layer_lut = get(vertex_index1, g_);

    GraphLayerTraits::vertex_iterator v, end;
    for(tie(v, end) = vertices(g_); v != end; ++v) {

        if(vtx_layer_lut[*v].is_active) {

            vtx_layer_lut[*v].Configure();
        }
    }
}

void LayerGraph_Impl::AddOutput(const std::string &name) {

    property_map<GraphLayerType, vertex_index1_t>::type
            vtx_layer_lut = get(vertex_index1, g_);

    bool found_name = false;
    GraphLayerTraits::vertex_iterator v, end;
    VtxDescriptor vtx_cur;
    for(tie(v, end) = vertices(g_); v != end && !found_name; ++v) {

        VecS vtx_outs = elm::Values(vtx_layer_lut[*v].io.OutputMap());

        VecS::const_iterator itr;
        itr = std::find(vtx_outs.begin(), vtx_outs.end(), name);

        if(itr != vtx_outs.end()) {

            found_name = true;
            vtx_cur = *v;
        }
    } // vertices

    if(!found_name) {

        stringstream s;
        s << "Output (" << name << ") not supported.";
        ELM_THROW_KEY_ERROR(s.str());
    }
    else {

//        property_map<GraphLayerType, vertex_name_t>::type
//                vtx_name_lut = get(vertex_name, g_);
//        std::cout<<"current: "<<vtx_name_lut[vtx_cur]<<std::endl;

        vtx_layer_lut[vtx_cur].is_active = true;

        std::vector<VtxDescriptor> parents;
        this->findParents(vtx_cur, parents);
        for(size_t i=0; i<parents.size(); i++) {

            vtx_layer_lut[parents[i]].is_active = true;
        }

//        std::cout<<"parents:";
//        for(size_t i=0; i<parents.size(); i++) {

//            std::cout<<vtx_name_lut[parents[i]]<<",";
//        }
//        std::cout<<std::endl;
    }
}

SetS LayerGraph_Impl::Outputs() const {

    SetS outputs;

    GraphLayerTraits::vertex_iterator v, end;
    for(tie(v, end) = vertices(g_); v != end; ++v) {

        const LayerVertex &tmp = boost::get(vertex_index1, g_, *v);
        if(tmp.is_active) {

            VecS vtx_outs = elm::Values(tmp.io.OutputMap());
            outputs.insert(vtx_outs.begin(), vtx_outs.end());
        }
    }

    return outputs;
}

SetS LayerGraph_Impl::Inputs() const {

    SetS inputs;

    GraphLayerTraits::vertex_iterator v, end;
    for(tie(v, end) = vertices(g_); v != end; ++v) {

        const LayerVertex &tmp = boost::get(vertex_index1, g_, *v);
        if(tmp.is_active) {

            VecS vtx_ins = elm::Values(tmp.io.InputMap());
            inputs.insert(vtx_ins.begin(), vtx_ins.end());
        }
    }

    // remove outputs of other layers, only keep primary inputs

    edge_iter e, e_end;
    for (tie(e, e_end) = edges(g_); e != e_end; ++e) {

        const EdgeName &tmp = boost::get(edge_name, g_, *e);

        SetS::iterator itr = inputs.find(tmp);
        if(itr != inputs.end()) {

            inputs.erase(itr);
        }
    }

    return inputs;
}

void LayerGraph_Impl::Toposort(std::vector<VtxDescriptor > &q) {

    q.clear();
    topological_sort(g_, std::back_inserter(q));
}

VtxColor LayerGraph_Impl::genVtxColor(const VtxName &name,
                     const LayerConfig &cfg,
                     const LayerIONames &io) const {

    VtxColor color = name;

    stringstream s;
    PrintXML(cfg.Params(), s);

    color += s.str();

    // inputs
    MapSS io_map = io.InputMap();
    color += elm::to_string(elm::Keys(io_map));
    color += elm::to_string(elm::Values(io_map));

    // outputs
    io_map = io.OutputMap();
    color += elm::to_string(elm::Keys(io_map));
    color += elm::to_string(elm::Values(io_map));

    return color;
}

//void LayerGraph::print() {

//    cout<<"Vertices:"<<endl;

//    cout<<num_vertices(g_)<<endl;

//    property_map<GraphLayerType, vertex_name_t>::type
//            vtx_name_lut = get(vertex_name, g_);

//    GraphLayerTraits::vertex_iterator v, end;
//    for(tie(v, end) = vertices(g_); v != end; ++v) {

//        VtxName key = vtx_name_lut[*v];
//        ELM_COUT_VAR(key);
//    }

//    cout<<"Edges:"<<endl;

//    property_map<GraphLayerType, edge_name_t >::type
//        edge_name_lut = get(edge_name, g_);
//    edge_iter ei, ei_end;
//    for (tie(ei, ei_end) = edges(g_); ei != ei_end; ++ei) {

//        EdgeName edge_name = edge_name_lut[*ei];

//        VtxDescriptor src = source(*ei, g_);
//        VtxName src_name = vtx_name_lut[src];

//        VtxDescriptor dst = target(*ei, g_);
//        VtxName dst_name = vtx_name_lut[dst];

//        cout<<src_name<<"->"<<edge_name<<"->"<<dst_name<<endl;
//    }

//    std::cout<<"Toposort..."<<std::endl;
//    std::vector<VtxDescriptor > sort_q;
//    Toposort(sort_q);

//    for(size_t i=0; i<sort_q.size(); ++i) {

//        std::cout<<vtx_name_lut[sort_q[i]]<<std::endl;
//    }
//}
<commit_msg>fix parameter indentation<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, ELM Library Project
// 3-clause BSD License
//
//M*/
#include "elm/layers/layergraph_impl.h"

#include <boost/graph/topological_sort.hpp>

//#include "elm/core/debug_utils.h"
#include "elm/core/boost/ptree_utils_inl.h"
#include "elm/core/exception.h"
#include "elm/core/stl/stl_inl.h"

using namespace std;
using namespace boost;
using namespace elm;

LayerGraph_Impl::LayerGraph_Impl() {
}

void LayerGraph_Impl::Add(const VtxName &name,
                          const LayerShared &layer_ptr,
                          const LayerConfig &cfg,
                          const LayerIONames &io) {

    VtxColor color = genVtxColor(name, cfg, io);

    VtxDescriptor vtx = add_vertex(color, g_);

    // Property accessors
    property_map<GraphLayerType, vertex_color_t>::type
            vtx_color_lut = get(vertex_color, g_);
    vtx_color_lut[vtx] = color;

    property_map<GraphLayerType, vertex_name_t>::type
            vtx_name_lut = get(vertex_name, g_);
    vtx_name_lut[vtx] = name;

    property_map<GraphLayerType, vertex_index1_t>::type
            vtx_layer_lut = get(vertex_index1, g_);

    LayerVertex layer_vtx;
    layer_vtx.Set(cfg, io, layer_ptr);
    vtx_layer_lut[vtx] = layer_vtx;

    // inputs
    VecS inputs = elm::Values(io.InputMap());
    VecS outputs = elm::Values(io.OutputMap());

    for (auto const& input : inputs) {

        GraphLayerTraits::vertex_iterator v, end;
        for(tie(v, end) = vertices(g_); v != end; ++v) {

            LayerIONames vtx_io = vtx_layer_lut[*v].io;
            VecS vtx_outs = elm::Values(vtx_io.OutputMap());

            VecS::const_iterator itr;
            itr = std::find(vtx_outs.begin(), vtx_outs.end(), input);

            if(itr != vtx_outs.end()) {

                EdgeProp edge_prop = *itr;

                add_edge(*v, vtx, edge_prop, g_);
            }
        } // vertices
    } // inputs

    for (auto const& output : outputs) {

        GraphLayerTraits::vertex_iterator v, end;
        for(tie(v, end) = vertices(g_); v != end; ++v) {

            LayerIONames vtx_io = vtx_layer_lut[*v].io;
            VecS vtx_ins = elm::Values(vtx_io.InputMap());

            VecS::const_iterator itr;
            itr = std::find(vtx_ins.begin(), vtx_ins.end(), output);

            if(itr != vtx_ins.end()) {

                EdgeProp edge_prop = *itr;
                add_edge(vtx, *v, edge_prop, g_);
            }
        } // vertices
    } // outputs
}

void LayerGraph_Impl::ClearActive() {

    property_map<GraphLayerType, vertex_index1_t>::type
            vtx_layer_lut = get(vertex_index1, g_);

    GraphLayerTraits::vertex_iterator v, end;
    for(tie(v, end) = vertices(g_); v != end; ++v) {

        vtx_layer_lut[*v].is_active = false;
    }
}

void LayerGraph_Impl::findParents(const VtxDescriptor &child,
                                  std::vector<VtxDescriptor> &parents) const {

    GraphLayerType::inv_adjacency_iterator itr, end;
    for(tie(itr, end) = inv_adjacent_vertices(child, g_);
        itr != end;
        ++itr) {

        VtxDescriptor parent = *itr;
        parents.push_back(parent);
        findParents(parent, parents);
    }
}

void LayerGraph_Impl::Sequence(std::vector<LayerShared> &layer_seq) {

    std::vector<VtxDescriptor > q;
    Toposort(q);

    property_map<GraphLayerType, vertex_index1_t>::type
            vtx_layer_lut = get(vertex_index1, g_);

    for (std::vector<VtxDescriptor >::reverse_iterator itr=q.rbegin();
         itr != q.rend();
         ++itr ) {

        if(vtx_layer_lut[*itr].is_active) {

            layer_seq.push_back(vtx_layer_lut[*itr].ptr);
        }
    }
}

void LayerGraph_Impl::Configure() {

    property_map<GraphLayerType, vertex_index1_t>::type
            vtx_layer_lut = get(vertex_index1, g_);

    GraphLayerTraits::vertex_iterator v, end;
    for(tie(v, end) = vertices(g_); v != end; ++v) {

        if(vtx_layer_lut[*v].is_active) {

            vtx_layer_lut[*v].Configure();
        }
    }
}

void LayerGraph_Impl::AddOutput(const std::string &name) {

    property_map<GraphLayerType, vertex_index1_t>::type
            vtx_layer_lut = get(vertex_index1, g_);

    bool found_name = false;
    GraphLayerTraits::vertex_iterator v, end;
    VtxDescriptor vtx_cur;
    for(tie(v, end) = vertices(g_); v != end && !found_name; ++v) {

        VecS vtx_outs = elm::Values(vtx_layer_lut[*v].io.OutputMap());

        VecS::const_iterator itr;
        itr = std::find(vtx_outs.begin(), vtx_outs.end(), name);

        if(itr != vtx_outs.end()) {

            found_name = true;
            vtx_cur = *v;
        }
    } // vertices

    if(!found_name) {

        stringstream s;
        s << "Output (" << name << ") not supported.";
        ELM_THROW_KEY_ERROR(s.str());
    }
    else {

//        property_map<GraphLayerType, vertex_name_t>::type
//                vtx_name_lut = get(vertex_name, g_);
//        std::cout<<"current: "<<vtx_name_lut[vtx_cur]<<std::endl;

        vtx_layer_lut[vtx_cur].is_active = true;

        std::vector<VtxDescriptor> parents;
        this->findParents(vtx_cur, parents);
        for(size_t i=0; i<parents.size(); i++) {

            vtx_layer_lut[parents[i]].is_active = true;
        }

//        std::cout<<"parents:";
//        for(size_t i=0; i<parents.size(); i++) {

//            std::cout<<vtx_name_lut[parents[i]]<<",";
//        }
//        std::cout<<std::endl;
    }
}

SetS LayerGraph_Impl::Outputs() const {

    SetS outputs;

    GraphLayerTraits::vertex_iterator v, end;
    for(tie(v, end) = vertices(g_); v != end; ++v) {

        const LayerVertex &tmp = boost::get(vertex_index1, g_, *v);
        if(tmp.is_active) {

            VecS vtx_outs = elm::Values(tmp.io.OutputMap());
            outputs.insert(vtx_outs.begin(), vtx_outs.end());
        }
    }

    return outputs;
}

SetS LayerGraph_Impl::Inputs() const {

    SetS inputs;

    GraphLayerTraits::vertex_iterator v, end;
    for(tie(v, end) = vertices(g_); v != end; ++v) {

        const LayerVertex &tmp = boost::get(vertex_index1, g_, *v);
        if(tmp.is_active) {

            VecS vtx_ins = elm::Values(tmp.io.InputMap());
            inputs.insert(vtx_ins.begin(), vtx_ins.end());
        }
    }

    // remove outputs of other layers, only keep primary inputs

    edge_iter e, e_end;
    for (tie(e, e_end) = edges(g_); e != e_end; ++e) {

        const EdgeName &tmp = boost::get(edge_name, g_, *e);

        SetS::iterator itr = inputs.find(tmp);
        if(itr != inputs.end()) {

            inputs.erase(itr);
        }
    }

    return inputs;
}

void LayerGraph_Impl::Toposort(std::vector<VtxDescriptor > &q) {

    q.clear();
    topological_sort(g_, std::back_inserter(q));
}

VtxColor LayerGraph_Impl::genVtxColor(const VtxName &name,
                     const LayerConfig &cfg,
                     const LayerIONames &io) const {

    VtxColor color = name;

    stringstream s;
    PrintXML(cfg.Params(), s);

    color += s.str();

    // inputs
    MapSS io_map = io.InputMap();
    color += elm::to_string(elm::Keys(io_map));
    color += elm::to_string(elm::Values(io_map));

    // outputs
    io_map = io.OutputMap();
    color += elm::to_string(elm::Keys(io_map));
    color += elm::to_string(elm::Values(io_map));

    return color;
}

//void LayerGraph::print() {

//    cout<<"Vertices:"<<endl;

//    cout<<num_vertices(g_)<<endl;

//    property_map<GraphLayerType, vertex_name_t>::type
//            vtx_name_lut = get(vertex_name, g_);

//    GraphLayerTraits::vertex_iterator v, end;
//    for(tie(v, end) = vertices(g_); v != end; ++v) {

//        VtxName key = vtx_name_lut[*v];
//        ELM_COUT_VAR(key);
//    }

//    cout<<"Edges:"<<endl;

//    property_map<GraphLayerType, edge_name_t >::type
//        edge_name_lut = get(edge_name, g_);
//    edge_iter ei, ei_end;
//    for (tie(ei, ei_end) = edges(g_); ei != ei_end; ++ei) {

//        EdgeName edge_name = edge_name_lut[*ei];

//        VtxDescriptor src = source(*ei, g_);
//        VtxName src_name = vtx_name_lut[src];

//        VtxDescriptor dst = target(*ei, g_);
//        VtxName dst_name = vtx_name_lut[dst];

//        cout<<src_name<<"->"<<edge_name<<"->"<<dst_name<<endl;
//    }

//    std::cout<<"Toposort..."<<std::endl;
//    std::vector<VtxDescriptor > sort_q;
//    Toposort(sort_q);

//    for(size_t i=0; i<sort_q.size(); ++i) {

//        std::cout<<vtx_name_lut[sort_q[i]]<<std::endl;
//    }
//}
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/hmi/utils/hmi_status_helper.h"

#include "gflags/gflags.h"
#include "modules/common/util/file.h"
#include "modules/common/util/string_util.h"
#include "modules/hmi/proto/config.pb.h"
#include "modules/hmi/utils/restful_client.h"

DEFINE_string(hmi_config_file, "modules/hmi/conf/config.pb.txt",
              "HMI config file, which should be text-formatted config proto.");

namespace apollo {
namespace hmi {
namespace {

RestfulClient* InitRestfulClient() {
  Config conf_pb;
  if (!apollo::common::util::GetProtoFromASCIIFile(FLAGS_hmi_config_file,
                                                   &conf_pb)) {
    return nullptr;
  }
  const auto& server = conf_pb.server();
  const auto url = apollo::common::util::StrCat(
      server.https().enabled() ? "https://" : "http://",
      "127.0.0.1:", server.port(), "/runtime_status");
  return new RestfulClient(url);
}

void ReportRuntimeStatus(const RuntimeStatus& runtime_status) {
  static auto* client = InitRestfulClient();
  if (client) {
    client->Post(runtime_status);
  } else {
    AERROR << "Cannot connect to HMI server.";
  }
}

}  // namespace

void HMIStatusHelper::ReportHardwareStatus(
    const std::vector<HardwareStatus> &hardware_status) {
  RuntimeStatus runtime_status;
  *runtime_status.mutable_hardware() = {hardware_status.begin(),
                                        hardware_status.end()};
  ReportRuntimeStatus(runtime_status);
}

void HMIStatusHelper::ReportModuleStatus(const ModuleStatus &module_status) {
  RuntimeStatus runtime_status;
  *runtime_status.add_modules() = module_status;
  ReportRuntimeStatus(runtime_status);
}

}  // namespace hmi
}  // namespace apollo
<commit_msg>HMI: Mute HMI warning before retiring.<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/hmi/utils/hmi_status_helper.h"

#include "gflags/gflags.h"
#include "modules/common/util/file.h"
#include "modules/common/util/string_util.h"
#include "modules/hmi/proto/config.pb.h"
#include "modules/hmi/utils/restful_client.h"

DEFINE_string(hmi_config_file, "modules/hmi/conf/config.pb.txt",
              "HMI config file, which should be text-formatted config proto.");

namespace apollo {
namespace hmi {
namespace {

RestfulClient* InitRestfulClient() {
  Config conf_pb;
  if (!apollo::common::util::GetProtoFromASCIIFile(FLAGS_hmi_config_file,
                                                   &conf_pb)) {
    return nullptr;
  }
  const auto& server = conf_pb.server();
  const auto url = apollo::common::util::StrCat(
      server.https().enabled() ? "https://" : "http://",
      "127.0.0.1:", server.port(), "/runtime_status");
  return new RestfulClient(url);
}

void ReportRuntimeStatus(const RuntimeStatus& runtime_status) {
  static auto* client = InitRestfulClient();
  if (client) {
    client->Post(runtime_status);
  } else {
    ADEBUG << "Cannot connect to HMI server.";
  }
}

}  // namespace

void HMIStatusHelper::ReportHardwareStatus(
    const std::vector<HardwareStatus> &hardware_status) {
  RuntimeStatus runtime_status;
  *runtime_status.mutable_hardware() = {hardware_status.begin(),
                                        hardware_status.end()};
  ReportRuntimeStatus(runtime_status);
}

void HMIStatusHelper::ReportModuleStatus(const ModuleStatus &module_status) {
  RuntimeStatus runtime_status;
  *runtime_status.add_modules() = module_status;
  ReportRuntimeStatus(runtime_status);
}

}  // namespace hmi
}  // namespace apollo
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

/**
 * @file speed_limit.cc
 **/

#include "modules/planning/common/speed_limit.h"

#include <algorithm>

#include "modules/common/util/util.h"
#include "modules/planning/common/planning_util.h"

namespace apollo {
namespace planning {

using common::SpeedPoint;

void SpeedLimit::add_speed_limit(const SpeedPoint& speed_point) {
  speed_points_.push_back(speed_point);
}

void SpeedLimit::add_speed_limit(const double s, const double t, const double v,
                                 const double a, const double da) {
  speed_points_.push_back(common::util::MakeSpeedPoint(s, t, v, a, da));
}

const std::vector<SpeedPoint>& SpeedLimit::speed_points() const {
  return speed_points_;
}

double SpeedLimit::get_speed_limit_by_s(const double s) const {
  double ref_s = s;
  if (speed_points_.size() == 0) {
    return 0.0;
  }

  if (speed_points_.size() == 1) {
    return speed_points_.front().v();
  }

  if (ref_s > speed_points_.back().s()) {
    return speed_points_.back().v();
  }

  if (ref_s < speed_points_.front().s()) {
    return speed_points_.front().v();
  }

  auto func = [](const SpeedPoint& sp, const double s) { return sp.s() < s; };

  auto it_lower =
      std::lower_bound(speed_points_.begin(), speed_points_.end(), s, func);
  if (it_lower == speed_points_.begin()) {
    return speed_points_.front().v();
  }

  double weight = 0.0;
  double range = (*it_lower).s() - (*(it_lower - 1)).s();
  if (range > 0) {
    weight = (s - (*(it_lower - 1)).s()) / range;
  }
  return util::interpolate(*(it_lower - 1), *it_lower, weight).v();
}

double SpeedLimit::get_speed_limit_by_t(const double t) const {
  double ref_t = t;
  if (speed_points_.size() == 0) {
    return 0.0;
  }

  if (speed_points_.size() == 1) {
    return speed_points_.front().v();
  }

  if (ref_t > speed_points_.back().t()) {
    return speed_points_.back().v();
  }

  if (ref_t < speed_points_.front().t()) {
    return speed_points_.front().v();
  }

  auto func = [](const SpeedPoint& sp, const double t) { return sp.t() < t; };

  auto it_lower =
      std::lower_bound(speed_points_.begin(), speed_points_.end(), t, func);
  if (it_lower == speed_points_.begin()) {
    return speed_points_.front().v();
  }

  double weight = 0.0;
  double range = (*it_lower).t() - (*(it_lower - 1)).t();
  if (range > 0) {
    weight = (t - (*(it_lower - 1)).t()) / range;
  }
  return util::interpolate(*(it_lower - 1), *it_lower, weight).v();
}

}  // namespace planning
}  // namespace apollo
<commit_msg>planning: improved the implementation of get_speed_limit_by_t in class SpeedLimit<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

/**
 * @file speed_limit.cc
 **/

#include "modules/planning/common/speed_limit.h"

#include <algorithm>

#include "modules/common/math/linear_interpolation.h"
#include "modules/common/util/util.h"
#include "modules/planning/common/planning_util.h"

namespace apollo {
namespace planning {

using common::SpeedPoint;

void SpeedLimit::add_speed_limit(const SpeedPoint& speed_point) {
  speed_points_.push_back(speed_point);
}

void SpeedLimit::add_speed_limit(const double s, const double t, const double v,
                                 const double a, const double da) {
  speed_points_.push_back(common::util::MakeSpeedPoint(s, t, v, a, da));
}

const std::vector<SpeedPoint>& SpeedLimit::speed_points() const {
  return speed_points_;
}

double SpeedLimit::get_speed_limit_by_s(const double s) const {
  double ref_s = s;
  if (speed_points_.size() == 0) {
    return 0.0;
  }

  if (speed_points_.size() == 1) {
    return speed_points_.front().v();
  }

  if (ref_s > speed_points_.back().s()) {
    return speed_points_.back().v();
  }

  if (ref_s < speed_points_.front().s()) {
    return speed_points_.front().v();
  }

  auto func = [](const SpeedPoint& sp, const double s) { return sp.s() < s; };

  auto it_lower =
      std::lower_bound(speed_points_.begin(), speed_points_.end(), s, func);
  if (it_lower == speed_points_.begin()) {
    return speed_points_.front().v();
  }

  double weight = 0.0;
  double range = (*it_lower).s() - (*(it_lower - 1)).s();
  if (range > 0) {
    weight = (s - (*(it_lower - 1)).s()) / range;
  }
  return util::interpolate(*(it_lower - 1), *it_lower, weight).v();
}

double SpeedLimit::get_speed_limit_by_t(const double t) const {
  if (speed_points_.size() == 0) {
    return 0.0;
  }

  if (speed_points_.size() == 1) {
    return speed_points_.front().v();
  }

  if (t > speed_points_.back().t()) {
    return speed_points_.back().v();
  }

  if (t < speed_points_.front().t()) {
    return speed_points_.front().v();
  }

  auto func = [](const SpeedPoint& sp, const double t) { return sp.t() < t; };

  auto it_lower =
      std::lower_bound(speed_points_.begin(), speed_points_.end(), t, func);
  if (it_lower == speed_points_.begin()) {
    return speed_points_.front().v();
  } else if (it_lower == speed_points_.end()) {
    return speed_points_.back().v();
  }

  double v0 = (it_lower - 1)->v();
  double t0 = (it_lower - 1)->t();

  double v1 = it_lower->v();
  double t1 = it_lower->t();

  return common::math::lerp(v0, t0, v1, t1, t);
}

}  // namespace planning
}  // namespace apollo
<|endoftext|>


<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2017 Nathan Osman
 *
 * 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 <qmdnsengine/dns.h>
#include <qmdnsengine/hostname.h>
#include <qmdnsengine/provider.h>
#include <qmdnsengine/server.h>

#include "provider_p.h"

using namespace QMdnsEngine;

ProviderPrivate::ProviderPrivate(QObject *parent, Server *server, Hostname *hostname)
    : QObject(parent),
      server(server),
      hostname(hostname),
      responder(server),
      initialized(false)
{
    connect(hostname, &Hostname::hostnameChanged, this, &ProviderPrivate::onHostnameChanged);

    browsePtrRecord.setType(PTR);
    ptrRecord.setType(PTR);
    srvRecord.setType(SRV);
    txtRecord.setType(TXT);
}

void ProviderPrivate::updateRecords()
{
    if (!hostname->isRegistered()) {
        return;
    }

    if (initialized) {
        responder.removeRecord(browsePtrRecord);
        responder.removeRecord(ptrRecord);
        responder.removeRecord(srvRecord);
        responder.removeRecord(txtRecord);
    }

    QByteArray fqName = service.name() + "." + service.type();

    browsePtrRecord.setName(service.type());
    browsePtrRecord.setTarget(fqName);

    ptrRecord.setName(service.type());
    ptrRecord.setTarget(fqName);

    srvRecord.setName(fqName);
    srvRecord.setPort(service.port());

    txtRecord.setName(fqName);
    txtRecord.setAttributes(service.attributes());

    responder.addRecord(browsePtrRecord);
    responder.addRecord(ptrRecord);
    responder.addRecord(srvRecord);
    responder.addRecord(txtRecord);

    initialized = true;
}

void ProviderPrivate::onHostnameChanged(const QByteArray &hostname)
{
    updateRecords();
}

Provider::Provider(Server *server, Hostname *hostname, QObject *parent)
    : QObject(parent),
      d(new ProviderPrivate(this, server, hostname))
{
}

void Provider::update(const Service &service)
{
    d->service = service;
    d->updateRecords();
}
<commit_msg>Fix records in Responder.<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2017 Nathan Osman
 *
 * 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 <qmdnsengine/dns.h>
#include <qmdnsengine/hostname.h>
#include <qmdnsengine/mdns.h>
#include <qmdnsengine/provider.h>
#include <qmdnsengine/server.h>

#include "provider_p.h"

using namespace QMdnsEngine;

ProviderPrivate::ProviderPrivate(QObject *parent, Server *server, Hostname *hostname)
    : QObject(parent),
      server(server),
      hostname(hostname),
      responder(server),
      initialized(false)
{
    connect(hostname, &Hostname::hostnameChanged, this, &ProviderPrivate::onHostnameChanged);

    browsePtrRecord.setType(PTR);
    ptrRecord.setType(PTR);
    srvRecord.setType(SRV);
    txtRecord.setType(TXT);
}

void ProviderPrivate::updateRecords()
{
    if (!hostname->isRegistered()) {
        return;
    }

    if (initialized) {
        responder.removeRecord(browsePtrRecord);
        responder.removeRecord(ptrRecord);
        responder.removeRecord(srvRecord);
        responder.removeRecord(txtRecord);
    }

    QByteArray fqName = service.name() + "." + service.type();

    browsePtrRecord.setName(MdnsBrowseType);
    browsePtrRecord.setTarget(service.type());

    ptrRecord.setName(service.type());
    ptrRecord.setTarget(fqName);

    srvRecord.setName(fqName);
    srvRecord.setPort(service.port());
    srvRecord.setTarget(hostname->hostname());

    txtRecord.setName(fqName);
    txtRecord.setAttributes(service.attributes());

    responder.addRecord(browsePtrRecord, false);
    responder.addRecord(ptrRecord, false);
    responder.addRecord(srvRecord, true);
    responder.addRecord(txtRecord, true);

    initialized = true;
}

void ProviderPrivate::onHostnameChanged(const QByteArray &hostname)
{
    updateRecords();
}

Provider::Provider(Server *server, Hostname *hostname, QObject *parent)
    : QObject(parent),
      d(new ProviderPrivate(this, server, hostname))
{
}

void Provider::update(const Service &service)
{
    d->service = service;
    d->updateRecords();
}
<|endoftext|>


<commit_before><commit_msg>Added ThreadID sync to src/WorkerThreadPool.cpp<commit_after><|endoftext|>


<commit_before>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/python.hpp>
#include <libtorrent/torrent_info.hpp>
#include "libtorrent/intrusive_ptr_base.hpp"

using namespace boost::python;
using namespace libtorrent;

namespace
{

    std::vector<announce_entry>::const_iterator begin_trackers(torrent_info& i)
    {
        return i.trackers().begin();
    }

    std::vector<announce_entry>::const_iterator end_trackers(torrent_info& i)
    {
        return i.trackers().end();
    }

    void add_node(torrent_info& ti, char const* hostname, int port)
    {
        ti.add_node(std::make_pair(hostname, port));
    }

    list nodes(torrent_info const& ti)
    {
        list result;

        typedef std::vector<std::pair<std::string, int> > list_type;

        for (list_type::const_iterator i = ti.nodes().begin(); i != ti.nodes().end(); ++i)
        {
            result.append(make_tuple(i->first, i->second));
        }

        return result;
    }

    file_storage::iterator begin_files(torrent_info& i)
    {
        return i.begin_files();
    }

    file_storage::iterator end_files(torrent_info& i)
    {
        return i.end_files();
    }

    //list files(torrent_info const& ti, bool storage) {
    list files(torrent_info const& ti, bool storage) {
        list result;

        typedef torrent_info::file_iterator iter;

        for (iter i = ti.begin_files(); i != ti.end_files(); ++i)
            result.append(ti.files().at(i));

        return result;
    }

    std::string hash_for_piece(torrent_info const& ti, int i)
    {
        return ti.hash_for_piece(i).to_string();
    }

    std::string metadata(torrent_info const& ti) {
        std::string result(ti.metadata().get(), ti.metadata_size());
        return result;
    }

    torrent_info construct0(std::string path) {
        return torrent_info(path);
    }

    list map_block(torrent_info& ti, int piece, size_type offset, int size)
    {
       std::vector<file_slice> p = ti.map_block(piece, offset, size);
       list result;

       for (std::vector<file_slice>::iterator i(p.begin()), e(p.end()); i != e; ++i)
          result.append(*i);

       return result;
    }

    bool get_tier(announce_entry const& ae) { return ae.tier; }
    void set_tier(announce_entry& ae, bool v) { ae.tier = v; }
    bool get_fail_limit(announce_entry const& ae) { return ae.fail_limit; }
    void set_fail_limit(announce_entry& ae, int l) { ae.fail_limit = l; }
    bool get_fails(announce_entry const& ae) { return ae.fails; }
    bool get_source(announce_entry const& ae) { return ae.source; }
    bool get_verified(announce_entry const& ae) { return ae.verified; }
    bool get_updating(announce_entry const& ae) { return ae.updating; }
    bool get_start_sent(announce_entry const& ae) { return ae.start_sent; }
    bool get_complete_sent(announce_entry const& ae) { return ae.complete_sent; }
    bool get_send_stats(announce_entry const& ae) { return ae.send_stats; }

    size_type get_size(file_entry const& fe) { return fe.size; }
    size_type get_offset(file_entry const& fe) { return fe.offset; }
    bool get_pad_file(file_entry const& fe) { return fe.pad_file; }
    bool get_executable_attribute(file_entry const& fe) { return fe.executable_attribute; }
    bool get_hidden_attribute(file_entry const& fe) { return fe.hidden_attribute; }
    bool get_symlink_attribute(file_entry const& fe) { return fe.symlink_attribute; }

} // namespace unnamed

void bind_torrent_info()
{
    return_value_policy<copy_const_reference> copy;

    void (torrent_info::*rename_file0)(int, std::string const&) = &torrent_info::rename_file;
#if TORRENT_USE_WSTRING
    void (torrent_info::*rename_file1)(int, std::wstring const&) = &torrent_info::rename_file;
#endif

    class_<file_slice>("file_slice")
        .def_readwrite("file_index", &file_slice::file_index)
        .def_readwrite("offset", &file_slice::offset)
        .def_readwrite("size", &file_slice::size)
        ;

    class_<torrent_info, boost::intrusive_ptr<torrent_info> >("torrent_info", no_init)
#ifndef TORRENT_NO_DEPRECATE
        .def(init<entry const&>(arg("e")))
#endif
        .def(init<sha1_hash const&, int>((arg("info_hash"), arg("flags") = 0)))
        .def(init<char const*, int, int>((arg("buffer"), arg("length"), arg("flags") = 0)))
        .def(init<std::string, int>((arg("file"), arg("flags") = 0)))
        .def(init<torrent_info const&, int>((arg("ti"), arg("flags") = 0)))
#if TORRENT_USE_WSTRING
        .def(init<std::wstring, int>((arg("file"), arg("flags") = 0)))
#endif

        .def("add_tracker", &torrent_info::add_tracker, arg("url"))
        .def("add_url_seed", &torrent_info::add_url_seed)

        .def("name", &torrent_info::name, copy)
        .def("comment", &torrent_info::comment, copy)
        .def("creator", &torrent_info::creator, copy)
        .def("total_size", &torrent_info::total_size)
        .def("piece_length", &torrent_info::piece_length)
        .def("num_pieces", &torrent_info::num_pieces)
#ifndef TORRENT_NO_DEPRECATE
        .def("info_hash", &torrent_info::info_hash, copy)
#endif
        .def("hash_for_piece", &hash_for_piece)
        .def("piece_size", &torrent_info::piece_size)

        .def("num_files", &torrent_info::num_files, (arg("storage")=false))
        .def("file_at", &torrent_info::file_at)
        .def("file_at_offset", &torrent_info::file_at_offset)
        .def("files", &files, (arg("storage")=false))
        .def("rename_file", rename_file0)
#if TORRENT_USE_WSTRING
        .def("rename_file", rename_file1)
#endif

        .def("priv", &torrent_info::priv)
        .def("trackers", range(begin_trackers, end_trackers))

        .def("creation_date", &torrent_info::creation_date)

        .def("add_node", &add_node)
        .def("nodes", &nodes)
        .def("metadata", &metadata)
        .def("metadata_size", &torrent_info::metadata_size)
        .def("map_block", map_block)
        .def("map_file", &torrent_info::map_file)
        ;

    class_<file_entry>("file_entry")
        .def_readwrite("path", &file_entry::path)
        .def_readwrite("symlink_path", &file_entry::symlink_path)
        .def_readwrite("filehash", &file_entry::filehash)
        .def_readwrite("mtime", &file_entry::mtime)
        .add_property("pad_file", &get_pad_file)
        .add_property("executable_attribute", &get_executable_attribute)
        .add_property("hidden_attribute", &get_hidden_attribute)
        .add_property("symlink_attribute", &get_symlink_attribute)
        .add_property("offset", &get_offset)
        .add_property("size", &get_size)
        ;

    class_<announce_entry>("announce_entry", init<std::string const&>())
        .def_readwrite("url", &announce_entry::url)
        .add_property("tier", &get_tier, &set_tier)
        .add_property("fail_limit", &get_fail_limit, &set_fail_limit)
        .add_property("fails", &get_fails)
        .add_property("source", &get_source)
        .add_property("verified", &get_verified)
        .add_property("updating", &get_updating)
        .add_property("start_sent", &get_start_sent)
        .add_property("complete_sent", &get_complete_sent)
        .add_property("send_stats", &get_send_stats)

        .def("reset", &announce_entry::reset)
        .def("failed", &announce_entry::failed, arg("retry_interval") = 0)
        .def("can_announce", &announce_entry::can_announce)
        .def("is_working", &announce_entry::is_working)
        .def("trim", &announce_entry::trim)
        ;

    enum_<announce_entry::tracker_source>("tracker_source")
        .value("source_torrent", announce_entry::source_torrent)
        .value("source_client", announce_entry::source_client)
        .value("source_magnet_link", announce_entry::source_magnet_link)
        .value("source_tex", announce_entry::source_tex)
    ;
}

<commit_msg>fix python binding build<commit_after>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/python.hpp>
#include <libtorrent/torrent_info.hpp>
#include "libtorrent/intrusive_ptr_base.hpp"
#include "libtorrent/session_settings.hpp"

using namespace boost::python;
using namespace libtorrent;

namespace
{

    std::vector<announce_entry>::const_iterator begin_trackers(torrent_info& i)
    {
        return i.trackers().begin();
    }

    std::vector<announce_entry>::const_iterator end_trackers(torrent_info& i)
    {
        return i.trackers().end();
    }

    void add_node(torrent_info& ti, char const* hostname, int port)
    {
        ti.add_node(std::make_pair(hostname, port));
    }

    list nodes(torrent_info const& ti)
    {
        list result;

        typedef std::vector<std::pair<std::string, int> > list_type;

        for (list_type::const_iterator i = ti.nodes().begin(); i != ti.nodes().end(); ++i)
        {
            result.append(make_tuple(i->first, i->second));
        }

        return result;
    }

    file_storage::iterator begin_files(torrent_info& i)
    {
        return i.begin_files();
    }

    file_storage::iterator end_files(torrent_info& i)
    {
        return i.end_files();
    }

    //list files(torrent_info const& ti, bool storage) {
    list files(torrent_info const& ti, bool storage) {
        list result;

        typedef torrent_info::file_iterator iter;

        for (iter i = ti.begin_files(); i != ti.end_files(); ++i)
            result.append(ti.files().at(i));

        return result;
    }

    std::string hash_for_piece(torrent_info const& ti, int i)
    {
        return ti.hash_for_piece(i).to_string();
    }

    std::string metadata(torrent_info const& ti) {
        std::string result(ti.metadata().get(), ti.metadata_size());
        return result;
    }

    torrent_info construct0(std::string path) {
        return torrent_info(path);
    }

    list map_block(torrent_info& ti, int piece, size_type offset, int size)
    {
       std::vector<file_slice> p = ti.map_block(piece, offset, size);
       list result;

       for (std::vector<file_slice>::iterator i(p.begin()), e(p.end()); i != e; ++i)
          result.append(*i);

       return result;
    }

    bool get_tier(announce_entry const& ae) { return ae.tier; }
    void set_tier(announce_entry& ae, bool v) { ae.tier = v; }
    bool get_fail_limit(announce_entry const& ae) { return ae.fail_limit; }
    void set_fail_limit(announce_entry& ae, int l) { ae.fail_limit = l; }
    bool get_fails(announce_entry const& ae) { return ae.fails; }
    bool get_source(announce_entry const& ae) { return ae.source; }
    bool get_verified(announce_entry const& ae) { return ae.verified; }
    bool get_updating(announce_entry const& ae) { return ae.updating; }
    bool get_start_sent(announce_entry const& ae) { return ae.start_sent; }
    bool get_complete_sent(announce_entry const& ae) { return ae.complete_sent; }
    bool get_send_stats(announce_entry const& ae) { return ae.send_stats; }

    size_type get_size(file_entry const& fe) { return fe.size; }
    size_type get_offset(file_entry const& fe) { return fe.offset; }
    bool get_pad_file(file_entry const& fe) { return fe.pad_file; }
    bool get_executable_attribute(file_entry const& fe) { return fe.executable_attribute; }
    bool get_hidden_attribute(file_entry const& fe) { return fe.hidden_attribute; }
    bool get_symlink_attribute(file_entry const& fe) { return fe.symlink_attribute; }

} // namespace unnamed

void bind_torrent_info()
{
    return_value_policy<copy_const_reference> copy;

    void (torrent_info::*rename_file0)(int, std::string const&) = &torrent_info::rename_file;
#if TORRENT_USE_WSTRING
    void (torrent_info::*rename_file1)(int, std::wstring const&) = &torrent_info::rename_file;
#endif

    class_<file_slice>("file_slice")
        .def_readwrite("file_index", &file_slice::file_index)
        .def_readwrite("offset", &file_slice::offset)
        .def_readwrite("size", &file_slice::size)
        ;

    class_<torrent_info, boost::intrusive_ptr<torrent_info> >("torrent_info", no_init)
#ifndef TORRENT_NO_DEPRECATE
        .def(init<entry const&>(arg("e")))
#endif
        .def(init<sha1_hash const&, int>((arg("info_hash"), arg("flags") = 0)))
        .def(init<char const*, int, int>((arg("buffer"), arg("length"), arg("flags") = 0)))
        .def(init<std::string, int>((arg("file"), arg("flags") = 0)))
        .def(init<torrent_info const&, int>((arg("ti"), arg("flags") = 0)))
#if TORRENT_USE_WSTRING
        .def(init<std::wstring, int>((arg("file"), arg("flags") = 0)))
#endif

        .def("add_tracker", &torrent_info::add_tracker, arg("url"))
        .def("add_url_seed", &torrent_info::add_url_seed)

        .def("name", &torrent_info::name, copy)
        .def("comment", &torrent_info::comment, copy)
        .def("creator", &torrent_info::creator, copy)
        .def("total_size", &torrent_info::total_size)
        .def("piece_length", &torrent_info::piece_length)
        .def("num_pieces", &torrent_info::num_pieces)
#ifndef TORRENT_NO_DEPRECATE
        .def("info_hash", &torrent_info::info_hash, copy)
#endif
        .def("hash_for_piece", &hash_for_piece)
        .def("piece_size", &torrent_info::piece_size)

        .def("num_files", &torrent_info::num_files, (arg("storage")=false))
        .def("file_at", &torrent_info::file_at)
        .def("file_at_offset", &torrent_info::file_at_offset)
        .def("files", &files, (arg("storage")=false))
        .def("rename_file", rename_file0)
#if TORRENT_USE_WSTRING
        .def("rename_file", rename_file1)
#endif

        .def("priv", &torrent_info::priv)
        .def("trackers", range(begin_trackers, end_trackers))

        .def("creation_date", &torrent_info::creation_date)

        .def("add_node", &add_node)
        .def("nodes", &nodes)
        .def("metadata", &metadata)
        .def("metadata_size", &torrent_info::metadata_size)
        .def("map_block", map_block)
        .def("map_file", &torrent_info::map_file)
        ;

    class_<file_entry>("file_entry")
        .def_readwrite("path", &file_entry::path)
        .def_readwrite("symlink_path", &file_entry::symlink_path)
        .def_readwrite("filehash", &file_entry::filehash)
        .def_readwrite("mtime", &file_entry::mtime)
        .add_property("pad_file", &get_pad_file)
        .add_property("executable_attribute", &get_executable_attribute)
        .add_property("hidden_attribute", &get_hidden_attribute)
        .add_property("symlink_attribute", &get_symlink_attribute)
        .add_property("offset", &get_offset)
        .add_property("size", &get_size)
        ;

    class_<announce_entry>("announce_entry", init<std::string const&>())
        .def_readwrite("url", &announce_entry::url)
        .add_property("tier", &get_tier, &set_tier)
        .add_property("fail_limit", &get_fail_limit, &set_fail_limit)
        .add_property("fails", &get_fails)
        .add_property("source", &get_source)
        .add_property("verified", &get_verified)
        .add_property("updating", &get_updating)
        .add_property("start_sent", &get_start_sent)
        .add_property("complete_sent", &get_complete_sent)
        .add_property("send_stats", &get_send_stats)

        .def("reset", &announce_entry::reset)
        .def("failed", &announce_entry::failed, arg("retry_interval") = 0)
        .def("can_announce", &announce_entry::can_announce)
        .def("is_working", &announce_entry::is_working)
        .def("trim", &announce_entry::trim)
        ;

    enum_<announce_entry::tracker_source>("tracker_source")
        .value("source_torrent", announce_entry::source_torrent)
        .value("source_client", announce_entry::source_client)
        .value("source_magnet_link", announce_entry::source_magnet_link)
        .value("source_tex", announce_entry::source_tex)
    ;
}

<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////
// This file is part of Grappa, a system for scaling irregular
// applications on commodity clusters.

// Copyright (C) 2010-2014 University of Washington and Battelle
// Memorial Institute. University of Washington authorizes use of this
// Grappa software.

// Grappa is free software: you can redistribute it and/or modify it
// under the terms of the Affero General Public License as published
// by Affero, Inc., either version 1 of the License, or (at your
// option) any later version.

// Grappa 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
// Affero General Public License for more details.

// You should have received a copy of the Affero General Public
// License along with this program. If not, you may obtain one from
// http://www.affero.org/oagl.html.
////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////
/// Demonstrates using the GraphLab API to implement SSSP
////////////////////////////////////////////////////////////////////////
#include <Grappa.hpp>
#include "graphlab.hpp"

DEFINE_bool( metrics, false, "Dump metrics");

DEFINE_bool( max_degree_source, false, "Start from maximum degree vertex");
DEFINE_int32(scale, 10, "Log2 number of vertices.");
DEFINE_int32(edgefactor, 16, "Average number of edges per vertex.");

DEFINE_int32(trials, 3, "Number of timed trials to run and average over.");

DEFINE_string(path, "", "Path to graph source file.");
DEFINE_string(format, "bintsv4", "Format of graph source file.");

GRAPPA_DEFINE_METRIC(SimpleMetric<double>, tuple_time, 0);
GRAPPA_DEFINE_METRIC(SimpleMetric<double>, construction_time, 0);
GRAPPA_DEFINE_METRIC(SummarizingMetric<double>, total_time, 0);

using distance_t = float;

const distance_t MAX_DIST = std::numeric_limits<distance_t>::max();

struct SSSPVertexData : public GraphlabVertexData< SSSPVertexData > {
  distance_t dist, new_dist;
  SSSPVertexData(): dist(MAX_DIST), new_dist(0.0) {}
};
struct EdgeDistance {
  distance_t dist;
};

using G = Graph<SSSPVertexData,EdgeDistance>;

template< typename G >
inline VertexID choose_root(GlobalAddress<G> g) {
  VertexID root;
  do {
    root = random() % g->nv;
  } while (call(g->vs+root,[](typename G::Vertex& v){ return v.nadj; }) == 0);
  return root;
}

struct SSSPVertexProgram : public GraphlabVertexProgram<G,bool> {
  bool changed;
  double min_dist;

  SSSPVertexProgram(const Vertex& v) {}

  bool gather_edges(Vertex& v) const { return false; }

  bool gather(Vertex& src, Edge& e) const { return 0; }

  void apply(Vertex& v, bool ignore) {
    changed = false;
    if (v->dist > v->new_dist) {
      changed = true;
      v->dist = v->new_dist;
    }
    min_dist = v->dist; // so we can use it in 'scatter'
  }

  bool scatter_edges(Vertex& v) const { return changed; }

  bool scatter(const Edge& e, Vertex& target) const {
    auto new_dist = min_dist + e->dist;
    if (new_dist < target->dist) {
      target->new_dist = new_dist;
      target->activate();
    }
    return false;
  }
};

using MaxDegree = CmpElement<VertexID,int64_t>;
Reducer<MaxDegree,ReducerType::Max> max_degree;

int main(int argc, char* argv[]) {
  init(&argc, &argv);
  run([]{
    double t;

    TupleGraph tg;

    GRAPPA_TIME_REGION(tuple_time) {
      if (FLAGS_path.empty()) {
        int64_t NE = (1L << FLAGS_scale) * FLAGS_edgefactor;
        tg = TupleGraph::Kronecker(FLAGS_scale, NE, 111, 222);
      } else {
        LOG(INFO) << "loading " << FLAGS_path;
        tg = TupleGraph::Load(FLAGS_path, FLAGS_format);
        LOG(INFO) << "done! loaded " << tg.nedge << " edges";
      }
    }

    t = walltime();

    auto g = G::create(tg); // undirected

    // TODO: random init
    forall(g, [=](G::Vertex& v){
      new (&v.data) SSSPVertexData();
      forall<async>(adj(g,v), [](G::Edge& e){
        e->dist = 1.0;
      });
    });

    tg.destroy();

    construction_time = (walltime()-t);
    LOG(INFO) << construction_time;

    VertexID root;
    if (FLAGS_max_degree_source) {
      forall(g, [](VertexID i, G::Vertex& v){
        max_degree << MaxDegree(i, v.nadj);
      });
      root = static_cast<MaxDegree>(max_degree).idx();
    } else {
      root = choose_root(g);
    }

    LOG(INFO) << "SSSP on root:" << root;

    for (int i = 0; i < FLAGS_trials; i++) {
      if (FLAGS_trials > 1) LOG(INFO) << "trial " << i;

      // re-initialize
      forall(g, [](G::Vertex& v){ new (&v.data) SSSPVertexData(); });

      GRAPPA_TIME_REGION(total_time) {
        activate(g->vs+root);
        run_synchronous< SSSPVertexProgram >(g);
      }

      if (i == 0) total_time.reset(); // don't count the first one
    }

    GRAPPA_TIME_REGION(total_time) {
      activate(g->vs+root);
      run_synchronous< SSSPVertexProgram >(g);
    }
    LOG(INFO) << "-- SSSP done";

    if (FLAGS_metrics) Metrics::merge_and_print();
    else {
      std::cerr << total_time << "\n"
                << iteration_time << "\n";
    }
    Metrics::merge_and_dump_to_file();

    if (FLAGS_scale <= 8) {
      g->dump([](std::ostream& o, G::Vertex& v){
        o << "{ dist:" << v->dist << " }";
      });
    }

    g->destroy();
  });
  finalize();
}
<commit_msg>fix sssp, accidentally running an additional time without re-initializing<commit_after>////////////////////////////////////////////////////////////////////////
// This file is part of Grappa, a system for scaling irregular
// applications on commodity clusters.

// Copyright (C) 2010-2014 University of Washington and Battelle
// Memorial Institute. University of Washington authorizes use of this
// Grappa software.

// Grappa is free software: you can redistribute it and/or modify it
// under the terms of the Affero General Public License as published
// by Affero, Inc., either version 1 of the License, or (at your
// option) any later version.

// Grappa 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
// Affero General Public License for more details.

// You should have received a copy of the Affero General Public
// License along with this program. If not, you may obtain one from
// http://www.affero.org/oagl.html.
////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////
/// Demonstrates using the GraphLab API to implement SSSP
////////////////////////////////////////////////////////////////////////
#include <Grappa.hpp>
#include "graphlab.hpp"

DEFINE_bool( metrics, false, "Dump metrics");

DEFINE_bool( max_degree_source, false, "Start from maximum degree vertex");
DEFINE_int32(scale, 10, "Log2 number of vertices.");
DEFINE_int32(edgefactor, 16, "Average number of edges per vertex.");

DEFINE_int32(trials, 3, "Number of timed trials to run and average over.");

DEFINE_string(path, "", "Path to graph source file.");
DEFINE_string(format, "bintsv4", "Format of graph source file.");

GRAPPA_DEFINE_METRIC(SimpleMetric<double>, tuple_time, 0);
GRAPPA_DEFINE_METRIC(SimpleMetric<double>, construction_time, 0);
GRAPPA_DEFINE_METRIC(SummarizingMetric<double>, total_time, 0);

using distance_t = float;

const distance_t MAX_DIST = std::numeric_limits<distance_t>::max();

struct SSSPVertexData : public GraphlabVertexData< SSSPVertexData > {
  distance_t dist, new_dist;
  SSSPVertexData(): dist(MAX_DIST), new_dist(0.0) {}
};
struct EdgeDistance {
  distance_t dist;
};

using G = Graph<SSSPVertexData,EdgeDistance>;

template< typename G >
inline VertexID choose_root(GlobalAddress<G> g) {
  VertexID root;
  do {
    root = random() % g->nv;
  } while (call(g->vs+root,[](typename G::Vertex& v){ return v.nadj; }) == 0);
  return root;
}

struct SSSPVertexProgram : public GraphlabVertexProgram<G,bool> {
  bool changed;
  double min_dist;

  SSSPVertexProgram(const Vertex& v) {}

  bool gather_edges(Vertex& v) const { return false; }

  bool gather(Vertex& src, Edge& e) const { return 0; }

  void apply(Vertex& v, bool ignore) {
    changed = false;
    if (v->dist > v->new_dist) {
      changed = true;
      v->dist = v->new_dist;
    }
    min_dist = v->dist; // so we can use it in 'scatter'
  }

  bool scatter_edges(Vertex& v) const { return changed; }

  bool scatter(const Edge& e, Vertex& target) const {
    auto new_dist = min_dist + e->dist;
    if (new_dist < target->dist) {
      target->new_dist = new_dist;
      target->activate();
    }
    return false;
  }
};

using MaxDegree = CmpElement<VertexID,int64_t>;
Reducer<MaxDegree,ReducerType::Max> max_degree;

int main(int argc, char* argv[]) {
  init(&argc, &argv);
  run([]{
    double t;

    TupleGraph tg;

    GRAPPA_TIME_REGION(tuple_time) {
      if (FLAGS_path.empty()) {
        int64_t NE = (1L << FLAGS_scale) * FLAGS_edgefactor;
        tg = TupleGraph::Kronecker(FLAGS_scale, NE, 111, 222);
      } else {
        LOG(INFO) << "loading " << FLAGS_path;
        tg = TupleGraph::Load(FLAGS_path, FLAGS_format);
        LOG(INFO) << "done! loaded " << tg.nedge << " edges";
      }
    }

    t = walltime();

    auto g = G::create(tg); // undirected

    // TODO: random init
    forall(g, [=](G::Vertex& v){
      new (&v.data) SSSPVertexData();
      forall<async>(adj(g,v), [](G::Edge& e){
        e->dist = 1.0;
      });
    });

    tg.destroy();

    construction_time = (walltime()-t);
    LOG(INFO) << construction_time;

    VertexID root;
    if (FLAGS_max_degree_source) {
      forall(g, [](VertexID i, G::Vertex& v){
        max_degree << MaxDegree(i, v.nadj);
      });
      root = static_cast<MaxDegree>(max_degree).idx();
    } else {
      root = choose_root(g);
    }

    LOG(INFO) << "SSSP on root:" << root;

    for (int i = 0; i < FLAGS_trials; i++) {
      if (FLAGS_trials > 1) LOG(INFO) << "trial " << i;

      // re-initialize
      forall(g, [](G::Vertex& v){ new (&v.data) SSSPVertexData(); });

      GRAPPA_TIME_REGION(total_time) {
        activate(g->vs+root);
        run_synchronous< SSSPVertexProgram >(g);
      }

      if (i == 0) total_time.reset(); // don't count the first one
    }

    LOG(INFO) << "-- SSSP done";

    if (FLAGS_metrics) Metrics::merge_and_print();
    else {
      std::cerr << total_time << "\n"
                << iteration_time << "\n";
    }
    Metrics::merge_and_dump_to_file();

    if (FLAGS_scale <= 8) {
      g->dump([](std::ostream& o, G::Vertex& v){
        o << "{ dist:" << v->dist << " }";
      });
    }

    g->destroy();
  });
  finalize();
}
<|endoftext|>


<commit_before>#include "testApp.h"
#include "BubbleData.h"
#include "QuestionData.h"
#include "constants.h"

// for testing
bool bDidFakeSecondTouch = false;

testApp *testApp::instance;
//--------------------------------------------------------------
void testApp::setup(){
	projection = BubbleProjection::getInstance();
	audioData = Donk::AudioData::getInstance();

	gradientProjection.allocate(500, 500);
	instance = this;

	setupOsc();
	setupKinect();
	setupGraphics();
	mode = Donk::Mode::getInstance();
	// default starting mode
	nextMode = "vote";
	mode->setMode(nextMode);
}

void testApp::setupGraphics() {
	ofSetVerticalSync(true);
	ofSetFrameRate(60.f);
	ofBackground(0, 0, 0);

	projection->allocate(PROJECTION_RESOLUTION_WIDTH, PROJECTION_RESOLUTION_HEIGHT);
	calibrationProjection.allocate(PROJECTION_RESOLUTION_WIDTH, PROJECTION_RESOLUTION_HEIGHT);

}
//--------------------------------------------------------------
void testApp::update(){

	Donk::BubbleData::update();

	processOsc();
	projection->update();

	ofSetWindowTitle(ofToString(ofGetFrameRate(), 2) + "fps,  " + ofToString(ofGetWindowSize().x) + "x"+ofToString(ofGetWindowSize().y));

}

void testApp::render() {

	// if we're capturing coords for projection mapping...
	if(calibrationProjection.calibrate) {
		calibrationProjection.render();
	} else {
		projection->render();
		gradientProjection.render();
	}
}

void testApp::drawView() {

	// comment this stuff out if you don't want to draw the mesh
	ofSetColor(mode->getValue("Background Red"),
			  mode->getValue("Background Green"),
			  mode->getValue("Background Blue"));

	if(calibrationProjection.calibrate) {

		calibrationProjection.drawOnModel(scene->getModel());
		if(calibrationProjection.drawFacets) {
			glLineWidth(calibrationProjection.lineWidth);
			ofSetHexColor(calibrationProjection.facetColor);
			scene->getModel()->drawOutline();
			glLineWidth(1);
		}

	} else {

		scene->getLight()->setPosition(ofVec3f(mode->getValue("light x"),
								  mode->getValue("light y"),
								  mode->getValue("light z")));
		// printf("%f %f %f\n", mode->getValue("light x"), mode->getValue("light y"), mode->getValue("light z"));
		//printf("%f %f %f\n", mode->getValue("light x"), mode->getValue("light y"), mode->getValue("light z"));
		glShadeModel(GL_FLAT);
		ofEnableLighting();
		scene->getLight()->enable();
//		scene->getModel()->drawSolid();
		gradientProjection.drawOnModel(scene->getModel());

		glShadeModel(GL_SMOOTH);
		ofDisableLighting();
		projection->drawOnModel(scene->getModel());
	}

}

//--------------------------------------------------------------
void testApp::keyPressed(int key){

	if(key == 'q') mode->setMode("buzz");
	if(key == 'w') mode->setMode("inspiration");
	if(key == 'e') mode->setMode("interview");
	if(key == 'r') mode->setMode("question");
	if(key == 't') mode->setMode("performance");

	if(key=='b'||key=='B') {
		ofxOscMessage m;
		Donk::BubbleData *data = new Donk::BubbleData(m);
		//data->mode = "buzz";
        data->mode = mode->getMode();
		data->id = "39A5D49FE5";
        if(data->mode == "buzz"){
            data->userName = "mazzbuzz";
            data->text = "Just a little tweet";
        }
        else if(data->mode == "inspiration"){
            data->userName = "inspirmaz";
            data->text = "Feel the poison in my veins. Tell me are you strong enough. To keep up with my life. Welcome to the dangerzone. What you see ain't what you get. Let us fly this aeroplane. 1";
        }
        else if(data->mode == "interview"){
            data->userName = "boxtalks";
            data->text = "A medium sized tweet for those who can't commit to long or short";
        }
        else if(data->mode == "question"){
            data->userName = "wonderbox";
            data->text = "This is test 1";
        }
        else if(data->mode == "performance"){
            data->userName = "boxrox";
            data->text = "This is test 1";
        }
        else{
            ofLog(OF_LOG_ERROR, "Test Bubble in invalid mode");
        }

        /*
		switch((int)ofRandom(5)) {
			case 0: data->text = "This is test 1"; break;
			case 1: data->text = "Bubble bubble bubble"; break;
			case 2: data->text = "Project donk here"; break;
			case 3: data->text = "Who is this Maroon 5?"; break;
			case 4: data->text = "brown sticky liquid!"; break;
		}
		switch((int)ofRandom(5)) {
			case 0: data->userName = "mazbox"; break;
			case 1: data->userName = "cokeMe!"; break;
			case 2: data->userName = "DeadSaxon"; break;
			case 3: data->userName = "jtnimoy"; break;
			case 4: data->userName = "timeteam"; break;
		}
		*/

		if(ofRandomuf()>0.5){
			data->media.push_back(Donk::BubbleData::MediaEntry());
			char fname[64];
			sprintf(fname,"images/performance/%i.png",(int)ofRandom(10,20)); //numbering of files is with leading zeros, so go from 10 to 20
			cout << fname << endl;
			data->media.back().mediaImage.loadImage(fname);
			data->media.back().thumbImage = data->media.back().mediaImage;
			data->media.back().thumbImage.resize(128, 128);
		}

		data->profileImage.loadImage("lena.png");

		projection->bubbleReceived(data);
	}

	if(!bDidFakeSecondTouch && key == 'x') {
		ofTouchEventArgs t;
		t.id = 1;
		t.x = (float)mouseX/ofGetWidth();
		t.y = (float)mouseY/ofGetHeight();
 		touchDown(t);
		bDidFakeSecondTouch = true;
	}
}

//--------------------------------------------------------------
void testApp::keyReleased(int key){

	if(bDidFakeSecondTouch) {
		ofTouchEventArgs t;
		t.id = 1;
		t.x = (float)mouseX/ofGetWidth();
		t.y = (float)mouseY/ofGetHeight();
 		touchUp(t);
		bDidFakeSecondTouch = false;
	}
}

//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ){

}

//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button){

	ofTouchEventArgs t;
	t.x = (float)x/ofGetWidth();
	t.y = (float)y/ofGetHeight();
	t.id = button;
	touchMoved(t);

	if(ofGetKeyPressed('x')) {

		t.id ++;
		float pct = 100.0 * ((float)x/(float)ofGetWidth());
		t.x = (float)(x-pct)/ofGetWidth();
		t.y = (float)y/ofGetHeight();
		if(!bDidFakeSecondTouch) {
			touchDown(t);
			bDidFakeSecondTouch = true;
		}
		else touchMoved(t);

	}
}

//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button){
	ofTouchEventArgs t;
	t.x = (float)x/ofGetWidth();
	t.y = (float)y/ofGetHeight();
	t.id = button;
	touchDown(t);

	if(ofGetKeyPressed('x')) {
		t.id = 1;
		t.x = (float)(x-50.0)/ofGetWidth();
		t.y = (float)y/ofGetHeight();
 		touchDown(t);
		bDidFakeSecondTouch = true;
	}
}

//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button){

	ofTouchEventArgs t;
	t.x = (float)x/ofGetWidth();
	t.y = (float)y/ofGetHeight();
	t.id = button;
	touchUp(t);

	if(bDidFakeSecondTouch) {
		t.id = 1;
		t.x = (float)(x-50.0)/ofGetWidth();
		t.y = (float)y/ofGetHeight();
 		touchUp(t);
		bDidFakeSecondTouch = false;
	}
}

//--------------------------------------------------------------
void testApp::windowResized(int w, int h){

}

//--------------------------------------------------------------

void testApp::setupOsc() {
	if(!json_settings.loadFromFile("settings/OSC.json.txt")){
		cerr << "failed to load json settings file" << endl;
		_exit(1);
	}
	oscIn.setup(json_settings["osc_listen_port"].asInt());
	audioData->connect(json_settings["audio_osc_port"].asInt());

}

void testApp::processOsc() {
	while(oscIn.hasWaitingMessages()) {
		ofxOscMessage m;
		oscIn.getNextMessage(&m);
		if(m.getAddress()=="/control/mode/next") {

			//get the next mode ready
			string modeName = m.getArgAsString(0);
			nextMode = modeName;

		}else if(m.getAddress()=="/control/mode/swap") {
			mode->setMode(nextMode);

		}else if(m.getAddress()=="/control/bubble/new") {

			Donk::BubbleData::add(m);

		}else if(m.getAddress()=="/control/question/update") {

			Donk::QuestionData qd(m);
			cout << "todo: handle question update \"" << qd.text << "\" " << qd.tags[0] << "=" <<
			qd.tag_counts[0] << "," << qd.tags[1] << "=" << qd.tag_counts[1] << endl;

		}
	}
	audioData->update();
}

void testApp::setupKinect() {
	tuio.connect(json_settings["tuio_listen_port"].asInt());
	ofAddListener(ofEvents.touchDown, this, &testApp::touchDown);
	ofAddListener(ofEvents.touchUp, this, &testApp::touchUp);
	ofAddListener(ofEvents.touchMoved, this, &testApp::touchMoved);

	calibrationProjection.setInteractiveArea(&projection->getInteractiveArea());
	calibrationProjection.createGui(getCalibrationGui());

}

void testApp::touchDown(ofTouchEventArgs &touch) {
	projection->touchDown(touch.x, touch.y, touch.id);
}

void testApp::touchMoved(ofTouchEventArgs &touch) {
	projection->touchMoved(touch.x, touch.y, touch.id);
	// e.g.
	// touches are normalized
	ofVec2f pos(touch.x, touch.y);

	// now scaled for screen coords
	pos *= ofGetWindowSize();
	//printf("pos: %f %f\n", pos.x, pos.y);
}

void testApp::touchUp(ofTouchEventArgs &touch) {
	projection->touchUp(touch.x, touch.y, touch.id);
}<commit_msg>auto mode tester hack<commit_after>#include "testApp.h"
#include "BubbleData.h"
#include "QuestionData.h"
#include "constants.h"

// for testing
bool bDidFakeSecondTouch = false;

testApp *testApp::instance;
//--------------------------------------------------------------
void testApp::setup(){
	projection = BubbleProjection::getInstance();
	audioData = Donk::AudioData::getInstance();

	gradientProjection.allocate(500, 500);
	instance = this;

	setupOsc();
	setupKinect();
	setupGraphics();
	mode = Donk::Mode::getInstance();
	// default starting mode
	nextMode = "vote";
	mode->setMode(nextMode);

#ifdef AUTO_TESTING
    switchModeTime = 12;
    switchModeLastTime = 0;
    makeBubbleTime = 3;
    makeBubbleLastTime = 0;
#endif
}

void testApp::setupGraphics() {
	ofSetVerticalSync(true);
	ofSetFrameRate(60.f);
	ofBackground(0, 0, 0);

	projection->allocate(PROJECTION_RESOLUTION_WIDTH, PROJECTION_RESOLUTION_HEIGHT);
	calibrationProjection.allocate(PROJECTION_RESOLUTION_WIDTH, PROJECTION_RESOLUTION_HEIGHT);

}
//--------------------------------------------------------------
void testApp::update(){

	Donk::BubbleData::update();

	processOsc();
	projection->update();

	ofSetWindowTitle(ofToString(ofGetFrameRate(), 2) + "fps,  " + ofToString(ofGetWindowSize().x) + "x"+ofToString(ofGetWindowSize().y));

	#ifdef AUTO_TESTING
	float dtSwitch = ofGetElapsedTimef() - switchModeLastTime;
    float dtBub = ofGetElapsedTimef() - makeBubbleLastTime;
    if(dtSwitch > switchModeTime)
    {
        switchModeLastTime = ofGetElapsedTimef();

		int newMode = ofRandom(0,5);
		switch(newMode)
		{
			case 0: mode->setMode("buzz");break;
			case 1: mode->setMode("inspiration");break;
			case 2: mode->setMode("performance");break;
			case 3: mode->setMode("interview");break;
			case 4: mode->setMode("vote");break;

		}

        switchModeTime = ofRandom(12,40);
        string timeStamp = ofToString(ofGetHours() )+" : " + ofToString(ofGetMinutes()) + " : " + ofToString( ofGetSeconds() );
        cout << "switched mode " << mode->getMode() << " " <<  timeStamp << endl;
    }

    if(dtBub > makeBubbleTime)
    {
        makeBubbleLastTime = ofGetElapsedTimef();
        keyPressed('b');
        makeBubbleTime = ofRandom(2,10);
        cout << "made bubble" << endl;
    }
	#endif

}

void testApp::render() {

	// if we're capturing coords for projection mapping...
	if(calibrationProjection.calibrate) {
		calibrationProjection.render();
	} else {
		projection->render();
		gradientProjection.render();
	}
}

void testApp::drawView() {

	// comment this stuff out if you don't want to draw the mesh
	ofSetColor(mode->getValue("Background Red"),
			  mode->getValue("Background Green"),
			  mode->getValue("Background Blue"));

	if(calibrationProjection.calibrate) {

		calibrationProjection.drawOnModel(scene->getModel());
		if(calibrationProjection.drawFacets) {
			glLineWidth(calibrationProjection.lineWidth);
			ofSetHexColor(calibrationProjection.facetColor);
			scene->getModel()->drawOutline();
			glLineWidth(1);
		}

	} else {

		scene->getLight()->setPosition(ofVec3f(mode->getValue("light x"),
								  mode->getValue("light y"),
								  mode->getValue("light z")));
		// printf("%f %f %f\n", mode->getValue("light x"), mode->getValue("light y"), mode->getValue("light z"));
		//printf("%f %f %f\n", mode->getValue("light x"), mode->getValue("light y"), mode->getValue("light z"));
		glShadeModel(GL_FLAT);
		ofEnableLighting();
		scene->getLight()->enable();
//		scene->getModel()->drawSolid();
		gradientProjection.drawOnModel(scene->getModel());

		glShadeModel(GL_SMOOTH);
		ofDisableLighting();
		projection->drawOnModel(scene->getModel());
	}

}

//--------------------------------------------------------------
void testApp::keyPressed(int key){

	if(key == 'q') mode->setMode("buzz");
	if(key == 'w') mode->setMode("inspiration");
	if(key == 'e') mode->setMode("interview");
	if(key == 'r') mode->setMode("question");
	if(key == 't') mode->setMode("performance");

	if(key=='b'||key=='B') {
		ofxOscMessage m;
		Donk::BubbleData *data = new Donk::BubbleData(m);
		//data->mode = "buzz";
        data->mode = mode->getMode();
		data->id = "39A5D49FE5";
        if(data->mode == "buzz"){
            data->userName = "mazzbuzz";
            data->text = "Just a little tweet";
        }
        else if(data->mode == "inspiration"){
            data->userName = "inspirmaz";
            data->text = "Feel the poison in my veins. Tell me are you strong enough. To keep up with my life. Welcome to the dangerzone. What you see ain't what you get. Let us fly this aeroplane. 1";
        }
        else if(data->mode == "interview"){
            data->userName = "boxtalks";
            data->text = "A medium sized tweet for those who can't commit to long or short";
        }
        else if(data->mode == "question"){
            data->userName = "wonderbox";
            data->text = "This is test 1";
        }
        else if(data->mode == "performance"){
            data->userName = "boxrox";
            data->text = "This is test 1";
        }
        else{
            ofLog(OF_LOG_ERROR, "Test Bubble in invalid mode");
        }

        /*
		switch((int)ofRandom(5)) {
			case 0: data->text = "This is test 1"; break;
			case 1: data->text = "Bubble bubble bubble"; break;
			case 2: data->text = "Project donk here"; break;
			case 3: data->text = "Who is this Maroon 5?"; break;
			case 4: data->text = "brown sticky liquid!"; break;
		}
		switch((int)ofRandom(5)) {
			case 0: data->userName = "mazbox"; break;
			case 1: data->userName = "cokeMe!"; break;
			case 2: data->userName = "DeadSaxon"; break;
			case 3: data->userName = "jtnimoy"; break;
			case 4: data->userName = "timeteam"; break;
		}
		*/

		if(ofRandomuf()>0.5){
			data->media.push_back(Donk::BubbleData::MediaEntry());
			char fname[64];
			sprintf(fname,"images/performance/%i.png",(int)ofRandom(10,20)); //numbering of files is with leading zeros, so go from 10 to 20
			cout << fname << endl;
			data->media.back().mediaImage.loadImage(fname);
			data->media.back().thumbImage = data->media.back().mediaImage;
			data->media.back().thumbImage.resize(128, 128);
		}

		data->profileImage.loadImage("lena.png");

		projection->bubbleReceived(data);
	}

	if(!bDidFakeSecondTouch && key == 'x') {
		ofTouchEventArgs t;
		t.id = 1;
		t.x = (float)mouseX/ofGetWidth();
		t.y = (float)mouseY/ofGetHeight();
 		touchDown(t);
		bDidFakeSecondTouch = true;
	}
}

//--------------------------------------------------------------
void testApp::keyReleased(int key){

	if(bDidFakeSecondTouch) {
		ofTouchEventArgs t;
		t.id = 1;
		t.x = (float)mouseX/ofGetWidth();
		t.y = (float)mouseY/ofGetHeight();
 		touchUp(t);
		bDidFakeSecondTouch = false;
	}
}

//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ){

}

//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button){

	ofTouchEventArgs t;
	t.x = (float)x/ofGetWidth();
	t.y = (float)y/ofGetHeight();
	t.id = button;
	touchMoved(t);

	if(ofGetKeyPressed('x')) {

		t.id ++;
		float pct = 100.0 * ((float)x/(float)ofGetWidth());
		t.x = (float)(x-pct)/ofGetWidth();
		t.y = (float)y/ofGetHeight();
		if(!bDidFakeSecondTouch) {
			touchDown(t);
			bDidFakeSecondTouch = true;
		}
		else touchMoved(t);

	}
}

//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button){
	ofTouchEventArgs t;
	t.x = (float)x/ofGetWidth();
	t.y = (float)y/ofGetHeight();
	t.id = button;
	touchDown(t);

	if(ofGetKeyPressed('x')) {
		t.id = 1;
		t.x = (float)(x-50.0)/ofGetWidth();
		t.y = (float)y/ofGetHeight();
 		touchDown(t);
		bDidFakeSecondTouch = true;
	}
}

//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button){

	ofTouchEventArgs t;
	t.x = (float)x/ofGetWidth();
	t.y = (float)y/ofGetHeight();
	t.id = button;
	touchUp(t);

	if(bDidFakeSecondTouch) {
		t.id = 1;
		t.x = (float)(x-50.0)/ofGetWidth();
		t.y = (float)y/ofGetHeight();
 		touchUp(t);
		bDidFakeSecondTouch = false;
	}
}

//--------------------------------------------------------------
void testApp::windowResized(int w, int h){

}

//--------------------------------------------------------------

void testApp::setupOsc() {
	if(!json_settings.loadFromFile("settings/OSC.json.txt")){
		cerr << "failed to load json settings file" << endl;
		_exit(1);
	}
	oscIn.setup(json_settings["osc_listen_port"].asInt());
	audioData->connect(json_settings["audio_osc_port"].asInt());

}

void testApp::processOsc() {
	while(oscIn.hasWaitingMessages()) {
		ofxOscMessage m;
		oscIn.getNextMessage(&m);
		if(m.getAddress()=="/control/mode/next") {

			//get the next mode ready
			string modeName = m.getArgAsString(0);
			nextMode = modeName;

		}else if(m.getAddress()=="/control/mode/swap") {
			mode->setMode(nextMode);

		}else if(m.getAddress()=="/control/bubble/new") {

			Donk::BubbleData::add(m);

		}else if(m.getAddress()=="/control/question/update") {

			Donk::QuestionData qd(m);
			cout << "todo: handle question update \"" << qd.text << "\" " << qd.tags[0] << "=" <<
			qd.tag_counts[0] << "," << qd.tags[1] << "=" << qd.tag_counts[1] << endl;

		}
	}
	audioData->update();
}

void testApp::setupKinect() {
	tuio.connect(json_settings["tuio_listen_port"].asInt());
	ofAddListener(ofEvents.touchDown, this, &testApp::touchDown);
	ofAddListener(ofEvents.touchUp, this, &testApp::touchUp);
	ofAddListener(ofEvents.touchMoved, this, &testApp::touchMoved);

	calibrationProjection.setInteractiveArea(&projection->getInteractiveArea());
	calibrationProjection.createGui(getCalibrationGui());

}

void testApp::touchDown(ofTouchEventArgs &touch) {
	projection->touchDown(touch.x, touch.y, touch.id);
}

void testApp::touchMoved(ofTouchEventArgs &touch) {
	projection->touchMoved(touch.x, touch.y, touch.id);
	// e.g.
	// touches are normalized
	ofVec2f pos(touch.x, touch.y);

	// now scaled for screen coords
	pos *= ofGetWindowSize();
	//printf("pos: %f %f\n", pos.x, pos.y);
}

void testApp::touchUp(ofTouchEventArgs &touch) {
	projection->touchUp(touch.x, touch.y, touch.id);
}<|endoftext|>