<commit_before>#include "ofdpa_fm_driver.hpp"
#include "ofdpa_datatypes.h"

#include <rofl/common/crofdpt.h>
#include <rofl/common/openflow/cofflowmod.h>
#include <rofl/common/protocols/fvlanframe.h>
#include <rofl/common/protocols/farpv4frame.h>

namespace basebox {

ofdpa_fm_driver::ofdpa_fm_driver(const rofl::cdptid& dptid) :
		dptid(dptid)
{
}

ofdpa_fm_driver::~ofdpa_fm_driver()
{
}

void
ofdpa_fm_driver::enable_port_pvid_ingress(uint16_t vid, uint32_t port_no)
{
	// XXX This contradicts the OF-DPA ASS (p. 64) "The VLAN_VID value cannot be used in a VLAN Filtering rule."
	// todo Send ticket to BCM to clarify
	enable_port_vid_ingress(vid, port_no);

	// check params
	assert(vid < 0x1000);
	assert(port_no);

	rofl::crofdpt& dpt = rofl::crofdpt::get_dpt(dptid);

	rofl::openflow::cofflowmod fm(dpt.get_version_negotiated());

	fm.set_command(rofl::openflow::OFPFC_ADD);
	fm.set_table_id(OFDPA_FLOW_TABLE_ID_VLAN);

	fm.set_idle_timeout(0);
	fm.set_hard_timeout(0);
	fm.set_priority(2);
	fm.set_cookie(0);

	fm.set_match().set_in_port(port_no);
	fm.set_match().set_vlan_vid(0, 0x1fff);

	fm.set_instructions().set_inst_apply_actions().set_actions().
			add_action_set_field(rofl::cindex(0)).set_oxm(rofl::openflow::coxmatch_ofb_vlan_vid(vid | rofl::openflow::OFPVID_PRESENT));

	fm.set_instructions().set_inst_goto_table().set_table_id(OFDPA_FLOW_TABLE_ID_TERMINATION_MAC);

	// XXX set vrf
	//	fm.set_instructions().set_inst_apply_actions().set_actions().add_action_set_field(
	//			rofl::cindex(0)).set_oxm(rofl::openflow::coxmatch_ofb_vrf(vid)); // currently vid == vrf

	std::cout << "write flow-mod:" << std::endl << fm;

	dpt.send_flow_mod_message(rofl::cauxid(0), fm);
}

void
ofdpa_fm_driver::enable_port_vid_ingress(uint16_t vid, uint32_t port_no)
{
	assert(vid < 0x1000);
	assert(port_no);

	rofl::crofdpt& dpt = rofl::crofdpt::get_dpt(dptid);

	rofl::openflow::cofflowmod fm(dpt.get_version_negotiated());

	fm.set_command(rofl::openflow::OFPFC_ADD); // todo check what happens if this is added two times?
	fm.set_table_id(OFDPA_FLOW_TABLE_ID_VLAN);

	fm.set_idle_timeout(0);
	fm.set_hard_timeout(0);
	fm.set_priority(3);
	fm.set_cookie(0);

	fm.set_match().set_in_port(port_no);
	fm.set_match().set_vlan_vid(vid | rofl::openflow::OFPVID_PRESENT, 0x1fff);

	fm.set_instructions().set_inst_goto_table().set_table_id(
			OFDPA_FLOW_TABLE_ID_TERMINATION_MAC);

	// XXX set vrf
//	fm.set_instructions().set_inst_apply_actions().set_actions().add_action_set_field(
//			rofl::cindex(0)).set_oxm(rofl::openflow::coxmatch_ofb_vrf(vid)); // currently vid == vrf

	std::cout << "write flow-mod:" << std::endl << fm;

	dpt.send_flow_mod_message(rofl::cauxid(0), fm);
}

uint32_t
ofdpa_fm_driver::enable_port_pvid_egress(uint16_t vid, uint32_t port_no)
{
	assert(vid < 0x1000);
	assert(port_no);

	uint32_t group_id = (0x0fff & vid) << 16 | (0xffff & port_no);

	rofl::crofdpt& dpt = rofl::crofdpt::get_dpt(dptid);
	rofl::openflow::cofgroupmod gm(dpt.get_version_negotiated());

	gm.set_command(rofl::openflow::OFPGC_ADD);
	gm.set_type(rofl::openflow::OFPGT_INDIRECT);
	gm.set_group_id(group_id);

	gm.set_buckets().add_bucket(0).set_actions().
			add_action_pop_vlan(rofl::cindex(0));
	gm.set_buckets().set_bucket(0).set_actions().
			add_action_output(rofl::cindex(1)).set_port_no(port_no);

	std::cout << "send group mod:" << std::endl << gm;

	dpt.send_group_mod_message(rofl::cauxid(0), gm);

	return group_id;
}

uint32_t
ofdpa_fm_driver::enable_group_l2_multicast(uint16_t vid, uint16_t id, const std::list<uint32_t>& l2_interfaces, bool update)
{
	assert(vid < 0x1000);

	static const uint16_t identifier = 0x1000;
	static uint16_t current_ident = 0;
	uint16_t next_ident = current_ident;
	if (update) {
		next_ident ^= identifier;
	}

	uint32_t group_id = 3 << 28 | (0x0fff & vid) << 16 | (0xffff & (id | next_ident));

	rofl::crofdpt& dpt = rofl::crofdpt::get_dpt(dptid);
	rofl::openflow::cofgroupmod gm(dpt.get_version_negotiated());

	gm.set_command(rofl::openflow::OFPGC_ADD);
	gm.set_type(rofl::openflow::OFPGT_ALL);
	gm.set_group_id(group_id);

	uint32_t bucket_id = 0;

	for (const uint32_t &i : l2_interfaces) {
		std::cout << i << ' ';

		gm.set_buckets().add_bucket(bucket_id).set_actions()
				.add_action_pop_vlan(rofl::cindex(0));
		gm.set_buckets().add_bucket(bucket_id).set_actions()
				.add_action_group(rofl::cindex(1)).set_group_id(i);

		++bucket_id;
	}
	std::cout << std::endl;

	std::cout << "send group mod:" << std::endl << gm;
	dpt.send_group_mod_message(rofl::cauxid(0), gm);

	if (update) {
		// update arp policy
		enable_policy_arp(vid, group_id, true);

		// delete old entry
		rofl::openflow::cofgroupmod gm(dpt.get_version_negotiated());

		gm.set_command(rofl::openflow::OFPGC_DELETE);
		gm.set_type(rofl::openflow::OFPGT_ALL);
		gm.set_group_id(3 << 28 | (0x0fff & vid) << 16 | (0xffff & (id | current_ident)));

		std::cout << "send gm delete" << std::endl;
		dpt.send_group_mod_message(rofl::cauxid(0), gm); // xxx this does not work currently

		current_ident = next_ident;
	}

	return group_id;
}

void
ofdpa_fm_driver::enable_bridging_dlf_vlan(uint16_t vid, uint32_t group_id, bool do_pkt_in)
{
	assert(vid < 0x1000);

	rofl::crofdpt& dpt = rofl::crofdpt::get_dpt(dptid);

	rofl::openflow::cofflowmod fm(dpt.get_version_negotiated());
	fm.set_table_id(OFDPA_FLOW_TABLE_ID_BRIDGING);

	fm.set_idle_timeout(0);
	fm.set_hard_timeout(0);
	fm.set_priority(2);
	fm.set_cookie(0);

	fm.set_match().set_vlan_vid(vid | rofl::openflow::OFPVID_PRESENT, 0x0fff);

	if (do_pkt_in) {
		fm.set_out_port(rofl::openflow::OFPP_CONTROLLER);

		fm.set_instructions().set_inst_apply_actions().set_actions().
				add_action_output(rofl::cindex(0)).set_port_no(rofl::openflow::OFPP_CONTROLLER);
	}

	// fixme not supported in this table... check with BCM
	//fm.set_instructions().set_inst_clear_actions();

	fm.set_instructions().set_inst_goto_table().set_table_id(OFDPA_FLOW_TABLE_ID_ACL_POLICY);

	std::cout << "write flow-mod:" << std::endl << fm;
	dpt.send_flow_mod_message(rofl::cauxid(0), fm);
}

void
ofdpa_fm_driver::enable_policy_arp(uint16_t vid, uint32_t group_id, bool update)
{
	assert(vid < 0x1000);

	rofl::crofdpt& dpt = rofl::crofdpt::get_dpt(dptid);
	rofl::openflow::cofflowmod fm(dpt.get_version_negotiated());
	fm.set_table_id(OFDPA_FLOW_TABLE_ID_ACL_POLICY);

	fm.set_idle_timeout(0);
	fm.set_hard_timeout(0);
	fm.set_priority(2);
	fm.set_cookie(0);

	fm.set_command(update ? rofl::openflow::OFPFC_MODIFY : rofl::openflow::OFPFC_ADD);

	fm.set_match().set_eth_dst(rofl::cmacaddr("ff:ff:ff:ff:ff:ff"));
	fm.set_match().set_eth_type(rofl::farpv4frame::ARPV4_ETHER);

	fm.set_out_port(rofl::openflow::OFPP_CONTROLLER);

	fm.set_instructions().set_inst_write_actions().set_actions()
			.add_action_group(rofl::cindex(0)).set_group_id(group_id);

	std::cout << "send flow mod:" << std::endl << fm;

	dpt.send_flow_mod_message(rofl::cauxid(0), fm);
}

void ofdpa_fm_driver::add_bridging_unicast_vlan(const rofl::cmacaddr& mac,
		uint16_t vid, uint32_t port_no)
{
	assert(vid < 0x1000);

	rofl::crofdpt& dpt = rofl::crofdpt::get_dpt(dptid);
	rofl::openflow::cofflowmod fm(dpt.get_version_negotiated());
	fm.set_table_id(OFDPA_FLOW_TABLE_ID_BRIDGING);

	fm.set_idle_timeout(0);
	fm.set_hard_timeout(0);
	fm.set_priority(2);
	fm.set_cookie(0);

	fm.set_command(rofl::openflow::OFPFC_ADD);

	fm.set_match().set_eth_dst(mac);
	fm.set_match().set_vlan_vid(vid | rofl::openflow::OFPVID_PRESENT);

	uint32_t group_id = (0x0fff & vid) << 16 | (0xffff & port_no);
	fm.set_instructions().set_inst_write_actions().set_actions()
			.add_action_group(rofl::cindex(0)).set_group_id(group_id);
	fm.set_instructions().set_inst_goto_table().set_table_id(OFDPA_FLOW_TABLE_ID_ACL_POLICY);

	std::cout << __FUNCTION__ << ": send flow mod:" << std::endl << fm;

	dpt.send_flow_mod_message(rofl::cauxid(0), fm);
}

} /* namespace basebox */
<commit_msg>prepare vrf in fm driver<commit_after>#include "ofdpa_fm_driver.hpp"
#include "ofdpa_datatypes.h"

#include <rofl/common/crofdpt.h>
#include <rofl/common/openflow/cofflowmod.h>
#include <rofl/common/openflow/openflow_common.h>
#include <rofl/common/openflow/coxmatch.h>
#include <rofl/common/protocols/fvlanframe.h>
#include <rofl/common/protocols/farpv4frame.h>

namespace basebox {

namespace ofdpa {

	static const uint32_t experimenter_id = 0x001018;

	/* OXM Flow match field types for OpenFlow Experimental */
	enum oxm_ofx_match_fields {

		OFPXMT_OFX_VRF	= 1,	/* virtual routing and forwarding */

		/* max value */
		OFPXMT_OFX_MAX,
	};

#define HAS_MASK_FLAG (1 << 8)

	/* OXM Flow match field types for OpenFlow experimenter class. */
	enum oxm_tlv_match_fields {
		OXM_TLV_EXPR_VRF			= (rofl::openflow::OFPXMC_EXPERIMENTER << 16) | (OFPXMT_OFX_VRF << 9)	|  2,
		OXM_TLV_EXPR_VRF_MASK		= (rofl::openflow::OFPXMC_EXPERIMENTER << 16) | (OFPXMT_OFX_VRF << 9)	|  4 | HAS_MASK_FLAG,
	};

}; // end of namespace ofdpa

class coxmatch_ofb_vrf : public rofl::openflow::coxmatch {
public:
	coxmatch_ofb_vrf(
			uint16_t vrf) :
				coxmatch(ofdpa::OXM_TLV_EXPR_VRF, vrf, COXMATCH_16BIT)
	{};
	coxmatch_ofb_vrf(
			uint16_t vrf, uint16_t mask) :
				coxmatch(ofdpa::OXM_TLV_EXPR_VRF_MASK, vrf, mask, COXMATCH_16BIT)
	{};
	coxmatch_ofb_vrf(
			const coxmatch& oxm) :
				coxmatch(oxm)
	{};
	virtual
	~coxmatch_ofb_vrf()
	{};
public:
	friend std::ostream&
	operator<< (std::ostream& os, const coxmatch_ofb_vrf& oxm) {
		os << dynamic_cast<const coxmatch&>(oxm);
		os << rofl::indent(2) << "<coxmatch_ofb_vlan_vid >" << std::endl;
		os << rofl::indent(4) << "<vlan-vid: 0x" << std::hex << (int)oxm.get_u16value() << "/0x" << (int)oxm.get_u16mask() << std::dec << " >" << std::endl;
		return os;
	};
};

ofdpa_fm_driver::ofdpa_fm_driver(const rofl::cdptid& dptid) :
		dptid(dptid)
{
}

ofdpa_fm_driver::~ofdpa_fm_driver()
{
}

void
ofdpa_fm_driver::enable_port_pvid_ingress(uint16_t vid, uint32_t port_no)
{
	// XXX This contradicts the OF-DPA ASS (p. 64) "The VLAN_VID value cannot be used in a VLAN Filtering rule."
	// todo Send ticket to BCM to clarify
	enable_port_vid_ingress(vid, port_no);

	// check params
	assert(vid < 0x1000);
	assert(port_no);

	rofl::crofdpt& dpt = rofl::crofdpt::get_dpt(dptid);

	rofl::openflow::cofflowmod fm(dpt.get_version_negotiated());

	fm.set_command(rofl::openflow::OFPFC_ADD);
	fm.set_table_id(OFDPA_FLOW_TABLE_ID_VLAN);

	fm.set_idle_timeout(0);
	fm.set_hard_timeout(0);
	fm.set_priority(2);
	fm.set_cookie(0);

	fm.set_match().set_in_port(port_no);
	fm.set_match().set_vlan_vid(0, 0x1fff);

	fm.set_instructions().set_inst_apply_actions().set_actions().
			add_action_set_field(rofl::cindex(0)).set_oxm(rofl::openflow::coxmatch_ofb_vlan_vid(vid | rofl::openflow::OFPVID_PRESENT));

	fm.set_instructions().set_inst_goto_table().set_table_id(OFDPA_FLOW_TABLE_ID_TERMINATION_MAC);

	// XXX set vrf
	//	fm.set_instructions().set_inst_apply_actions().set_actions().add_action_set_field(
	//			rofl::cindex(0)).set_oxm(rofl::openflow::coxmatch_ofb_vrf(vid)); // currently vid == vrf

	std::cout << "write flow-mod:" << std::endl << fm;

	dpt.send_flow_mod_message(rofl::cauxid(0), fm);
}

void
ofdpa_fm_driver::enable_port_vid_ingress(uint16_t vid, uint32_t port_no)
{
	assert(vid < 0x1000);
	assert(port_no);

	rofl::crofdpt& dpt = rofl::crofdpt::get_dpt(dptid);

	rofl::openflow::cofflowmod fm(dpt.get_version_negotiated());

	fm.set_command(rofl::openflow::OFPFC_ADD); // todo check what happens if this is added two times?
	fm.set_table_id(OFDPA_FLOW_TABLE_ID_VLAN);

	fm.set_idle_timeout(0);
	fm.set_hard_timeout(0);
	fm.set_priority(3);
	fm.set_cookie(0);

	fm.set_match().set_in_port(port_no);
	fm.set_match().set_vlan_vid(vid | rofl::openflow::OFPVID_PRESENT, 0x1fff);

	fm.set_instructions().set_inst_goto_table().set_table_id(
			OFDPA_FLOW_TABLE_ID_TERMINATION_MAC);

	// XXX set vrf
//	fm.set_instructions().set_inst_apply_actions().set_actions().add_action_set_field(
//			rofl::cindex(0)).set_oxm(rofl::openflow::coxmatch_ofb_vrf(vid)); // currently vid == vrf

	std::cout << "write flow-mod:" << std::endl << fm;

	dpt.send_flow_mod_message(rofl::cauxid(0), fm);
}

uint32_t
ofdpa_fm_driver::enable_port_pvid_egress(uint16_t vid, uint32_t port_no)
{
	assert(vid < 0x1000);
	assert(port_no);

	uint32_t group_id = (0x0fff & vid) << 16 | (0xffff & port_no);

	rofl::crofdpt& dpt = rofl::crofdpt::get_dpt(dptid);
	rofl::openflow::cofgroupmod gm(dpt.get_version_negotiated());

	gm.set_command(rofl::openflow::OFPGC_ADD);
	gm.set_type(rofl::openflow::OFPGT_INDIRECT);
	gm.set_group_id(group_id);

	gm.set_buckets().add_bucket(0).set_actions().
			add_action_pop_vlan(rofl::cindex(0));
	gm.set_buckets().set_bucket(0).set_actions().
			add_action_output(rofl::cindex(1)).set_port_no(port_no);

	std::cout << "send group mod:" << std::endl << gm;

	dpt.send_group_mod_message(rofl::cauxid(0), gm);

	return group_id;
}

uint32_t
ofdpa_fm_driver::enable_group_l2_multicast(uint16_t vid, uint16_t id, const std::list<uint32_t>& l2_interfaces, bool update)
{
	assert(vid < 0x1000);

	static const uint16_t identifier = 0x1000;
	static uint16_t current_ident = 0;
	uint16_t next_ident = current_ident;
	if (update) {
		next_ident ^= identifier;
	}

	uint32_t group_id = 3 << 28 | (0x0fff & vid) << 16 | (0xffff & (id | next_ident));

	rofl::crofdpt& dpt = rofl::crofdpt::get_dpt(dptid);
	rofl::openflow::cofgroupmod gm(dpt.get_version_negotiated());

	gm.set_command(rofl::openflow::OFPGC_ADD);
	gm.set_type(rofl::openflow::OFPGT_ALL);
	gm.set_group_id(group_id);

	uint32_t bucket_id = 0;

	for (const uint32_t &i : l2_interfaces) {
		std::cout << i << ' ';

		gm.set_buckets().add_bucket(bucket_id).set_actions()
				.add_action_pop_vlan(rofl::cindex(0));
		gm.set_buckets().add_bucket(bucket_id).set_actions()
				.add_action_group(rofl::cindex(1)).set_group_id(i);

		++bucket_id;
	}
	std::cout << std::endl;

	std::cout << "send group mod:" << std::endl << gm;
	dpt.send_group_mod_message(rofl::cauxid(0), gm);

	if (update) {
		// update arp policy
		enable_policy_arp(vid, group_id, true);

		// delete old entry
		rofl::openflow::cofgroupmod gm(dpt.get_version_negotiated());

		gm.set_command(rofl::openflow::OFPGC_DELETE);
		gm.set_type(rofl::openflow::OFPGT_ALL);
		gm.set_group_id(3 << 28 | (0x0fff & vid) << 16 | (0xffff & (id | current_ident)));

		std::cout << "send gm delete" << std::endl;
		dpt.send_group_mod_message(rofl::cauxid(0), gm); // xxx this does not work currently

		current_ident = next_ident;
	}

	return group_id;
}

void
ofdpa_fm_driver::enable_bridging_dlf_vlan(uint16_t vid, uint32_t group_id, bool do_pkt_in)
{
	assert(vid < 0x1000);

	rofl::crofdpt& dpt = rofl::crofdpt::get_dpt(dptid);

	rofl::openflow::cofflowmod fm(dpt.get_version_negotiated());
	fm.set_table_id(OFDPA_FLOW_TABLE_ID_BRIDGING);

	fm.set_idle_timeout(0);
	fm.set_hard_timeout(0);
	fm.set_priority(2);
	fm.set_cookie(0);

	fm.set_match().set_vlan_vid(vid | rofl::openflow::OFPVID_PRESENT, 0x0fff);

	if (do_pkt_in) {
		fm.set_out_port(rofl::openflow::OFPP_CONTROLLER);

		fm.set_instructions().set_inst_apply_actions().set_actions().
				add_action_output(rofl::cindex(0)).set_port_no(rofl::openflow::OFPP_CONTROLLER);
	}

	// fixme not supported in this table... check with BCM
	//fm.set_instructions().set_inst_clear_actions();

	fm.set_instructions().set_inst_goto_table().set_table_id(OFDPA_FLOW_TABLE_ID_ACL_POLICY);

	std::cout << "write flow-mod:" << std::endl << fm;
	dpt.send_flow_mod_message(rofl::cauxid(0), fm);
}

void
ofdpa_fm_driver::enable_policy_arp(uint16_t vid, uint32_t group_id, bool update)
{
	assert(vid < 0x1000);

	rofl::crofdpt& dpt = rofl::crofdpt::get_dpt(dptid);
	rofl::openflow::cofflowmod fm(dpt.get_version_negotiated());
	fm.set_table_id(OFDPA_FLOW_TABLE_ID_ACL_POLICY);

	fm.set_idle_timeout(0);
	fm.set_hard_timeout(0);
	fm.set_priority(2);
	fm.set_cookie(0);

	fm.set_command(update ? rofl::openflow::OFPFC_MODIFY : rofl::openflow::OFPFC_ADD);

	fm.set_match().set_eth_dst(rofl::cmacaddr("ff:ff:ff:ff:ff:ff"));
	fm.set_match().set_eth_type(rofl::farpv4frame::ARPV4_ETHER);

	fm.set_out_port(rofl::openflow::OFPP_CONTROLLER);

	fm.set_instructions().set_inst_write_actions().set_actions()
			.add_action_group(rofl::cindex(0)).set_group_id(group_id);

	std::cout << "send flow mod:" << std::endl << fm;

	dpt.send_flow_mod_message(rofl::cauxid(0), fm);
}

void ofdpa_fm_driver::add_bridging_unicast_vlan(const rofl::cmacaddr& mac,
		uint16_t vid, uint32_t port_no)
{
	assert(vid < 0x1000);

	rofl::crofdpt& dpt = rofl::crofdpt::get_dpt(dptid);
	rofl::openflow::cofflowmod fm(dpt.get_version_negotiated());
	fm.set_table_id(OFDPA_FLOW_TABLE_ID_BRIDGING);

	fm.set_idle_timeout(0);
	fm.set_hard_timeout(0);
	fm.set_priority(2);
	fm.set_cookie(0);

	fm.set_command(rofl::openflow::OFPFC_ADD);

	fm.set_match().set_eth_dst(mac);
	fm.set_match().set_vlan_vid(vid | rofl::openflow::OFPVID_PRESENT);

	uint32_t group_id = (0x0fff & vid) << 16 | (0xffff & port_no);
	fm.set_instructions().set_inst_write_actions().set_actions()
			.add_action_group(rofl::cindex(0)).set_group_id(group_id);
	fm.set_instructions().set_inst_goto_table().set_table_id(OFDPA_FLOW_TABLE_ID_ACL_POLICY);

	std::cout << __FUNCTION__ << ": send flow mod:" << std::endl << fm;

	dpt.send_flow_mod_message(rofl::cauxid(0), fm);
}

} /* namespace basebox */
<|endoftext|>


<commit_before>
#include "ViewFactory.h"
#include "KinectController.h"
#include "View.h"
#include "BwView.h"
#include "BwShaderView.h"
#include "ColorInvertShaderView.h"
#include "ColorDepthShaderView.h"
#include "MeshView.h"
#include "NormalMapView.h"
#include "FatSuitView.h"
#include "IdleView.h"

ViewPtr CreateView(const ViewType::Enum& type, const KinectControllerPtr& kinectController, int width, int height) {
	ViewPtr ptr;
	switch (type) {
		case ViewType::Normal:
			ptr.reset(new View(kinectController, width, height));
			break;
		case ViewType::BwView:
			ptr.reset(new BwView(kinectController, width, height));
			break;
		case ViewType::BwShaderView:
			ptr.reset(new BwShaderView(kinectController, width, height));
			break;
		case ViewType::ColorInvertShaderView:
			ptr.reset(new ColorInvertShaderView(kinectController, width, height));
			break;
		case ViewType::ColorDepthShaderView:
			ptr.reset(new ColorDepthShaderView(kinectController, width, height));
			break;
		case ViewType::MeshView:
			ptr.reset(new MeshView(kinectController, width, height));
			break;
		case ViewType::NormalMapView:
			ptr.reset(new NormalMapView(kinectController, width, height));
			break;
		case ViewType::FatSuitView:
			ptr.reset(new FatSuitView(kinectController, width, height));
			break;
		case ViewType::PointCloudView:
			ptr.reset(new MeshView(kinectController, width, height, true));
		case ViewType::Idle:
			ptr.reset(new IdleView(kinectController, width, height));
			break;
		default:
			ptr.reset(new View(kinectController, width, height));
			break;
	}

	return ptr;
}<commit_msg>view factory switch case missing break<commit_after>
#include "ViewFactory.h"
#include "KinectController.h"
#include "View.h"
#include "BwView.h"
#include "BwShaderView.h"
#include "ColorInvertShaderView.h"
#include "ColorDepthShaderView.h"
#include "MeshView.h"
#include "NormalMapView.h"
#include "FatSuitView.h"
#include "IdleView.h"

ViewPtr CreateView(const ViewType::Enum& type, const KinectControllerPtr& kinectController, int width, int height) {
	ViewPtr ptr;
	switch (type) {
		case ViewType::Normal:
			ptr.reset(new View(kinectController, width, height));
			break;
		case ViewType::BwView:
			ptr.reset(new BwView(kinectController, width, height));
			break;
		case ViewType::BwShaderView:
			ptr.reset(new BwShaderView(kinectController, width, height));
			break;
		case ViewType::ColorInvertShaderView:
			ptr.reset(new ColorInvertShaderView(kinectController, width, height));
			break;
		case ViewType::ColorDepthShaderView:
			ptr.reset(new ColorDepthShaderView(kinectController, width, height));
			break;
		case ViewType::MeshView:
			ptr.reset(new MeshView(kinectController, width, height));
			break;
		case ViewType::NormalMapView:
			ptr.reset(new NormalMapView(kinectController, width, height));
			break;
		case ViewType::FatSuitView:
			ptr.reset(new FatSuitView(kinectController, width, height));
			break;
		case ViewType::PointCloudView:
			ptr.reset(new MeshView(kinectController, width, height, true));
			break;
		case ViewType::Idle:
			ptr.reset(new IdleView(kinectController, width, height));
			break;
		default:
			ptr.reset(new View(kinectController, width, height));
			break;
	}

	return ptr;
}<|endoftext|>


<commit_before>/*
 * Copyright (c) 2008, Willow Garage, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Willow Garage, Inc. nor the names of its
 *       contributors may be used to endorse or promote products derived from
 *       this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "planning_display.h"
#include "common.h"
#include "helpers/robot.h"
#include "properties/property.h"
#include "properties/property_manager.h"

#include <ogre_tools/axes.h>

#include <urdf/URDF.h>
#include <tf/transform_listener.h>
#include <planning_models/kinematic.h>

#include <OgreSceneNode.h>
#include <OgreSceneManager.h>

namespace rviz
{

PlanningDisplay::PlanningDisplay( const std::string& name, VisualizationManager* manager )
: Display( name, manager )
, kinematic_model_( NULL )
, new_kinematic_path_( false )
, animating_path_( false )
, state_display_time_( 0.05f )
, visual_enabled_property_( NULL )
, collision_enabled_property_( NULL )
, state_display_time_property_( NULL )
, robot_description_property_( NULL )
, topic_property_( NULL )
{
  robot_ = new Robot( scene_manager_ );

  setVisualVisible( false );
  setCollisionVisible( true );
  robot_->setUserData( Ogre::Any( (void*)this ) );
}

PlanningDisplay::~PlanningDisplay()
{
  unsubscribe();

  delete robot_;
}

void PlanningDisplay::initialize( const std::string& description_param, const std::string& kinematic_path_topic )
{
  setRobotDescription( description_param );
  setTopic( kinematic_path_topic );
}

void PlanningDisplay::setRobotDescription( const std::string& description_param )
{
  description_param_ = description_param;

  if ( robot_description_property_ )
  {
    robot_description_property_->changed();
  }

  if ( isEnabled() )
  {
    load();
    causeRender();
  }
}

void PlanningDisplay::setTopic( const std::string& topic )
{
  unsubscribe();
  kinematic_path_topic_ = topic;
  subscribe();

  if ( topic_property_ )
  {
    topic_property_->changed();
  }
}

void PlanningDisplay::setStateDisplayTime( float time )
{
  state_display_time_ = time;

  if ( state_display_time_property_ )
  {
    state_display_time_property_->changed();
  }

  causeRender();
}

void PlanningDisplay::setVisualVisible( bool visible )
{
  robot_->setVisualVisible( visible );

  if ( visual_enabled_property_ )
  {
    visual_enabled_property_->changed();
  }

  causeRender();
}

void PlanningDisplay::setCollisionVisible( bool visible )
{
  robot_->setCollisionVisible( visible );

  if ( collision_enabled_property_ )
  {
    collision_enabled_property_->changed();
  }

  causeRender();
}

bool PlanningDisplay::isVisualVisible()
{
  return robot_->isVisualVisible();
}

bool PlanningDisplay::isCollisionVisible()
{
  return robot_->isCollisionVisible();
}

void PlanningDisplay::load()
{
  std::string content;
  ros_node_->getParam(description_param_, content);
  robot_desc::URDF file;
  file.loadString(content.c_str());

  robot_->load( &file );

  delete kinematic_model_;
  kinematic_model_ = new planning_models::KinematicModel();
  kinematic_model_->setVerbose( false );
  kinematic_model_->build( file );
  kinematic_model_->reduceToRobotFrame();

  robot_->update( kinematic_model_, target_frame_ );
}

void PlanningDisplay::onEnable()
{
  subscribe();

  load();
  robot_->setVisible( true );
}

void PlanningDisplay::onDisable()
{
  unsubscribe();
  robot_->setVisible( false );
}

void PlanningDisplay::subscribe()
{
  if ( !isEnabled() )
  {
    return;
  }

  if ( !kinematic_path_topic_.empty() )
  {
    ros_node_->subscribe( kinematic_path_topic_, incoming_kinematic_path_message_, &PlanningDisplay::incomingKinematicPath, this, 0 );
  }

}

void PlanningDisplay::unsubscribe()
{
  if ( !kinematic_path_topic_.empty() )
  {
    ros_node_->unsubscribe( kinematic_path_topic_, &PlanningDisplay::incomingKinematicPath, this );
  }
}

void PlanningDisplay::update( float dt )
{
  incoming_kinematic_path_message_.lock();

  if ( !animating_path_ && new_kinematic_path_ )
  {
    displaying_kinematic_path_message_ = incoming_kinematic_path_message_;

    animating_path_ = true;
    new_kinematic_path_ = false;
    current_state_ = -1;
    current_state_time_ = state_display_time_ + 1.0f;

    if (displaying_kinematic_path_message_.start_state.vals.size() > 0)
	kinematic_model_->computeTransforms(&displaying_kinematic_path_message_.start_state.vals[0]);
    robot_->update( kinematic_model_, target_frame_ );
  }

  incoming_kinematic_path_message_.unlock();

  if ( animating_path_ )
  {
    if ( current_state_time_ > state_display_time_ )
    {
      ++current_state_;

      calculateRobotPosition();

      if ( (size_t)current_state_ < displaying_kinematic_path_message_.path.get_states_size() )
      {
        int group_id = kinematic_model_->getGroupID( displaying_kinematic_path_message_.model_name );
	if (displaying_kinematic_path_message_.path.states[ current_state_ ].vals.size() > 0)
	    kinematic_model_->computeTransforms(&displaying_kinematic_path_message_.path.states[ current_state_ ].vals[0], group_id);
        robot_->update( kinematic_model_, target_frame_ );

        causeRender();
      }
      else
      {
        animating_path_ = false;
      }

      current_state_time_ = 0.0f;
    }

    current_state_time_ += dt;
  }
}

void PlanningDisplay::calculateRobotPosition()
{
  tf::Stamped<tf::Pose> pose( btTransform( btQuaternion( 0, 0, 0 ), btVector3( 0, 0, 0 ) ), ros::Time(), displaying_kinematic_path_message_.frame_id );

  if (tf_->canTransform(target_frame_, displaying_kinematic_path_message_.frame_id, ros::Time()))
  {
    try
    {
      tf_->transformPose( target_frame_, pose, pose );
    }
    catch(tf::TransformException& e)
    {
      ROS_ERROR( "Error transforming from frame '%s' to frame '%s'\n", pose.frame_id_.c_str(), target_frame_.c_str() );
    }
  }

  Ogre::Vector3 position( pose.getOrigin().x(), pose.getOrigin().y(), pose.getOrigin().z() );
  robotToOgre( position );

  btScalar yaw, pitch, roll;
  pose.getBasis().getEulerZYX( yaw, pitch, roll );
  Ogre::Matrix3 orientation;
  orientation.FromEulerAnglesYXZ( Ogre::Radian( yaw ), Ogre::Radian( pitch ), Ogre::Radian( roll ) );

  robot_->setPosition( position );
  robot_->setOrientation( orientation );
}

void PlanningDisplay::incomingKinematicPath()
{
  new_kinematic_path_ = true;
}

void PlanningDisplay::targetFrameChanged()
{
  calculateRobotPosition();
}

void PlanningDisplay::createProperties()
{
  visual_enabled_property_ = property_manager_->createProperty<BoolProperty>( "Visual Enabled", property_prefix_, boost::bind( &PlanningDisplay::isVisualVisible, this ),
                                                                               boost::bind( &PlanningDisplay::setVisualVisible, this, _1 ), parent_category_, this );
  collision_enabled_property_ = property_manager_->createProperty<BoolProperty>( "Collision Enabled", property_prefix_, boost::bind( &PlanningDisplay::isCollisionVisible, this ),
                                                                                boost::bind( &PlanningDisplay::setCollisionVisible, this, _1 ), parent_category_, this );
  state_display_time_property_ = property_manager_->createProperty<FloatProperty>( "State Display Time", property_prefix_, boost::bind( &PlanningDisplay::getStateDisplayTime, this ),
                                                                                boost::bind( &PlanningDisplay::setStateDisplayTime, this, _1 ), parent_category_, this );
  state_display_time_property_->setMin( 0.0001 );
  robot_description_property_ = property_manager_->createProperty<StringProperty>( "Robot Description", property_prefix_, boost::bind( &PlanningDisplay::getRobotDescription, this ),
                                                                                boost::bind( &PlanningDisplay::setRobotDescription, this, _1 ), parent_category_, this );
  topic_property_ = property_manager_->createProperty<ROSTopicStringProperty>( "Topic", property_prefix_, boost::bind( &PlanningDisplay::getTopic, this ),
                                                                               boost::bind( &PlanningDisplay::setTopic, this, _1 ), parent_category_, this );
  topic_property_->setMessageType(robot_msgs::DisplayKinematicPath::__s_getDataType());
}

const char* PlanningDisplay::getDescription()
{
  return "Displays a planned path given by a robot_msgs::DisplayKinematicPath message.";
}

} // namespace rviz

<commit_msg>Partially ported planning display to the mechanism model.<commit_after>/*
 * Copyright (c) 2008, Willow Garage, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Willow Garage, Inc. nor the names of its
 *       contributors may be used to endorse or promote products derived from
 *       this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "planning_display.h"
#include "common.h"
#include "helpers/robot.h"
#include "properties/property.h"
#include "properties/property_manager.h"

#include <ogre_tools/axes.h>

#include <urdf/URDF.h>
#include <tf/transform_listener.h>
#include <planning_models/kinematic.h>

#include <OgreSceneNode.h>
#include <OgreSceneManager.h>

namespace rviz
{

PlanningDisplay::PlanningDisplay( const std::string& name, VisualizationManager* manager )
: Display( name, manager )
, kinematic_model_( NULL )
, new_kinematic_path_( false )
, animating_path_( false )
, state_display_time_( 0.05f )
, visual_enabled_property_( NULL )
, collision_enabled_property_( NULL )
, state_display_time_property_( NULL )
, robot_description_property_( NULL )
, topic_property_( NULL )
{
  robot_ = new Robot( scene_manager_ );

  setVisualVisible( false );
  setCollisionVisible( true );
  robot_->setUserData( Ogre::Any( (void*)this ) );
}

PlanningDisplay::~PlanningDisplay()
{
  unsubscribe();

  delete robot_;
}

void PlanningDisplay::initialize( const std::string& description_param, const std::string& kinematic_path_topic )
{
  setRobotDescription( description_param );
  setTopic( kinematic_path_topic );
}

void PlanningDisplay::setRobotDescription( const std::string& description_param )
{
  description_param_ = description_param;

  if ( robot_description_property_ )
  {
    robot_description_property_->changed();
  }

  if ( isEnabled() )
  {
    load();
    causeRender();
  }
}

void PlanningDisplay::setTopic( const std::string& topic )
{
  unsubscribe();
  kinematic_path_topic_ = topic;
  subscribe();

  if ( topic_property_ )
  {
    topic_property_->changed();
  }
}

void PlanningDisplay::setStateDisplayTime( float time )
{
  state_display_time_ = time;

  if ( state_display_time_property_ )
  {
    state_display_time_property_->changed();
  }

  causeRender();
}

void PlanningDisplay::setVisualVisible( bool visible )
{
  robot_->setVisualVisible( visible );

  if ( visual_enabled_property_ )
  {
    visual_enabled_property_->changed();
  }

  causeRender();
}

void PlanningDisplay::setCollisionVisible( bool visible )
{
  robot_->setCollisionVisible( visible );

  if ( collision_enabled_property_ )
  {
    collision_enabled_property_->changed();
  }

  causeRender();
}

bool PlanningDisplay::isVisualVisible()
{
  return robot_->isVisualVisible();
}

bool PlanningDisplay::isCollisionVisible()
{
  return robot_->isCollisionVisible();
}

void PlanningDisplay::load()
{
  std::string content;
  ros_node_->getParam(description_param_, content);
  robot_desc::URDF file;
  file.loadString(content.c_str());

  TiXmlDocument doc;
  doc.Parse(content.c_str());
  if (!doc.RootElement())
    return;

  mechanism::Robot descr;
  descr.initXml(doc.RootElement());
  robot_->load( descr );

  delete kinematic_model_;
  kinematic_model_ = new planning_models::KinematicModel();
  kinematic_model_->setVerbose( false );
  kinematic_model_->build( file );
  kinematic_model_->reduceToRobotFrame();

  robot_->update( kinematic_model_, target_frame_ );
}

void PlanningDisplay::onEnable()
{
  subscribe();

  load();
  robot_->setVisible( true );
}

void PlanningDisplay::onDisable()
{
  unsubscribe();
  robot_->setVisible( false );
}

void PlanningDisplay::subscribe()
{
  if ( !isEnabled() )
  {
    return;
  }

  if ( !kinematic_path_topic_.empty() )
  {
    ros_node_->subscribe( kinematic_path_topic_, incoming_kinematic_path_message_, &PlanningDisplay::incomingKinematicPath, this, 0 );
  }

}

void PlanningDisplay::unsubscribe()
{
  if ( !kinematic_path_topic_.empty() )
  {
    ros_node_->unsubscribe( kinematic_path_topic_, &PlanningDisplay::incomingKinematicPath, this );
  }
}

void PlanningDisplay::update( float dt )
{
  incoming_kinematic_path_message_.lock();

  if ( !animating_path_ && new_kinematic_path_ )
  {
    displaying_kinematic_path_message_ = incoming_kinematic_path_message_;

    animating_path_ = true;
    new_kinematic_path_ = false;
    current_state_ = -1;
    current_state_time_ = state_display_time_ + 1.0f;

    if (displaying_kinematic_path_message_.start_state.vals.size() > 0)
	kinematic_model_->computeTransforms(&displaying_kinematic_path_message_.start_state.vals[0]);
    robot_->update( kinematic_model_, target_frame_ );
  }

  incoming_kinematic_path_message_.unlock();

  if ( animating_path_ )
  {
    if ( current_state_time_ > state_display_time_ )
    {
      ++current_state_;

      calculateRobotPosition();

      if ( (size_t)current_state_ < displaying_kinematic_path_message_.path.get_states_size() )
      {
        int group_id = kinematic_model_->getGroupID( displaying_kinematic_path_message_.model_name );
	if (displaying_kinematic_path_message_.path.states[ current_state_ ].vals.size() > 0)
	    kinematic_model_->computeTransforms(&displaying_kinematic_path_message_.path.states[ current_state_ ].vals[0], group_id);
        robot_->update( kinematic_model_, target_frame_ );

        causeRender();
      }
      else
      {
        animating_path_ = false;
      }

      current_state_time_ = 0.0f;
    }

    current_state_time_ += dt;
  }
}

void PlanningDisplay::calculateRobotPosition()
{
  tf::Stamped<tf::Pose> pose( btTransform( btQuaternion( 0, 0, 0 ), btVector3( 0, 0, 0 ) ), ros::Time(), displaying_kinematic_path_message_.frame_id );

  if (tf_->canTransform(target_frame_, displaying_kinematic_path_message_.frame_id, ros::Time()))
  {
    try
    {
      tf_->transformPose( target_frame_, pose, pose );
    }
    catch(tf::TransformException& e)
    {
      ROS_ERROR( "Error transforming from frame '%s' to frame '%s'\n", pose.frame_id_.c_str(), target_frame_.c_str() );
    }
  }

  Ogre::Vector3 position( pose.getOrigin().x(), pose.getOrigin().y(), pose.getOrigin().z() );
  robotToOgre( position );

  btScalar yaw, pitch, roll;
  pose.getBasis().getEulerZYX( yaw, pitch, roll );
  Ogre::Matrix3 orientation;
  orientation.FromEulerAnglesYXZ( Ogre::Radian( yaw ), Ogre::Radian( pitch ), Ogre::Radian( roll ) );

  robot_->setPosition( position );
  robot_->setOrientation( orientation );
}

void PlanningDisplay::incomingKinematicPath()
{
  new_kinematic_path_ = true;
}

void PlanningDisplay::targetFrameChanged()
{
  calculateRobotPosition();
}

void PlanningDisplay::createProperties()
{
  visual_enabled_property_ = property_manager_->createProperty<BoolProperty>( "Visual Enabled", property_prefix_, boost::bind( &PlanningDisplay::isVisualVisible, this ),
                                                                               boost::bind( &PlanningDisplay::setVisualVisible, this, _1 ), parent_category_, this );
  collision_enabled_property_ = property_manager_->createProperty<BoolProperty>( "Collision Enabled", property_prefix_, boost::bind( &PlanningDisplay::isCollisionVisible, this ),
                                                                                boost::bind( &PlanningDisplay::setCollisionVisible, this, _1 ), parent_category_, this );
  state_display_time_property_ = property_manager_->createProperty<FloatProperty>( "State Display Time", property_prefix_, boost::bind( &PlanningDisplay::getStateDisplayTime, this ),
                                                                                boost::bind( &PlanningDisplay::setStateDisplayTime, this, _1 ), parent_category_, this );
  state_display_time_property_->setMin( 0.0001 );
  robot_description_property_ = property_manager_->createProperty<StringProperty>( "Robot Description", property_prefix_, boost::bind( &PlanningDisplay::getRobotDescription, this ),
                                                                                boost::bind( &PlanningDisplay::setRobotDescription, this, _1 ), parent_category_, this );
  topic_property_ = property_manager_->createProperty<ROSTopicStringProperty>( "Topic", property_prefix_, boost::bind( &PlanningDisplay::getTopic, this ),
                                                                               boost::bind( &PlanningDisplay::setTopic, this, _1 ), parent_category_, this );
  topic_property_->setMessageType(robot_msgs::DisplayKinematicPath::__s_getDataType());
}

const char* PlanningDisplay::getDescription()
{
  return "Displays a planned path given by a robot_msgs::DisplayKinematicPath message.";
}

} // namespace rviz

<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <random>
#include <string>
#include <errno.h>

//Boost includes
#include <boost/filesystem.cpp>

using namespace std;
using namespace boost::filesystem;

//Key len in bytes (Will be encoded in hex)
static const int KEY_LEN = 256;
static const path DIR_PATH = path("/var/lib/agfs");
static const string KEY_LIST_PATH = "/var/lib/agfs/authkeys";

static const char hexValues[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};

int main(int argc, char** argv)
{
  if(argc != 6) {
    cout << "usage: agfs-keygen {host dns name/ip addr} {port} {user} {local mount point} {key file name}" << endl;
    return 0;
  }

  if(!exists(DIR_PATH)) {
    if(!create_directory(DIR_PATH)) {
      cerr << "Could not create key directory" << endl;
      return -ENOENT;
    }
  }

  fstream devRandom;
  devRandom.open("/dev/random", fstream::in);

  fstream keyListFile;
  keyListFile.open(KEY_LIST_PATH, fstream::out | fstream::app);

  if(!keyListFile.is_open()){
    cerr << "Could not open keyListFile" <<endl;
    return -ENOENT;
  }

  fstream keyFile;
  keyFile.open(argv[4], fstream::out);

  if(!keyFile.is_open()) {
    cerr << "Could not open key file: " << argv[4] << endl;
    return -ENOENT;
  }

  //put the header of the key file
  //Print DNS name and port
  keyFile << arv[1] << endl << arv[2] << endl;

  //Generate the random key
  string keyStr = "";
  size_t count = 0;

  while (count < KEY_LEN) {
    char c;
    devRandom.get(&c);
    char lowerByte, upperByte;
    lowerByte = hexValues[0xff & c];
    upperByte = hexValues[(0xff00 & c) >> 8];
    keyStr += upperByte;
    keyStr += lowerByte;
    ++count;
  }

  //print the key to the keyfile
  keyFile << keyStr << endl;

  //print mount point, uname, key to the key list file
  keyListFile << argv[4] << "," << argv[3] << "," keyStr << endl;

  //Close files
  devRandom.close();
  keyFile.close();
  keyListFile.close();

  return 0;
}
<commit_msg>Fixed afgf-keygen to put key file in the correct location and print correct hex characters as the key.<commit_after>#include <iostream>
#include <fstream>
#include <random>
#include <string>
#include <errno.h>

//Boost includes
#include <boost/filesystem.hpp>

using namespace std;
using namespace boost::filesystem;

//Key len in bytes (Will be encoded in hex)
static const int KEY_LEN = 256;
static const path DIR_PATH = path("/var/lib/agfs");
static const string KEY_NAME_PATH = "/var/lib/agfs/";
static const string KEY_EXTENSION = ".agkey";
static const string KEY_LIST_PATH = "/var/lib/agfs/authkeys";

static const char hexValues[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};

int main(int argc, char** argv)
{
  if(argc != 6) {
    cout << "usage: agfs-keygen {host dns name/ip addr} {port} {user} {local mount point} {key file name}" << endl;
    return 0;
  }

  if(!exists(DIR_PATH)) {
    if(!create_directory(DIR_PATH)) {
      cerr << "Could not create key directory" << endl;
      return -ENOENT;
    }
  }

  fstream devRandom;
  devRandom.open("/dev/urandom", fstream::in);

  fstream keyListFile;
  keyListFile.open(KEY_LIST_PATH, fstream::out | fstream::app);

  if(!keyListFile.is_open()){
    cerr << "Could not open keyListFile" <<endl;
    return -ENOENT;
  }

  fstream keyFile;
  string keyFileName = KEY_NAME_PATH + argv[5] + KEY_EXTENSION;
  keyFile.open(keyFileName, fstream::out);

  if(!keyFile.is_open()) {
    cerr << "Could not open key file: " << argv[5] << endl;
    return -ENOENT;
  }

  //put the header of the key file
  //Print DNS name and port
  keyFile << argv[1] << endl << argv[2] << endl;

  //Generate the random key
  string keyStr = "";
  size_t count = 0;

  while (count < KEY_LEN) {
    char c;
    devRandom.get(c);
    char lowerByte, upperByte;
    lowerByte = hexValues[0x0f & c];
    upperByte = hexValues[(0xf0 & c) >> 4];
    keyStr += upperByte;
    keyStr += lowerByte;
    ++count;
  }

  //print the key to the keyfile
  keyFile << keyStr << endl;

  //print mount point, uname, key to the key list file
  keyListFile << argv[4] << "," << argv[3] << "," << keyStr << endl;

  //Close files
  devRandom.close();
  keyFile.close();
  keyListFile.close();

  cerr << "Successfuly created new key file" << endl;

  return 0;
}
<|endoftext|>


<commit_before>/*******************************************************
 * Copyright (c) 2017, ArrayFire
 * All rights reserved.
 *
 * This file is distributed under 3-clause BSD license.
 * The complete license agreement can be obtained at:
 * http://arrayfire.com/licenses/BSD-3-Clause
 ********************************************************/

#include <af/dim4.hpp>
#include <af/defines.h>
#include <af/image.h>
#include <af/seq.h>
#include <err_common.hpp>
#include <backend.hpp>
#include <Array.hpp>
#include <handle.hpp>
#include <arith.hpp>
#include <canny.hpp>
#include <complex.hpp>
#include <convolve.hpp>
#include <copy.hpp>
#include <histogram.hpp>
#include <logic.hpp>
#include <sobel.hpp>
#include <transpose.hpp>
#include <unary.hpp>
#include <reduce.hpp>
#include <ireduce.hpp>
#include <tile.hpp>
#include <iota.hpp>
#include <utility>
#include <iostream>

using af::dim4;
using namespace detail;

Array<float> gradientMagnitude(const Array<float>& gx, const Array<float>& gy, const bool& isf)
{
    if (isf) {
        Array<float> gx2 = detail::abs<float, float>(gx);
        Array<float> gy2 = detail::abs<float, float>(gy);
        return detail::arithOp<float, af_add_t>(gx2, gy2, gx2.dims());
    } else {
        Array<float> gx2 = detail::arithOp<float, af_mul_t>(gx, gx, gx.dims());
        Array<float> gy2 = detail::arithOp<float, af_mul_t>(gy, gy, gy.dims());
        Array<float> sg  = detail::arithOp<float, af_add_t>(gx2, gy2, gx2.dims());
        return detail::unaryOp<float, af_sqrt_t>(sg);
    }
}

Array<float> otsuThreshold(const Array<float>& supEdges,
                           const unsigned NUM_BINS, const float maxVal)
{
    Array<uint> hist = detail::histogram<float, uint, false>(supEdges, NUM_BINS, 0, maxVal);

    const af::dim4 hDims = hist.dims();

    // reduce along histogram dimension i.e. 0th dimension
    auto totals  = reduce<af_add_t, uint, float>(hist, 0);

    // tile histogram total along 0th dimension
    auto ttotals = tile(totals, af::dim4(hDims[0]));

    // pixel frequency probabilities
    auto probability = arithOp<float, af_div_t>(cast<float, uint>(hist), ttotals, hDims);

    std::vector<af_seq> seqBegin(4, af_span);
    std::vector<af_seq> seqRest(4, af_span);

    seqBegin[0] = af_make_seq(0, hDims[0]-1, 1);
    seqRest[0] = af_make_seq(0, hDims[0]-1, 1);

    const af::dim4& iDims = supEdges.dims();

    Array<float> sigmas = detail::createEmptyArray<float>(hDims);

    for (unsigned b=0; b<(NUM_BINS-1); ++b)
    {
        seqBegin[0].end  = (double)b;
        seqRest[0].begin = (double)(b+1);

        auto frontPartition = createSubArray(probability, seqBegin, false);
        auto endPartition   = createSubArray(probability, seqRest, false);

        auto qL = reduce<af_add_t, float, float>(frontPartition, 0);
        auto qH = reduce<af_add_t, float, float>(endPartition, 0);

        const dim4 fdims(b+1, hDims[1], hDims[2], hDims[3]);
        const dim4 edims(NUM_BINS-1-b, hDims[1], hDims[2], hDims[3]);

        const dim4 tdims(1, hDims[1], hDims[2], hDims[3]);
        auto frontWeights   = iota<float>(dim4(b+1), tdims);
        auto endWeights     = iota<float>(dim4(NUM_BINS-1-b), tdims);
        auto offsetValues   = createValueArray<float>(edims, b+1);

        endWeights = arithOp<float, af_add_t>(endWeights, offsetValues, edims);
        auto __muL = arithOp<float, af_mul_t>(frontPartition, frontWeights, fdims);
        auto __muH = arithOp<float, af_mul_t>(endPartition, endWeights, edims);
        auto _muL  = reduce<af_add_t, float, float>(__muL, 0);
        auto _muH  = reduce<af_add_t, float, float>(__muH, 0);
        auto muL   = arithOp<float, af_div_t>(_muL, qL, tdims);
        auto muH   = arithOp<float, af_div_t>(_muH, qH, tdims);
        auto TWOS  = createValueArray<float>(tdims, 2.0f);
        auto diff  = arithOp<float, af_sub_t>(muL, muH, tdims);
        auto sqrd  = arithOp<float, af_pow_t>(diff, TWOS, tdims);
        auto op2   = arithOp<float, af_mul_t>(qL, qH, tdims);
        auto sigma = arithOp<float, af_mul_t>(sqrd, op2, tdims);

        std::vector<af_seq> sliceIndex(4, af_span);
        sliceIndex[0] = {double(b), double(b), 1};

        auto binRes = createSubArray<float>(sigmas, sliceIndex, false);

        copyArray<float>(binRes, sigma);
    }

    dim4 odims = sigmas.dims();
    odims[0] = 1;
    Array<float> thresh = createEmptyArray<float>(odims);
    Array<uint> locs    = createEmptyArray<uint>(odims);

    ireduce<af_max_t, float>(thresh, locs, sigmas, 0);

    return cast<float, uint>(tile(locs, dim4(iDims[0], iDims[1], 1, 1)));
}

Array<float> normalize(const Array<float>& supEdges, const float minVal, const float maxVal)
{
    auto minArray = createValueArray<float>(supEdges.dims(), minVal);
    auto diff     = arithOp<float, af_sub_t>(supEdges, minArray, supEdges.dims());
    auto denom    = createValueArray<float>(supEdges.dims(), (maxVal-minVal));
    return arithOp<float, af_div_t>(diff, denom, supEdges.dims());
}

std::pair< Array<char>, Array<char> >
computeCandidates(const Array<float>& supEdges, const float t1,
                  const af_canny_threshold ct, const float t2)
{
    float maxVal = detail::reduce_all<af_max_t, float, float>(supEdges);
    const unsigned NUM_BINS = static_cast<unsigned>(maxVal);

    auto lowRatio = createValueArray<float>(supEdges.dims(), t1);

    switch(ct)
    {
        case AF_AUTO_OTSU_THRESHOLD:
            {
                auto T2            = otsuThreshold(supEdges, NUM_BINS, maxVal);
                auto T1            = arithOp<float, af_mul_t>(T2, lowRatio, T2.dims());
                Array<char> weak1  = logicOp<float, af_ge_t >(supEdges,    T1, supEdges.dims());
                Array<char> weak2  = logicOp<float, af_lt_t >(supEdges,    T2, supEdges.dims());
                Array<char> weak   = logicOp<char , af_and_t>(   weak1, weak2,    weak1.dims());
                Array<char> strong = logicOp<float, af_ge_t >(supEdges,    T2, supEdges.dims());
                return std::make_pair(strong, weak);
            };
        default:
            {
                float minVal       = detail::reduce_all<af_min_t, float, float>(supEdges);
                auto normG         = normalize(supEdges, minVal, maxVal);
                auto T2            = createValueArray<float>(supEdges.dims(), t2);
                auto T1            = createValueArray<float>(supEdges.dims(), t1);
                Array<char> weak1  = logicOp<float, af_ge_t >(normG,    T1, normG.dims());
                Array<char> weak2  = logicOp<float, af_lt_t >(normG,    T2, normG.dims());
                Array<char> weak   = logicOp<char , af_and_t>(weak1, weak2, weak1.dims());
                Array<char> strong = logicOp<float, af_ge_t >(normG,    T2, normG.dims());
                return std::make_pair(strong, weak);
            };
    }
}

template<typename T>
af_array cannyHelper(const Array<T> in, const float t1, const af_canny_threshold ct,
                     const float t2, const unsigned sw, const bool isf)
{
    static const std::vector<float> v = {-0.11021, -0.23691, -0.30576, -0.23691, -0.11021};
    Array<float> cFilter= detail::createHostDataArray<float>(dim4(5, 1), v.data());
    Array<float> rFilter= detail::createHostDataArray<float>(dim4(1, 5), v.data());

    // Run separable convolution to smooth the input image
    Array<float> smt = detail::convolve2<float, float, false>(cast<float, T>(in), cFilter, rFilter);

    auto g  = detail::sobelDerivatives<float, float>(smt, sw);
    Array<float> gx = g.first;
    Array<float> gy = g.second;

    Array<float> gmag = gradientMagnitude(gx, gy, isf);

    Array<float> supEdges = detail::nonMaximumSuppression(gmag, gx, gy);

    auto swpair = computeCandidates(supEdges, t1, ct, t2);

    return getHandle(detail::edgeTrackingByHysteresis(swpair.first, swpair.second));
}

af_err af_canny(af_array* out, const af_array in, const af_canny_threshold ct,
                const float t1, const float t2, const unsigned sw, const bool isf)
{
    try {
        const ArrayInfo& info = getInfo(in);
        af::dim4 dims  = info.dims();

        DIM_ASSERT(2, (dims.ndims() >= 2));
        // Input should be a minimum of 5x5 image
        // since the gaussian filter used for smoothing
        // the input is of 5x5 size. It's not mandatory but
        // it is essentially of no use if image is less than 5x5
        DIM_ASSERT(2, (dims[0]>=5 && dims[1]>=5));
        ARG_ASSERT(5, (sw==3));

        af_array output;

        af_dtype type  = info.getType();
        switch(type) {
            case f32: output = cannyHelper<float >(getArray<float >(in), t1, ct, t2, sw, isf); break;
            case f64: output = cannyHelper<double>(getArray<double>(in), t1, ct, t2, sw, isf); break;
            case s32: output = cannyHelper<int   >(getArray<int   >(in), t1, ct, t2, sw, isf); break;
            case u32: output = cannyHelper<uint  >(getArray<uint  >(in), t1, ct, t2, sw, isf); break;
            case s16: output = cannyHelper<short >(getArray<short >(in), t1, ct, t2, sw, isf); break;
            case u16: output = cannyHelper<ushort>(getArray<ushort>(in), t1, ct, t2, sw, isf); break;
            case u8:  output = cannyHelper<uchar >(getArray<uchar >(in), t1, ct, t2, sw, isf); break;
            default : TYPE_ERROR(1, type);
        }
        // output array is binary array
        std::swap(output, *out);
    }
    CATCHALL;

    return AF_SUCCESS;
}
<commit_msg>Fix narrowing error/warning in canny<commit_after>/*******************************************************
 * Copyright (c) 2017, ArrayFire
 * All rights reserved.
 *
 * This file is distributed under 3-clause BSD license.
 * The complete license agreement can be obtained at:
 * http://arrayfire.com/licenses/BSD-3-Clause
 ********************************************************/

#include <af/dim4.hpp>
#include <af/defines.h>
#include <af/image.h>
#include <af/seq.h>
#include <err_common.hpp>
#include <backend.hpp>
#include <Array.hpp>
#include <handle.hpp>
#include <arith.hpp>
#include <canny.hpp>
#include <complex.hpp>
#include <convolve.hpp>
#include <copy.hpp>
#include <histogram.hpp>
#include <logic.hpp>
#include <sobel.hpp>
#include <transpose.hpp>
#include <unary.hpp>
#include <reduce.hpp>
#include <ireduce.hpp>
#include <tile.hpp>
#include <iota.hpp>
#include <utility>
#include <iostream>

using af::dim4;
using namespace detail;

Array<float> gradientMagnitude(const Array<float>& gx, const Array<float>& gy, const bool& isf)
{
    if (isf) {
        Array<float> gx2 = detail::abs<float, float>(gx);
        Array<float> gy2 = detail::abs<float, float>(gy);
        return detail::arithOp<float, af_add_t>(gx2, gy2, gx2.dims());
    } else {
        Array<float> gx2 = detail::arithOp<float, af_mul_t>(gx, gx, gx.dims());
        Array<float> gy2 = detail::arithOp<float, af_mul_t>(gy, gy, gy.dims());
        Array<float> sg  = detail::arithOp<float, af_add_t>(gx2, gy2, gx2.dims());
        return detail::unaryOp<float, af_sqrt_t>(sg);
    }
}

Array<float> otsuThreshold(const Array<float>& supEdges,
                           const unsigned NUM_BINS, const float maxVal)
{
    Array<uint> hist = detail::histogram<float, uint, false>(supEdges, NUM_BINS, 0, maxVal);

    const af::dim4 hDims = hist.dims();

    // reduce along histogram dimension i.e. 0th dimension
    auto totals  = reduce<af_add_t, uint, float>(hist, 0);

    // tile histogram total along 0th dimension
    auto ttotals = tile(totals, af::dim4(hDims[0]));

    // pixel frequency probabilities
    auto probability = arithOp<float, af_div_t>(cast<float, uint>(hist), ttotals, hDims);

    std::vector<af_seq> seqBegin(4, af_span);
    std::vector<af_seq> seqRest(4, af_span);

    seqBegin[0] = af_make_seq(0, hDims[0]-1, 1);
    seqRest[0] = af_make_seq(0, hDims[0]-1, 1);

    const af::dim4& iDims = supEdges.dims();

    Array<float> sigmas = detail::createEmptyArray<float>(hDims);

    for (unsigned b=0; b<(NUM_BINS-1); ++b)
    {
        seqBegin[0].end  = (double)b;
        seqRest[0].begin = (double)(b+1);

        auto frontPartition = createSubArray(probability, seqBegin, false);
        auto endPartition   = createSubArray(probability, seqRest, false);

        auto qL = reduce<af_add_t, float, float>(frontPartition, 0);
        auto qH = reduce<af_add_t, float, float>(endPartition, 0);

        const dim4 fdims(b+1, hDims[1], hDims[2], hDims[3]);
        const dim4 edims(NUM_BINS-1-b, hDims[1], hDims[2], hDims[3]);

        const dim4 tdims(1, hDims[1], hDims[2], hDims[3]);
        auto frontWeights   = iota<float>(dim4(b+1), tdims);
        auto endWeights     = iota<float>(dim4(NUM_BINS-1-b), tdims);
        auto offsetValues   = createValueArray<float>(edims, b+1);

        endWeights = arithOp<float, af_add_t>(endWeights, offsetValues, edims);
        auto __muL = arithOp<float, af_mul_t>(frontPartition, frontWeights, fdims);
        auto __muH = arithOp<float, af_mul_t>(endPartition, endWeights, edims);
        auto _muL  = reduce<af_add_t, float, float>(__muL, 0);
        auto _muH  = reduce<af_add_t, float, float>(__muH, 0);
        auto muL   = arithOp<float, af_div_t>(_muL, qL, tdims);
        auto muH   = arithOp<float, af_div_t>(_muH, qH, tdims);
        auto TWOS  = createValueArray<float>(tdims, 2.0f);
        auto diff  = arithOp<float, af_sub_t>(muL, muH, tdims);
        auto sqrd  = arithOp<float, af_pow_t>(diff, TWOS, tdims);
        auto op2   = arithOp<float, af_mul_t>(qL, qH, tdims);
        auto sigma = arithOp<float, af_mul_t>(sqrd, op2, tdims);

        std::vector<af_seq> sliceIndex(4, af_span);
        sliceIndex[0] = {double(b), double(b), 1};

        auto binRes = createSubArray<float>(sigmas, sliceIndex, false);

        copyArray<float>(binRes, sigma);
    }

    dim4 odims = sigmas.dims();
    odims[0] = 1;
    Array<float> thresh = createEmptyArray<float>(odims);
    Array<uint> locs    = createEmptyArray<uint>(odims);

    ireduce<af_max_t, float>(thresh, locs, sigmas, 0);

    return cast<float, uint>(tile(locs, dim4(iDims[0], iDims[1], 1, 1)));
}

Array<float> normalize(const Array<float>& supEdges, const float minVal, const float maxVal)
{
    auto minArray = createValueArray<float>(supEdges.dims(), minVal);
    auto diff     = arithOp<float, af_sub_t>(supEdges, minArray, supEdges.dims());
    auto denom    = createValueArray<float>(supEdges.dims(), (maxVal-minVal));
    return arithOp<float, af_div_t>(diff, denom, supEdges.dims());
}

std::pair< Array<char>, Array<char> >
computeCandidates(const Array<float>& supEdges, const float t1,
                  const af_canny_threshold ct, const float t2)
{
    float maxVal = detail::reduce_all<af_max_t, float, float>(supEdges);
    const unsigned NUM_BINS = static_cast<unsigned>(maxVal);

    auto lowRatio = createValueArray<float>(supEdges.dims(), t1);

    switch(ct)
    {
        case AF_AUTO_OTSU_THRESHOLD:
            {
                auto T2            = otsuThreshold(supEdges, NUM_BINS, maxVal);
                auto T1            = arithOp<float, af_mul_t>(T2, lowRatio, T2.dims());
                Array<char> weak1  = logicOp<float, af_ge_t >(supEdges,    T1, supEdges.dims());
                Array<char> weak2  = logicOp<float, af_lt_t >(supEdges,    T2, supEdges.dims());
                Array<char> weak   = logicOp<char , af_and_t>(   weak1, weak2,    weak1.dims());
                Array<char> strong = logicOp<float, af_ge_t >(supEdges,    T2, supEdges.dims());
                return std::make_pair(strong, weak);
            };
        default:
            {
                float minVal       = detail::reduce_all<af_min_t, float, float>(supEdges);
                auto normG         = normalize(supEdges, minVal, maxVal);
                auto T2            = createValueArray<float>(supEdges.dims(), t2);
                auto T1            = createValueArray<float>(supEdges.dims(), t1);
                Array<char> weak1  = logicOp<float, af_ge_t >(normG,    T1, normG.dims());
                Array<char> weak2  = logicOp<float, af_lt_t >(normG,    T2, normG.dims());
                Array<char> weak   = logicOp<char , af_and_t>(weak1, weak2, weak1.dims());
                Array<char> strong = logicOp<float, af_ge_t >(normG,    T2, normG.dims());
                return std::make_pair(strong, weak);
            };
    }
}

template<typename T>
af_array cannyHelper(const Array<T> in, const float t1, const af_canny_threshold ct,
                     const float t2, const unsigned sw, const bool isf)
{
    static const std::vector<float> v = {-0.11021f, -0.23691f, -0.30576f, -0.23691f, -0.11021f};
    Array<float> cFilter= detail::createHostDataArray<float>(dim4(5, 1), v.data());
    Array<float> rFilter= detail::createHostDataArray<float>(dim4(1, 5), v.data());

    // Run separable convolution to smooth the input image
    Array<float> smt = detail::convolve2<float, float, false>(cast<float, T>(in), cFilter, rFilter);

    auto g  = detail::sobelDerivatives<float, float>(smt, sw);
    Array<float> gx = g.first;
    Array<float> gy = g.second;

    Array<float> gmag = gradientMagnitude(gx, gy, isf);

    Array<float> supEdges = detail::nonMaximumSuppression(gmag, gx, gy);

    auto swpair = computeCandidates(supEdges, t1, ct, t2);

    return getHandle(detail::edgeTrackingByHysteresis(swpair.first, swpair.second));
}

af_err af_canny(af_array* out, const af_array in, const af_canny_threshold ct,
                const float t1, const float t2, const unsigned sw, const bool isf)
{
    try {
        const ArrayInfo& info = getInfo(in);
        af::dim4 dims  = info.dims();

        DIM_ASSERT(2, (dims.ndims() >= 2));
        // Input should be a minimum of 5x5 image
        // since the gaussian filter used for smoothing
        // the input is of 5x5 size. It's not mandatory but
        // it is essentially of no use if image is less than 5x5
        DIM_ASSERT(2, (dims[0]>=5 && dims[1]>=5));
        ARG_ASSERT(5, (sw==3));

        af_array output;

        af_dtype type  = info.getType();
        switch(type) {
            case f32: output = cannyHelper<float >(getArray<float >(in), t1, ct, t2, sw, isf); break;
            case f64: output = cannyHelper<double>(getArray<double>(in), t1, ct, t2, sw, isf); break;
            case s32: output = cannyHelper<int   >(getArray<int   >(in), t1, ct, t2, sw, isf); break;
            case u32: output = cannyHelper<uint  >(getArray<uint  >(in), t1, ct, t2, sw, isf); break;
            case s16: output = cannyHelper<short >(getArray<short >(in), t1, ct, t2, sw, isf); break;
            case u16: output = cannyHelper<ushort>(getArray<ushort>(in), t1, ct, t2, sw, isf); break;
            case u8:  output = cannyHelper<uchar >(getArray<uchar >(in), t1, ct, t2, sw, isf); break;
            default : TYPE_ERROR(1, type);
        }
        // output array is binary array
        std::swap(output, *out);
    }
    CATCHALL;

    return AF_SUCCESS;
}
<|endoftext|>


<commit_before>#include "battle_room/application.h"

#include "battle_room/common/input_gatherer.h"
#include "battle_room/common/application_message_receiver.h"
#include "battle_room/game/query_world.h"
#include "battle_room/game/objects/object_factory.h"
#include "battle_room/user_interface/interface_factory.h"
#include "battle_room/networking/world_updater_factory.h"

#include <thread>
#include <algorithm>

namespace BattleRoom {

    void sortByViewLayer(std::vector<ViewInterface *> &interfaces, ResourceDescriptor settings);

    Application::Application(ResourceDescriptor settings) {

        m_windows.clear();
        m_viewInterfaces.clear();

        applySettings(settings);
    }

    void Application::runApplicationLoop() {

        while (!ApplicationMessageReceiver::containsQuitEvent()) {

            // get inputs from last frame
            for (UniqueDisplayWindow &window : m_windows) {
                window->gatherInputs();
            }
            Inputs inputs = InputGatherer::getAndClearInputs();

            ///// start game interface thread
            std::thread interfaceThread([this, &inputs]() {

                    // Handle inputs view interfaces
                    for (const auto& interface : m_viewInterfaces) {
                    inputs = interface->handleInputs(inputs);
                    }

                    // Update world for client
                    QueryWorld::updateBuffer();

                    // get any settings that need to be applied to windows
                    ResourceDescriptor settings;
                    for (const auto& interface : m_viewInterfaces) {
                    settings.addSubResources(interface->getNewSettings());
                    }
                    for (UniqueDisplayWindow &window : m_windows) {
                    window->applySettings(settings);
                    }

                    // Prepare objects for display
                    for (const auto& interface : m_viewInterfaces) {

                        UniqueId associatedView = interface->getAssociatedView();
                        std::vector<DrawableObject> objects = interface->getDrawableObjects();
                        std::vector<DrawableText> texts = interface->getDrawableTexts();
                        std::vector<DrawableMenu> menus = interface->getDrawableMenus();

                        for (UniqueDisplayWindow &window : m_windows) {
                            window->addViewObjects(objects, associatedView);
                            window->addViewTexts(texts, associatedView);
                            window->addViewMenus(menus, associatedView);
                        }
                    }

                    // Handle inputs for windows
                    for (UniqueDisplayWindow &window : m_windows) {
                        inputs = window->handleInputs(inputs);
                    }

                    // prevents the CPU from railing
                    std::this_thread::sleep_for(std::chrono::milliseconds(25));

            });
            ////// End game interface thread

            ///// Start Drawing "thread" - must be on main thread
            for (UniqueDisplayWindow &window : m_windows) {
                window->drawScreen();
            }
            //// End drawing "thread"

            interfaceThread.join();

            // Switch buffers that view objects and texts are written to
            for (UniqueDisplayWindow &window : m_windows) {
                window->switchBuffers();
            }

            // apply application message
            std::vector<ApplicationMessage> messages = ApplicationMessageReceiver::getAndClearMessages();
            for (auto& message : messages) {
                applyMessage(message);
            }
        }
    }

    void Application::applySettings(ResourceDescriptor settings) {

        ObjectFactory::applySettings(settings.getSubResource("ObjectTemplates"));

        // Create the world updater - empty if startup menu, or a server connection,
        // or a local updater
        m_worldUpdater = WorldUpdaterFactory::createWorldUpdater(settings.getSubResource("WorldUpdater"));

        // Create the windows for displaying - including view/camera setup in each
        for (ResourceDescriptor window : settings.getSubResources("Window")) {
            addResource(window);
        }

        for (ResourceDescriptor sub : settings.getSubResources("Interface")) {
            addResource(sub);
        }

        for (ResourceDescriptor sub : settings.getSubResources("MenuInterface")) {
            addResource(sub);
        }
        //sortByViewLayer(m_viewInterfaces, settings);
    }

    template <typename T> T findIn(std::vector<T>& vec, UniqueId target) {

        auto res = std::find_if(vec.begin(), vec.end(),
             [target](const T v) -> bool { return v->getUniqueId() == target; });

        return res != vec.end() ? *res : nullptr;
    }

    template <typename R> R* findUniqueIn(std::vector<std::unique_ptr<R>>& vec, UniqueId target) {
        for (const auto& v : vec) {
            if (v->getUniqueId() == target) {
                return v.get();
            }
        }
        return nullptr;
    }

    DisplayWindow* findWindow(std::vector<UniqueDisplayWindow>& vec, std::string val) {

        if (isEmpty(val)) {
            return nullptr;
        }

        UniqueId id = UniqueId::fromString(val);

        if (id.isValid()) {
            for (const auto& w : vec) {
                if (w->getUniqueId() == id) {
                    return w.get();
                }
            }
        }

        for (const auto& w : vec) {
            if (keyMatch(w->getName(), val)) {
                return w.get();
            }
        }

        return nullptr;
    }

    void Application::addResource(ResourceDescriptor settings) {

        // TODO add an interface factory
        if (keyMatch("Window", settings.getKey())) {
            m_windows.push_back(createDisplayWindow(settings));
        } else if (keyMatch("Interface", settings.getKey())) {

            ResourceDescriptor sub = settings.getSubResource("Window");
            DisplayWindow* window = findWindow(m_windows, sub.getValue());
            if (window) {
                m_viewInterfaces.push_back(InterfaceFactory::createInterface(settings, window->addView(settings)));
            }
        }
    }

    void Application::modifyResource(UniqueId target, ResourceDescriptor settings) {

        Resource* resource = findUniqueIn(m_viewInterfaces, target);

        if (!resource) {
            resource = findUniqueIn(m_windows, target);
        }

        if (!resource && m_worldUpdater && m_worldUpdater->getUniqueId() == target) {
            resource = m_worldUpdater.get();
        }

        // apply
        if (resource) {
            resource->applySettings(settings);
        }
    }

    void Application::removeResource(UniqueId target) {

        auto res = std::find_if(m_viewInterfaces.begin(), m_viewInterfaces.end(),
             [target](const UniqueInterface& v) -> bool { return v->getUniqueId() == target; });
        if (res != m_viewInterfaces.end()) {
            m_viewInterfaces.erase(res);
        }

        auto win = std::find_if(m_windows.begin(), m_windows.end(),
             [target](const UniqueDisplayWindow& v) -> bool { return v->getUniqueId() == target; });
        if (win != m_windows.end()) {
            m_windows.erase(win);
        }

        if (m_worldUpdater && m_worldUpdater->getUniqueId() == target) {
            m_worldUpdater = nullptr;
        }
    }

    void Application::applyMessage(ApplicationMessage message) {

        if (ApplicationMessage::Type::Add == message.getType()) {
            addResource(message.getSettings());

        } else if (ApplicationMessage::Type::Modify == message.getType()) {
            modifyResource(message.getTarget(), message.getSettings());

        } else if (ApplicationMessage::Type::Remove == message.getType()) {
            removeResource(message.getTarget());

        }
    }

//    void sortByViewLayer(std::vector<ViewInterface *> &interfaces, ResourceDescriptor settings) {
//
//        // create a map of view names to view layers
//        std::unordered_map<std::string, int> viewLayerMap;
//        for (ResourceDescriptor window : settings.getSubResources("Window")) {
//            for (ResourceDescriptor view : window.getSubResources("View")) {
//                int viewLayer = 0;
//                if (isNotEmpty(view.getSubResource("Layer").getValue())) {
//                    viewLayer = std::stoi(view.getSubResource("Layer").getValue());
//                }
//
//                viewLayerMap.insert(std::make_pair(view.getValue(), viewLayer));
//            }
//        }
//
//        // sort by created map
//        std::sort(interfaces.begin(), interfaces.end(),
//                [&viewLayerMap](ViewInterface *a, ViewInterface *b) {
//
//                int aLayer = 0, bLayer = 0;
//                if (viewLayerMap.count(a->getAssociatedView()) > 0) {
//                aLayer = viewLayerMap.at(a->getAssociatedView());
//                }
//                if (viewLayerMap.count(b->getAssociatedView()) > 0) {
//                bLayer = viewLayerMap.at(b->getAssociatedView());
//                }
//                return aLayer < bLayer;
//                }
//                );
//    }

} // BattleRoom namespace
<commit_msg>Removed old interface comment.<commit_after>#include "battle_room/application.h"

#include "battle_room/common/input_gatherer.h"
#include "battle_room/common/application_message_receiver.h"
#include "battle_room/game/query_world.h"
#include "battle_room/game/objects/object_factory.h"
#include "battle_room/user_interface/interface_factory.h"
#include "battle_room/networking/world_updater_factory.h"

#include <thread>
#include <algorithm>

namespace BattleRoom {

    void sortByViewLayer(std::vector<ViewInterface *> &interfaces, ResourceDescriptor settings);

    Application::Application(ResourceDescriptor settings) {

        m_windows.clear();
        m_viewInterfaces.clear();

        applySettings(settings);
    }

    void Application::runApplicationLoop() {

        while (!ApplicationMessageReceiver::containsQuitEvent()) {

            // get inputs from last frame
            for (UniqueDisplayWindow &window : m_windows) {
                window->gatherInputs();
            }
            Inputs inputs = InputGatherer::getAndClearInputs();

            ///// start game interface thread
            std::thread interfaceThread([this, &inputs]() {

                    // Handle inputs view interfaces
                    for (const auto& interface : m_viewInterfaces) {
                    inputs = interface->handleInputs(inputs);
                    }

                    // Update world for client
                    QueryWorld::updateBuffer();

                    // get any settings that need to be applied to windows
                    ResourceDescriptor settings;
                    for (const auto& interface : m_viewInterfaces) {
                    settings.addSubResources(interface->getNewSettings());
                    }
                    for (UniqueDisplayWindow &window : m_windows) {
                    window->applySettings(settings);
                    }

                    // Prepare objects for display
                    for (const auto& interface : m_viewInterfaces) {

                        UniqueId associatedView = interface->getAssociatedView();
                        std::vector<DrawableObject> objects = interface->getDrawableObjects();
                        std::vector<DrawableText> texts = interface->getDrawableTexts();
                        std::vector<DrawableMenu> menus = interface->getDrawableMenus();

                        for (UniqueDisplayWindow &window : m_windows) {
                            window->addViewObjects(objects, associatedView);
                            window->addViewTexts(texts, associatedView);
                            window->addViewMenus(menus, associatedView);
                        }
                    }

                    // Handle inputs for windows
                    for (UniqueDisplayWindow &window : m_windows) {
                        inputs = window->handleInputs(inputs);
                    }

                    // prevents the CPU from railing
                    std::this_thread::sleep_for(std::chrono::milliseconds(25));

            });
            ////// End game interface thread

            ///// Start Drawing "thread" - must be on main thread
            for (UniqueDisplayWindow &window : m_windows) {
                window->drawScreen();
            }
            //// End drawing "thread"

            interfaceThread.join();

            // Switch buffers that view objects and texts are written to
            for (UniqueDisplayWindow &window : m_windows) {
                window->switchBuffers();
            }

            // apply application message
            std::vector<ApplicationMessage> messages = ApplicationMessageReceiver::getAndClearMessages();
            for (auto& message : messages) {
                applyMessage(message);
            }
        }
    }

    void Application::applySettings(ResourceDescriptor settings) {

        ObjectFactory::applySettings(settings.getSubResource("ObjectTemplates"));

        // Create the world updater - empty if startup menu, or a server connection,
        // or a local updater
        m_worldUpdater = WorldUpdaterFactory::createWorldUpdater(settings.getSubResource("WorldUpdater"));

        // Create the windows for displaying - including view/camera setup in each
        for (ResourceDescriptor window : settings.getSubResources("Window")) {
            addResource(window);
        }

        for (ResourceDescriptor sub : settings.getSubResources("Interface")) {
            addResource(sub);
        }
        //sortByViewLayer(m_viewInterfaces, settings);
    }

    template <typename T> T findIn(std::vector<T>& vec, UniqueId target) {

        auto res = std::find_if(vec.begin(), vec.end(),
             [target](const T v) -> bool { return v->getUniqueId() == target; });

        return res != vec.end() ? *res : nullptr;
    }

    template <typename R> R* findUniqueIn(std::vector<std::unique_ptr<R>>& vec, UniqueId target) {
        for (const auto& v : vec) {
            if (v->getUniqueId() == target) {
                return v.get();
            }
        }
        return nullptr;
    }

    DisplayWindow* findWindow(std::vector<UniqueDisplayWindow>& vec, std::string val) {

        if (isEmpty(val)) {
            return nullptr;
        }

        UniqueId id = UniqueId::fromString(val);

        if (id.isValid()) {
            for (const auto& w : vec) {
                if (w->getUniqueId() == id) {
                    return w.get();
                }
            }
        }

        for (const auto& w : vec) {
            if (keyMatch(w->getName(), val)) {
                return w.get();
            }
        }

        return nullptr;
    }

    void Application::addResource(ResourceDescriptor settings) {

        if (keyMatch("Window", settings.getKey())) {
            m_windows.push_back(createDisplayWindow(settings));
        } else if (keyMatch("Interface", settings.getKey())) {

            ResourceDescriptor sub = settings.getSubResource("Window");
            DisplayWindow* window = findWindow(m_windows, sub.getValue());
            if (window) {
                m_viewInterfaces.push_back(InterfaceFactory::createInterface(settings, window->addView(settings)));
            }
        }
    }

    void Application::modifyResource(UniqueId target, ResourceDescriptor settings) {

        Resource* resource = findUniqueIn(m_viewInterfaces, target);

        if (!resource) {
            resource = findUniqueIn(m_windows, target);
        }

        if (!resource && m_worldUpdater && m_worldUpdater->getUniqueId() == target) {
            resource = m_worldUpdater.get();
        }

        // apply
        if (resource) {
            resource->applySettings(settings);
        }
    }

    void Application::removeResource(UniqueId target) {

        auto res = std::find_if(m_viewInterfaces.begin(), m_viewInterfaces.end(),
             [target](const UniqueInterface& v) -> bool { return v->getUniqueId() == target; });
        if (res != m_viewInterfaces.end()) {
            m_viewInterfaces.erase(res);
        }

        auto win = std::find_if(m_windows.begin(), m_windows.end(),
             [target](const UniqueDisplayWindow& v) -> bool { return v->getUniqueId() == target; });
        if (win != m_windows.end()) {
            m_windows.erase(win);
        }

        if (m_worldUpdater && m_worldUpdater->getUniqueId() == target) {
            m_worldUpdater = nullptr;
        }
    }

    void Application::applyMessage(ApplicationMessage message) {

        if (ApplicationMessage::Type::Add == message.getType()) {
            addResource(message.getSettings());

        } else if (ApplicationMessage::Type::Modify == message.getType()) {
            modifyResource(message.getTarget(), message.getSettings());

        } else if (ApplicationMessage::Type::Remove == message.getType()) {
            removeResource(message.getTarget());

        }
    }

//    void sortByViewLayer(std::vector<ViewInterface *> &interfaces, ResourceDescriptor settings) {
//
//        // create a map of view names to view layers
//        std::unordered_map<std::string, int> viewLayerMap;
//        for (ResourceDescriptor window : settings.getSubResources("Window")) {
//            for (ResourceDescriptor view : window.getSubResources("View")) {
//                int viewLayer = 0;
//                if (isNotEmpty(view.getSubResource("Layer").getValue())) {
//                    viewLayer = std::stoi(view.getSubResource("Layer").getValue());
//                }
//
//                viewLayerMap.insert(std::make_pair(view.getValue(), viewLayer));
//            }
//        }
//
//        // sort by created map
//        std::sort(interfaces.begin(), interfaces.end(),
//                [&viewLayerMap](ViewInterface *a, ViewInterface *b) {
//
//                int aLayer = 0, bLayer = 0;
//                if (viewLayerMap.count(a->getAssociatedView()) > 0) {
//                aLayer = viewLayerMap.at(a->getAssociatedView());
//                }
//                if (viewLayerMap.count(b->getAssociatedView()) > 0) {
//                bLayer = viewLayerMap.at(b->getAssociatedView());
//                }
//                return aLayer < bLayer;
//                }
//                );
//    }

} // BattleRoom namespace
<|endoftext|>