<commit_before>/*ckwg +5
 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
 * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
 * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
 */

#include "process.h"
#include "process_exception.h"

#include "config.h"
#include "datum.h"
#include "edge.h"
#include "stamp.h"
#include "types.h"

#include <boost/algorithm/string/predicate.hpp>
#include <boost/foreach.hpp>

#include <utility>

/**
 * \file process.cxx
 *
 * \brief Implementation of the base class for \link vistk::process processes\endlink.
 */

namespace vistk
{

process::port_t const process::port_heartbeat = port_t("heartbeat");
config::key_t const process::config_name = config::key_t("_name");
config::key_t const process::config_type = config::key_t("_type");
process::port_type_t const process::type_any = port_type_t("_any");
process::port_type_t const process::type_none = port_type_t("_none");
process::port_flag_t const process::flag_output_const = port_flag_t("_const");
process::port_flag_t const process::flag_input_mutable = port_flag_t("_mutable");
process::port_flag_t const process::flag_required = port_flag_t("_required");

process::port_info
::port_info(port_type_t const& type,
            port_flags_t const& flags,
            port_description_t const& description)
  : type(type)
  , flags(flags)
  , description(description)
{
}

process::port_info
::~port_info()
{
}

process::conf_info
::conf_info(config::value_t const& def,
              config::description_t const& description)
  : def(def)
  , description(description)
{
}

process::conf_info
::~conf_info()
{
}

class process::priv
{
  public:
    priv();
    ~priv();

    void run_heartbeat();

    name_t name;
    process_registry::type_t type;

    typedef std::pair<edge_t, edge_t> edge_pair_t;
    typedef std::map<port_t, edge_pair_t> edge_map_t;

    edges_t heartbeats;

    edges_t input_edges;
    edges_t output_edges;

    bool is_complete;

    stamp_t hb_stamp;

    static config::value_t const DEFAULT_PROCESS_NAME;
};

config::key_t const process::priv::DEFAULT_PROCESS_NAME = "(unnamed)";

void
process
::init()
{
  process::_init();
}

void
process
::step()
{
  /// \todo Make reentrant.

  /// \todo Are there any pre-_step actions?

  if (d->is_complete)
  {
    /// \todo What exactly should be done here?
  }
  else
  {
    _step();
  }

  /// \todo Are there any post-_step actions?

  d->run_heartbeat();
}

bool
process
::is_reentrant() const
{
  return false;
}

void
process
::connect_input_port(port_t const& port, edge_t edge)
{
  if (!edge)
  {
    throw null_edge_port_connection_exception(d->name, port);
  }

  _connect_input_port(port, edge);
}

void
process
::connect_output_port(port_t const& port, edge_t edge)
{
  if (!edge)
  {
    throw null_edge_port_connection_exception(d->name, port);
  }

  if (port == port_heartbeat)
  {
    d->heartbeats.push_back(edge);

    return;
  }

  _connect_output_port(port, edge);
}

process::ports_t
process
::input_ports() const
{
  ports_t ports = _input_ports();

  return ports;
}

process::ports_t
process
::output_ports() const
{
  ports_t ports = _output_ports();

  ports.push_back(port_heartbeat);

  return ports;
}

process::port_info_t
process
::input_port_info(port_t const& port) const
{
  return _input_port_info(port);
}

process::port_info_t
process
::output_port_info(port_t const& port) const
{
  if (port == port_heartbeat)
  {
    return port_info_t(new port_info(
      type_none,
      port_flags_t(),
      port_description_t("Outputs the heartbeat stamp with an empty datum")));
  }

  return _output_port_info(port);
}

config::keys_t
process
::available_config() const
{
  config::keys_t keys = _available_config();

  keys.push_back(config_name);
  keys.push_back(config_type);

  return keys;
}

process::conf_info_t
process
::config_info(config::key_t const& key) const
{
  if (key == config_name)
  {
    return conf_info_t(new conf_info(
      boost::lexical_cast<config::value_t>(priv::DEFAULT_PROCESS_NAME),
      config::description_t("The name of the process")));
  }
  if (key == config_type)
  {
    return conf_info_t(new conf_info(
      config::value_t(),
      config::description_t("The type of the process")));
  }

  return _config_info(key);
}

process::name_t
process
::name() const
{
  return d->name;
}

process_registry::type_t
process
::type() const
{
  return d->type;
}

process
::process(config_t const& config) throw()
{
  d = boost::shared_ptr<priv>(new priv);

  d->name = config->get_value<name_t>(config_name, priv::DEFAULT_PROCESS_NAME);
  d->type = config->get_value<name_t>(config_type);
}

process
::~process()
{
}

void
process
::_init()
{
}

void
process
::_step()
{
}

void
process
::_connect_input_port(port_t const& port, edge_t /*edge*/)
{
  throw no_such_port_exception(d->name, port);
}

void
process
::_connect_output_port(port_t const& port, edge_t /*edge*/)
{
  throw no_such_port_exception(d->name, port);
}

process::ports_t
process
::_input_ports() const
{
  return ports_t();
}

process::ports_t
process
::_output_ports() const
{
  return ports_t();
}

process::port_info_t
process
::_input_port_info(port_t const& port) const
{
  throw no_such_port_exception(d->name, port);
}

process::port_info_t
process
::_output_port_info(port_t const& port) const
{
  throw no_such_port_exception(d->name, port);
}

config::keys_t
process
::_available_config() const
{
  return config::keys_t();
}

process::conf_info_t
process
::_config_info(config::key_t const& key) const
{
  throw unknown_configuration_value_exception(d->name, key);
}

void
process
::mark_as_complete()
{
  d->is_complete = true;
}

stamp_t
process
::heartbeat_stamp() const
{
  return d->hb_stamp;
}

bool
process
::same_colored_edges(edges_t const& edges)
{
  edges_t::const_iterator it = edges.begin();
  edges_t::const_iterator it_end = edges.end();

  for ( ; it != it_end; ++it)
  {
    edges_t::const_iterator it2 = it;

    stamp_t const st = (*it)->peek_datum().get<1>();

    for (++it2; it2 != it_end; ++it2)
    {
      if (!st->is_same_color((*it2)->peek_datum().get<1>()))
      {
        return false;
      }
    }
  }

  return true;
}

bool
process
::syncd_edges(edges_t const& edges)
{
  edges_t::const_iterator it = edges.begin();
  edges_t::const_iterator it_end = edges.end();

  for ( ; it != it_end; ++it)
  {
    edges_t::const_iterator it2 = it;

    stamp_t const st = (*it)->peek_datum().get<1>();

    for (++it2; it2 != it_end; ++it2)
    {
      stamp_t const st2 = (*it2)->peek_datum().get<1>();

      if (*st != *st2)
      {
        return false;
      }
    }
  }

  return true;
}

datum::datum_type_t
process
::max_status(edge_data_t const& data)
{
  datum::datum_type_t max_type = datum::DATUM_INVALID;

  BOOST_FOREACH (edge_datum_t const& dat, data)
  {
    datum::datum_type_t const type = dat.get<0>()->type();

    if (max_type < type)
    {
      max_type = type;
    }
  }

  return max_type;
}

void
process
::push_to_edges(edges_t const& edges, edge_datum_t const& dat)
{
  BOOST_FOREACH (edge_t e, edges)
  {
    e->push_datum(dat);
  }
}

process::priv
::priv()
  : is_complete(false)
  , hb_stamp(stamp::new_stamp())
{
}

process::priv
::~priv()
{
}

void
process::priv
::run_heartbeat()
{
  datum_t dat;

  if (is_complete)
  {
    dat = datum::complete_datum();
  }
  else
  {
    dat = datum::empty_datum();
  }

  edge_datum_t edge_dat(dat, hb_stamp);

  hb_stamp = stamp::incremented_stamp(hb_stamp);

  edges_t::iterator hb = heartbeats.begin();
  edges_t::iterator hb_end = heartbeats.end();

  for ( ; hb != hb_end; ++hb)
  {
    (*hb)->push_datum(edge_dat);
  }
}

}
<commit_msg>Store the port an conf info once<commit_after>/*ckwg +5
 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
 * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
 * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
 */

#include "process.h"
#include "process_exception.h"

#include "config.h"
#include "datum.h"
#include "edge.h"
#include "stamp.h"
#include "types.h"

#include <boost/algorithm/string/predicate.hpp>
#include <boost/foreach.hpp>

#include <utility>

/**
 * \file process.cxx
 *
 * \brief Implementation of the base class for \link vistk::process processes\endlink.
 */

namespace vistk
{

process::port_t const process::port_heartbeat = port_t("heartbeat");
config::key_t const process::config_name = config::key_t("_name");
config::key_t const process::config_type = config::key_t("_type");
process::port_type_t const process::type_any = port_type_t("_any");
process::port_type_t const process::type_none = port_type_t("_none");
process::port_flag_t const process::flag_output_const = port_flag_t("_const");
process::port_flag_t const process::flag_input_mutable = port_flag_t("_mutable");
process::port_flag_t const process::flag_required = port_flag_t("_required");

process::port_info
::port_info(port_type_t const& type,
            port_flags_t const& flags,
            port_description_t const& description)
  : type(type)
  , flags(flags)
  , description(description)
{
}

process::port_info
::~port_info()
{
}

process::conf_info
::conf_info(config::value_t const& def,
              config::description_t const& description)
  : def(def)
  , description(description)
{
}

process::conf_info
::~conf_info()
{
}

class process::priv
{
  public:
    priv();
    ~priv();

    void run_heartbeat();

    name_t name;
    process_registry::type_t type;

    conf_info_t name_conf_info;
    conf_info_t type_conf_info;

    typedef std::pair<edge_t, edge_t> edge_pair_t;
    typedef std::map<port_t, edge_pair_t> edge_map_t;

    edges_t heartbeats;

    port_info_t heartbeat_port_info;

    edges_t input_edges;
    edges_t output_edges;

    bool is_complete;

    stamp_t hb_stamp;

    static config::value_t const DEFAULT_PROCESS_NAME;
};

config::key_t const process::priv::DEFAULT_PROCESS_NAME = "(unnamed)";

void
process
::init()
{
  process::_init();
}

void
process
::step()
{
  /// \todo Make reentrant.

  /// \todo Are there any pre-_step actions?

  if (d->is_complete)
  {
    /// \todo What exactly should be done here?
  }
  else
  {
    _step();
  }

  /// \todo Are there any post-_step actions?

  d->run_heartbeat();
}

bool
process
::is_reentrant() const
{
  return false;
}

void
process
::connect_input_port(port_t const& port, edge_t edge)
{
  if (!edge)
  {
    throw null_edge_port_connection_exception(d->name, port);
  }

  _connect_input_port(port, edge);
}

void
process
::connect_output_port(port_t const& port, edge_t edge)
{
  if (!edge)
  {
    throw null_edge_port_connection_exception(d->name, port);
  }

  if (port == port_heartbeat)
  {
    d->heartbeats.push_back(edge);

    return;
  }

  _connect_output_port(port, edge);
}

process::ports_t
process
::input_ports() const
{
  ports_t ports = _input_ports();

  return ports;
}

process::ports_t
process
::output_ports() const
{
  ports_t ports = _output_ports();

  ports.push_back(port_heartbeat);

  return ports;
}

process::port_info_t
process
::input_port_info(port_t const& port) const
{
  return _input_port_info(port);
}

process::port_info_t
process
::output_port_info(port_t const& port) const
{
  if (port == port_heartbeat)
  {
    return d->heartbeat_port_info;
  }

  return _output_port_info(port);
}

config::keys_t
process
::available_config() const
{
  config::keys_t keys = _available_config();

  keys.push_back(config_name);
  keys.push_back(config_type);

  return keys;
}

process::conf_info_t
process
::config_info(config::key_t const& key) const
{
  if (key == config_name)
  {
    return d->name_conf_info;
  }
  if (key == config_type)
  {
    return d->type_conf_info;
  }

  return _config_info(key);
}

process::name_t
process
::name() const
{
  return d->name;
}

process_registry::type_t
process
::type() const
{
  return d->type;
}

process
::process(config_t const& config) throw()
{
  d = boost::shared_ptr<priv>(new priv);

  d->name = config->get_value<name_t>(config_name, priv::DEFAULT_PROCESS_NAME);
  d->type = config->get_value<name_t>(config_type);
}

process
::~process()
{
}

void
process
::_init()
{
}

void
process
::_step()
{
}

void
process
::_connect_input_port(port_t const& port, edge_t /*edge*/)
{
  throw no_such_port_exception(d->name, port);
}

void
process
::_connect_output_port(port_t const& port, edge_t /*edge*/)
{
  throw no_such_port_exception(d->name, port);
}

process::ports_t
process
::_input_ports() const
{
  return ports_t();
}

process::ports_t
process
::_output_ports() const
{
  return ports_t();
}

process::port_info_t
process
::_input_port_info(port_t const& port) const
{
  throw no_such_port_exception(d->name, port);
}

process::port_info_t
process
::_output_port_info(port_t const& port) const
{
  throw no_such_port_exception(d->name, port);
}

config::keys_t
process
::_available_config() const
{
  return config::keys_t();
}

process::conf_info_t
process
::_config_info(config::key_t const& key) const
{
  throw unknown_configuration_value_exception(d->name, key);
}

void
process
::mark_as_complete()
{
  d->is_complete = true;
}

stamp_t
process
::heartbeat_stamp() const
{
  return d->hb_stamp;
}

bool
process
::same_colored_edges(edges_t const& edges)
{
  edges_t::const_iterator it = edges.begin();
  edges_t::const_iterator it_end = edges.end();

  for ( ; it != it_end; ++it)
  {
    edges_t::const_iterator it2 = it;

    stamp_t const st = (*it)->peek_datum().get<1>();

    for (++it2; it2 != it_end; ++it2)
    {
      if (!st->is_same_color((*it2)->peek_datum().get<1>()))
      {
        return false;
      }
    }
  }

  return true;
}

bool
process
::syncd_edges(edges_t const& edges)
{
  edges_t::const_iterator it = edges.begin();
  edges_t::const_iterator it_end = edges.end();

  for ( ; it != it_end; ++it)
  {
    edges_t::const_iterator it2 = it;

    stamp_t const st = (*it)->peek_datum().get<1>();

    for (++it2; it2 != it_end; ++it2)
    {
      stamp_t const st2 = (*it2)->peek_datum().get<1>();

      if (*st != *st2)
      {
        return false;
      }
    }
  }

  return true;
}

datum::datum_type_t
process
::max_status(edge_data_t const& data)
{
  datum::datum_type_t max_type = datum::DATUM_INVALID;

  BOOST_FOREACH (edge_datum_t const& dat, data)
  {
    datum::datum_type_t const type = dat.get<0>()->type();

    if (max_type < type)
    {
      max_type = type;
    }
  }

  return max_type;
}

void
process
::push_to_edges(edges_t const& edges, edge_datum_t const& dat)
{
  BOOST_FOREACH (edge_t e, edges)
  {
    e->push_datum(dat);
  }
}

process::priv
::priv()
  : is_complete(false)
  , hb_stamp(stamp::new_stamp())
{
  heartbeat_port_info = port_info_t(new port_info(
    type_none,
    port_flags_t(),
    port_description_t("Outputs the heartbeat stamp with an empty datum")));

  name_conf_info = conf_info_t(new conf_info(
    boost::lexical_cast<config::value_t>(priv::DEFAULT_PROCESS_NAME),
    config::description_t("The name of the process")));
  type_conf_info = conf_info_t(new conf_info(
    config::value_t(),
    config::description_t("The type of the process")));
}

process::priv
::~priv()
{
}

void
process::priv
::run_heartbeat()
{
  datum_t dat;

  if (is_complete)
  {
    dat = datum::complete_datum();
  }
  else
  {
    dat = datum::empty_datum();
  }

  edge_datum_t edge_dat(dat, hb_stamp);

  hb_stamp = stamp::incremented_stamp(hb_stamp);

  edges_t::iterator hb = heartbeats.begin();
  edges_t::iterator hb_end = heartbeats.end();

  for ( ; hb != hb_end; ++hb)
  {
    (*hb)->push_datum(edge_dat);
  }
}

}
<|endoftext|>


<commit_before>#pragma once

#include <string>
#include <typeinfo>
#include <vector>
#include <functional>
#include <SFML/Graphics.hpp>
#include <kaguya/kaguya.hpp>

#include "DataParser.hpp"

namespace mse
{
	namespace System
	{
		namespace Loaders
		{
			extern std::function<int(sf::Texture*, std::string)> textureLoader;
			extern std::function<int(Data::DataParser*, std::string)> dataLoader;
			extern std::function<int(sf::Font*, std::string)> fontLoader;
			extern std::function<int(std::vector<std::string>*, std::string)> dirPathLoader;
			extern std::function<int(std::vector<std::string>*, std::string)> filePathLoader;
			extern std::function<int(kaguya::State*, std::string)> luaLoader;
		}
		class Path
		{
			private:
				std::string path;
			public:
				Path();
				Path(const Path& path);
				Path(std::string path);
				Path add(std::string path);
				std::string getPath(int index);
				std::string toString() const;
				template<typename R>
				bool Path::checkType(R type, std::string expectedType);
				template <typename R, typename F>
				std::string loadResource(R* resource, F lambda, bool silent = false);
				static std::vector<std::string> basePaths;
		};
		template<typename R>
		inline bool Path::checkType(R type, std::string expectedType)
		{
			return (std::string(typeid(R).name()) == expectedType);
		}
		template<typename R, typename F>
		inline std::string Path::loadResource(R* resource, F lambda, bool silent)
		{
			int loadSum = 0;
			for (int i = 0; i < basePaths.size(); i++)
			{
				int loadResponse = 0;
				if (Functions::File::fileExists(basePaths[i] + ((basePaths[i] != "") ? "/" : "") + this->path))
					loadResponse = lambda(resource, basePaths[i] + ((basePaths[i] != "") ? "/" : "") + this->path);
				loadSum += loadResponse;
				if (loadResponse == 1)
					return basePaths[i];
			}
			if (loadSum > 0)
				return "*";
			else
			{
				if (silent)
					std::cout << "<Error:PathResolver:Path>[loadResource] : Can't find resource : " << this->path << std::endl;
				return "";
			}
		}
	}
}
<commit_msg>Removed extra qualification (PathResolver)<commit_after>#pragma once

#include <string>
#include <typeinfo>
#include <vector>
#include <functional>
#include <SFML/Graphics.hpp>
#include <kaguya/kaguya.hpp>

#include "DataParser.hpp"

namespace mse
{
	namespace System
	{
		namespace Loaders
		{
			extern std::function<int(sf::Texture*, std::string)> textureLoader;
			extern std::function<int(Data::DataParser*, std::string)> dataLoader;
			extern std::function<int(sf::Font*, std::string)> fontLoader;
			extern std::function<int(std::vector<std::string>*, std::string)> dirPathLoader;
			extern std::function<int(std::vector<std::string>*, std::string)> filePathLoader;
			extern std::function<int(kaguya::State*, std::string)> luaLoader;
		}
		class Path
		{
			private:
				std::string path;
			public:
				Path();
				Path(const Path& path);
				Path(std::string path);
				Path add(std::string path);
				std::string getPath(int index);
				std::string toString() const;
				template<typename R>
				bool checkType(R type, std::string expectedType);
				template <typename R, typename F>
				std::string loadResource(R* resource, F lambda, bool silent = false);
				static std::vector<std::string> basePaths;
		};
		template<typename R>
		inline bool Path::checkType(R type, std::string expectedType)
		{
			return (std::string(typeid(R).name()) == expectedType);
		}
		template<typename R, typename F>
		inline std::string Path::loadResource(R* resource, F lambda, bool silent)
		{
			int loadSum = 0;
			for (int i = 0; i < basePaths.size(); i++)
			{
				int loadResponse = 0;
				if (Functions::File::fileExists(basePaths[i] + ((basePaths[i] != "") ? "/" : "") + this->path))
					loadResponse = lambda(resource, basePaths[i] + ((basePaths[i] != "") ? "/" : "") + this->path);
				loadSum += loadResponse;
				if (loadResponse == 1)
					return basePaths[i];
			}
			if (loadSum > 0)
				return "*";
			else
			{
				if (silent)
					std::cout << "<Error:PathResolver:Path>[loadResource] : Can't find resource : " << this->path << std::endl;
				return "";
			}
		}
	}
}
<|endoftext|>


<commit_before>/*
 * MultilevelLayouter.cpp
 *
 *  Created on: 27.01.2014
 *      Author: Henning
 */

#include "MultilevelLayouter.h"

namespace NetworKit {

const count MultilevelLayouter::N_THRSH = 15;

MultilevelLayouter::MultilevelLayouter(Point<float> bottomLeft, Point<float> topRight):
		Layouter(bottomLeft, topRight)
{

}

MultilevelLayouter::~MultilevelLayouter() {

}

void MultilevelLayouter::prolongCoordinates(Graph& Gcon, Graph& G) {

}

void MultilevelLayouter::draw(Graph& G) {
	count n = G.numberOfNodes();

	if (n <= N_THRSH) {
		// unrecursive part: call drawing routine
		FruchtermanReingold layouter(bottomLeft, topRight, false);
		layouter.draw(G);
	}
	else {
		// compute matching
		LocalMaxMatcher matcher(none);
		Matching M = matcher.run(G);

		// coarsen by matching
		MatchingContracter contracter;
		std::pair<Graph, NodeMap<node> > mypair = contracter.run(G, M, true);
		Graph& Gcon = mypair.first;
		NodeMap<node>& mapping = mypair.second;

		// make recursive call
		draw(Gcon);

		// apply recursive solution to current graph
		Gcon.initCoordinates();
		G.forNodes([&](node v) {
			G.setCoordinate(v, 0, Gcon.getCoordinate(mapping[v], 0));
			G.setCoordinate(v, 1, Gcon.getCoordinate(mapping[v], 1));
		});

		// run drawing code on current graph
		FruchtermanReingold layouter(bottomLeft, topRight, true);
		layouter.draw(G);
	}

}

} /* namespace NetworKit */
<commit_msg>multilevel drawing, still buggy<commit_after>/*
 * MultilevelLayouter.cpp
 *
 *  Created on: 27.01.2014
 *      Author: Henning
 */

#include "MultilevelLayouter.h"

namespace NetworKit {

const count MultilevelLayouter::N_THRSH = 15;

MultilevelLayouter::MultilevelLayouter(Point<float> bottomLeft, Point<float> topRight):
		Layouter(bottomLeft, topRight)
{

}

MultilevelLayouter::~MultilevelLayouter() {

}

void MultilevelLayouter::prolongCoordinates(Graph& Gcon, Graph& G) {

}

void MultilevelLayouter::draw(Graph& G) {
	count n = G.numberOfNodes();

	if (n <= N_THRSH) {
		// unrecursive part: call drawing routine
		FruchtermanReingold layouter(bottomLeft, topRight, false);
		layouter.draw(G);
	}
	else {
		// compute matching
		LocalMaxMatcher matcher(none);
		Matching M = matcher.run(G);

		// coarsen by matching
		MatchingContracter contracter;
		std::pair<Graph, NodeMap<node> > mypair = contracter.run(G, M, true);
		Graph& Gcon = mypair.first;
		NodeMap<node>& mapping = mypair.second;

		// make recursive call
		draw(Gcon);

		// apply recursive solution to current graph
		G.initCoordinates();
		G.forNodes([&](node v) {
			G.setCoordinate(v, 0, Gcon.getCoordinate(mapping[v], 0));
			G.setCoordinate(v, 1, Gcon.getCoordinate(mapping[v], 1));
		});

		// run drawing code on current graph
		FruchtermanReingold layouter(bottomLeft, topRight, true);
		layouter.draw(G);
	}

}

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


<commit_before>//
// TcpASIOServer.hh for LibNet in /home/alexmog/projets/LibNet/include
//
// Made by Moghrabi Alexandre
// Login   <alexandre.moghrabi@epitech.eu>
//
// Started on  Sat Nov 15 18:00:03 2014 Moghrabi Alexandre
// Last update Tue Nov 18 09:28:53 2014 Moghrabi Alexandre
//

/*!
 * \file TcpASIOServer.hh
 * \brief Gère les threads d'écriture et de lecture
 * \author AlexMog
 * \version 0.1
 */

#ifndef TCPASIOSERVER_HH_
# define TCPASIOSERVER_HH_

# include <list>
# include "TcpServerSocket.hh"
# include "TcpASIOListener.hh"
# include "TcpASIOWriter.hh"

namespace mognetwork
{
  /*!
   * \class TcpASIOServer
   * \brief Gère les threads d'écriture et de lecture en ASIO
   */
  class TcpASIOServer
  {
  public:
    /*!
     * \brief Constructeur par défaut
     * \param port Le port sur lequel le serveur écoute
     */
    TcpASIOServer(int port);
    virtual ~TcpASIOServer();

  public:
    /*!
     * \brief Démarre les différents threads, et attends qu'ils se terminent.
     */
    void start();
    /*!
     * \brief Arrête le thread de lecture et d'écriture.
     */
    void stop();
    /*!
     * \brief Ajoute un listener au serveur.
     * \param listener le listener en question en utilisant ITcpASIOListenerHandler
     */
    void addListener(ITcpASIOListenerHandler* listener) {m_serverListener->addListener(listener);}
    /*!
     * \brief Dans le cas ou une socket client contient des données à envoyer, met à jour le thread d'écriture
     */
    void sendPendingDatas() {m_serverWriter->triggerData();}

  private:
    TcpASIOListener* m_serverListener; /*!< instance du thread d'écoute */
    TcpServerSocket m_serverSocket; /*!< socket serveur */
    TcpASIOWriter* m_serverWriter; /*!< instance du thread d'écriture */
    int m_port; /*!< port d'écoute du serveur */
  };
} // namespace mognetwork

#endif // !TCPASIOSERVER_HH_
<commit_msg>Added some getters and setters<commit_after>//
// TcpASIOServer.hh for LibNet in /home/alexmog/projets/LibNet/include
//
// Made by Moghrabi Alexandre
// Login   <alexandre.moghrabi@epitech.eu>
//
// Started on  Sat Nov 15 18:00:03 2014 Moghrabi Alexandre
// Last update Tue Nov 18 12:45:22 2014 Moghrabi Alexandre
//

/*!
 * \file TcpASIOServer.hh
 * \brief Gère les threads d'écriture et de lecture
 * \author AlexMog
 * \version 0.1
 */

#ifndef TCPASIOSERVER_HH_
# define TCPASIOSERVER_HH_

# include <list>
# include "TcpServerSocket.hh"
# include "TcpASIOListener.hh"
# include "TcpASIOWriter.hh"

namespace mognetwork
{
  /*!
   * \class TcpASIOServer
   * \brief Gère les threads d'écriture et de lecture en ASIO
   */
  class TcpASIOServer
  {
  public:
    /*!
     * \brief Constructeur par défaut
     * \param port Le port sur lequel le serveur écoute
     */
    TcpASIOServer(int port);
    virtual ~TcpASIOServer();

  public:
    /*!
     * \brief Démarre les différents threads, et attends qu'ils se terminent.
     */
    void start();
    /*!
     * \brief Arrête le thread de lecture et d'écriture.
     */
    void stop();
    /*!
     * \brief Ajoute un listener au serveur.
     * \param listener le listener en question en utilisant ITcpASIOListenerHandler
     */
    void addListener(ITcpASIOListenerHandler* listener) {m_serverListener->addListener(listener);}
    /*!
     * \brief Dans le cas ou une socket client contient des données à envoyer, met à jour le thread d'écriture
     */
    void sendPendingDatas() {m_serverWriter->triggerData();}

  public:
    /*!
     * \brief Récupère le writer TcpASIOWriter
     * \return un pointeur sur le TcpASIOWriter
     */
    TcpASIOWriter* getServerWriter() const {return m_serverWriter;}
    /*!
     * \brief Récupère le listener TcpASIOListener
     * \return un pointeur sur le TcpASIOWriter
     */
    TcpASIOListener* getServerListener() const {return m_serverListener;}

  private:
    TcpASIOListener* m_serverListener; /*!< instance du thread d'écoute */
    TcpServerSocket m_serverSocket; /*!< socket serveur */
    TcpASIOWriter* m_serverWriter; /*!< instance du thread d'écriture */
    int m_port; /*!< port d'écoute du serveur */
  };
} // namespace mognetwork

#endif // !TCPASIOSERVER_HH_
<|endoftext|>


<commit_before>#include "sani/resource/compiler/resource_writer.hpp"
#include "sani/platform/platform_config.hpp"
#include "sani/platform/file/file_stream.hpp"
#include "sani/resource/compiler/resource_compiler.hpp"

namespace sani {
	using namespace io;
	namespace resource {
		namespace compiler {
			// DO NOT CHANGE THESE, THEY ARE FOLLOWING THE PLATFORM CONFIG
			const char ResourceWriter::Platforms[] = {
				'w', // win32
				'l', // linux
				'X', // MAC
				'a', // android
				'W', // windows phone
				'i' // iOS
				// TODO emscripte, ps4, xbox
			};

			ResourceWriter::ResourceWriter(const FileStream* stream, const ResourceCompiler* compiler)
				: BinaryWriter(stream), compiler(compiler) {

			}
			ResourceWriter::~ResourceWriter() {}

			void ResourceWriter::writeHeader() {
#if SANI_TARGET_PLATFORM == SANI_PLATFORM_UNKOWN
#error "Couldnt determine the platform"
#endif
				// magic 3 bytes
				write('S');
				write('N');
				write('B');

				// platform
				write(Platforms[SANI_TARGET_PLATFORM]);
				// version, is this needed?
				write(Version);
			}

			void ResourceWriter::writeTypeWriters() {
				write7BitEncodedInt(writers.size());
				for (auto& kv : writers) {
					write(kv.second->getRuntimeReader());
				}
			}

			ResourceTypeWriter* ResourceWriter::getWriter(const std::type_index& info) {
				// we dont have writer yet lets add it
				if (writers.find(info) == writers.end()) {
					ResourceTypeWriter* w = compiler->getWriter(info);
					writers[info] = w;
					return w;
				}
				// we have the typewriter already
				return writers[info];
			}

			void ResourceWriter::writeObject(const std::type_index& type, const ResourceItem* obj) {
				if (obj == nullptr) {
					throw std::runtime_error("obj is nullptr");
				}
				ResourceTypeWriter* writer = getWriter(type);
				if (writer == nullptr) {
					throw std::runtime_error("Cant get writer for T");
				}
				writer->write(this, obj);
			}

			void ResourceWriter::flush(const std::type_index& type, const ResourceItem* obj) {
				// this is hax, just so we have the writer in list...
				getWriter(type);
				// write the header..
				writeHeader();
				// write the readers to deserialize
				writeTypeWriters();
				// write the final object..
				writeObject(type, obj);

				BinaryWriter::flush();
			}
		}
	}
}<commit_msg>Write bytes instead of int32's<commit_after>#include "sani/resource/compiler/resource_writer.hpp"
#include "sani/platform/platform_config.hpp"
#include "sani/platform/file/file_stream.hpp"
#include "sani/resource/compiler/resource_compiler.hpp"

namespace sani {
	using namespace io;
	namespace resource {
		namespace compiler {
			// DO NOT CHANGE THESE, THEY ARE FOLLOWING THE PLATFORM CONFIG
			const char ResourceWriter::Platforms[] = {
				'w', // win32
				'l', // linux
				'X', // MAC
				'a', // android
				'W', // windows phone
				'i' // iOS
				// TODO emscripte, ps4, xbox
			};

			ResourceWriter::ResourceWriter(const FileStream* stream, const ResourceCompiler* compiler)
				: BinaryWriter(stream), compiler(compiler) {

			}
			ResourceWriter::~ResourceWriter() {}

			void ResourceWriter::writeHeader() {
#if SANI_TARGET_PLATFORM == SANI_PLATFORM_UNKOWN
#error "Couldnt determine the platform"
#endif
				// magic 3 bytes
				write((uint8)'S');
				write((uint8)'N');
				write((uint8)'B');

				// platform
				write(Platforms[SANI_TARGET_PLATFORM]);
				// version, is this needed?
				write(Version);
			}

			void ResourceWriter::writeTypeWriters() {
				write7BitEncodedInt(writers.size());
				for (auto& kv : writers) {
					write(kv.second->getRuntimeReader());
				}
			}

			ResourceTypeWriter* ResourceWriter::getWriter(const std::type_index& info) {
				// we dont have writer yet lets add it
				if (writers.find(info) == writers.end()) {
					ResourceTypeWriter* w = compiler->getWriter(info);
					writers[info] = w;
					return w;
				}
				// we have the typewriter already
				return writers[info];
			}

			void ResourceWriter::writeObject(const std::type_index& type, const ResourceItem* obj) {
				if (obj == nullptr) {
					throw std::runtime_error("obj is nullptr");
				}
				ResourceTypeWriter* writer = getWriter(type);
				if (writer == nullptr) {
					throw std::runtime_error("Cant get writer for T");
				}
				writer->write(this, obj);
			}

			void ResourceWriter::flush(const std::type_index& type, const ResourceItem* obj) {
				// this is hax, just so we have the writer in list...
				getWriter(type);
				// write the header..
				writeHeader();
				// write the readers to deserialize
				writeTypeWriters();
				// write the final object..
				writeObject(type, obj);

				BinaryWriter::flush();
			}
		}
	}
}<|endoftext|>


<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, development version     *
*                (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                               SOFA :: Modules                               *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#include <SofaConstraint/FreeMotionAnimationLoop.h>
#include <sofa/core/visual/VisualParams.h>

#include <SofaConstraint/LCPConstraintSolver.h>

#include <sofa/core/ObjectFactory.h>
#include <sofa/core/VecId.h>

#include <sofa/helper/AdvancedTimer.h>

#include <sofa/simulation/BehaviorUpdatePositionVisitor.h>
#include <sofa/simulation/MechanicalOperations.h>
#include <sofa/simulation/SolveVisitor.h>
#include <sofa/simulation/VectorOperations.h>
#include <sofa/simulation/AnimateBeginEvent.h>
#include <sofa/simulation/AnimateEndEvent.h>
#include <sofa/simulation/PropagateEventVisitor.h>
#include <sofa/simulation/UpdateContextVisitor.h>
#include <sofa/simulation/UpdateMappingVisitor.h>
#include <sofa/simulation/UpdateMappingEndEvent.h>
#include <sofa/simulation/UpdateBoundingBoxVisitor.h>

namespace sofa
{

namespace component
{

namespace animationloop
{

using namespace core::behavior;
using namespace sofa::simulation;

FreeMotionAnimationLoop::FreeMotionAnimationLoop(simulation::Node* gnode)
    : Inherit(gnode)
    , m_solveVelocityConstraintFirst(initData(&m_solveVelocityConstraintFirst , false, "solveVelocityConstraintFirst", "solve separately velocity constraint violations before position constraint violations"))
    , constraintSolver(NULL)
    , defaultSolver(NULL)
{
}

FreeMotionAnimationLoop::~FreeMotionAnimationLoop()
{
    if (defaultSolver != NULL)
        defaultSolver.reset();
}

void FreeMotionAnimationLoop::parse ( sofa::core::objectmodel::BaseObjectDescription* arg )
{
    this->simulation::CollisionAnimationLoop::parse(arg);

    defaultSolver = sofa::core::objectmodel::New<constraintset::LCPConstraintSolver>();
    defaultSolver->parse(arg);
}

void FreeMotionAnimationLoop::init()
{

    {
    simulation::common::VectorOperations vop(core::ExecParams::defaultInstance(), this->getContext());
    MultiVecDeriv dx(&vop, core::VecDerivId::dx() ); dx.realloc( &vop, true, true );
    MultiVecDeriv df(&vop, core::VecDerivId::dforce() ); df.realloc( &vop, true, true );
    }

    getContext()->get(constraintSolver, core::objectmodel::BaseContext::SearchDown);
    if (constraintSolver == NULL && defaultSolver != NULL)
    {
        serr << "No ConstraintSolver found, using default LCPConstraintSolver" << sendl;
        this->getContext()->addObject(defaultSolver);
        constraintSolver = defaultSolver.get();
        defaultSolver = NULL;
    }
    else
    {
        defaultSolver.reset();
    }
}

void FreeMotionAnimationLoop::step(const sofa::core::ExecParams* params, SReal dt)
{
    if (dt == 0)
        dt = this->gnode->getDt();

#ifdef SOFA_DUMP_VISITOR_INFO
    simulation::Visitor::printNode("Step");
#endif

    {
        sofa::helper::AdvancedTimer::stepBegin("AnimateBeginEvent");
        AnimateBeginEvent ev ( dt );
        PropagateEventVisitor act ( params, &ev );
        this->gnode->execute ( act );
        sofa::helper::AdvancedTimer::stepEnd("AnimateBeginEvent");
    }

    double startTime = this->gnode->getTime();

    simulation::common::VectorOperations vop(params, this->getContext());
    simulation::common::MechanicalOperations mop(params, this->getContext());

    MultiVecCoord pos(&vop, core::VecCoordId::position() );
    MultiVecDeriv vel(&vop, core::VecDerivId::velocity() );
    MultiVecCoord freePos(&vop, core::VecCoordId::freePosition() );
    MultiVecDeriv freeVel(&vop, core::VecDerivId::freeVelocity() );

    {
    MultiVecDeriv dx(&vop, core::VecDerivId::dx() ); dx.realloc( &vop, true, true );
    MultiVecDeriv df(&vop, core::VecDerivId::dforce() ); df.realloc( &vop, true, true );
    }

    // This solver will work in freePosition and freeVelocity vectors.
    // We need to initialize them if it's not already done.
    sofa::helper::AdvancedTimer::stepBegin("MechanicalVInitVisitor");
    simulation::MechanicalVInitVisitor< core::V_COORD >(params, core::VecCoordId::freePosition(), core::ConstVecCoordId::position(), true).execute(this->gnode);
    simulation::MechanicalVInitVisitor< core::V_DERIV >(params, core::VecDerivId::freeVelocity(), core::ConstVecDerivId::velocity(), true).execute(this->gnode);

    sofa::helper::AdvancedTimer::stepEnd("MechanicalVInitVisitor");

    BehaviorUpdatePositionVisitor beh(params , dt);

    using helper::system::thread::CTime;
    using sofa::helper::AdvancedTimer;

    double time = 0.0;
    //double timeTotal = 0.0;
    double timeScale = 1000.0 / (double)CTime::getTicksPerSec();

    if (displayTime.getValue())
    {
        time = (double) CTime::getTime();
        //timeTotal = (double) CTime::getTime();
    }

    // Update the BehaviorModels
    // Required to allow the RayPickInteractor interaction
    if (f_printLog.getValue())
        serr << "updatePos called" << sendl;

    AdvancedTimer::stepBegin("UpdatePosition");
    this->gnode->execute(&beh);
    AdvancedTimer::stepEnd("UpdatePosition");

    if (f_printLog.getValue())
        serr << "updatePos performed - beginVisitor called" << sendl;

    simulation::MechanicalBeginIntegrationVisitor beginVisitor(params, dt);
    this->gnode->execute(&beginVisitor);

    if (f_printLog.getValue())
        serr << "beginVisitor performed - SolveVisitor for freeMotion is called" << sendl;

    // Free Motion
    AdvancedTimer::stepBegin("FreeMotion");
    simulation::SolveVisitor freeMotion(params, dt, true);
    this->gnode->execute(&freeMotion);
    AdvancedTimer::stepEnd("FreeMotion");

    mop.propagateXAndV(freePos, freeVel, true); // apply projective constraints

    if (f_printLog.getValue())
        serr << " SolveVisitor for freeMotion performed" << sendl;

    if (displayTime.getValue())
    {
        sout << " >>>>> Begin display FreeMotionAnimationLoop time" << sendl;
        sout <<" Free Motion " << ((double)CTime::getTime() - time) * timeScale << " ms" << sendl;

        time = (double)CTime::getTime();
    }

    // Collision detection and response creation
    AdvancedTimer::stepBegin("Collision");
    computeCollision(params);
    AdvancedTimer::stepEnd  ("Collision");

    mop.propagateX(pos, false); // Why is this done at that point ???

    if (displayTime.getValue())
    {
        sout << " computeCollision " << ((double) CTime::getTime() - time) * timeScale << " ms" << sendl;
        time = (double)CTime::getTime();
    }

    // Solve constraints
    if (constraintSolver)
    {
        AdvancedTimer::stepBegin("ConstraintSolver");

        if (m_solveVelocityConstraintFirst.getValue())
        {
            core::ConstraintParams cparams(*params);
            cparams.setX(freePos);
            cparams.setV(freeVel);

            cparams.setOrder(core::ConstraintParams::VEL);
            constraintSolver->solveConstraint(&cparams, vel);

            MultiVecDeriv dv(&vop, constraintSolver->getDx());
            mop.projectResponse(dv);
            mop.propagateDx(dv);

            // xfree += dv * dt
            freePos.eq(freePos, dv, dt);
            mop.propagateX(freePos, false); // ignore projective constraints

            cparams.setOrder(core::ConstraintParams::POS);
            constraintSolver->solveConstraint(&cparams, pos);

            MultiVecDeriv dx(&vop, constraintSolver->getDx());

            mop.propagateV(vel, true); // apply projective constraints
            mop.projectResponse(dx);
            mop.propagateDx(dx, true);

            // "mapped" x = xfree + dx
            simulation::MechanicalVOpVisitor(params, pos, freePos, dx, 1.0 ).setOnlyMapped(true).execute(this->gnode);
        }
        else
        {
            core::ConstraintParams cparams(*params);
            cparams.setX(freePos);
            cparams.setV(freeVel);

            constraintSolver->solveConstraint(&cparams, pos, vel);
            mop.propagateV(vel, true); // apply projective constraints

            MultiVecDeriv dx(&vop, constraintSolver->getDx());
            mop.projectResponse(dx);
            mop.propagateDx(dx, true);

            // "mapped" x = xfree + dx
            simulation::MechanicalVOpVisitor(params, pos, freePos, dx, 1.0 ).setOnlyMapped(true).execute(this->gnode);
        }
        AdvancedTimer::stepEnd("ConstraintSolver");

    }

    if ( displayTime.getValue() )
    {
        sout << " contactCorrections " << ((double)CTime::getTime() - time) * timeScale << " ms" <<sendl;
        sout << "<<<<<< End display FreeMotionAnimationLoop time." << sendl;
    }

    simulation::MechanicalEndIntegrationVisitor endVisitor(params, dt);
    this->gnode->execute(&endVisitor);

    this->gnode->setTime ( startTime + dt );
    this->gnode->execute<UpdateSimulationContextVisitor>(params);  // propagate time

    {
        AnimateEndEvent ev ( dt );
        PropagateEventVisitor act ( params, &ev );
        this->gnode->execute ( act );
    }

    sofa::helper::AdvancedTimer::stepBegin("UpdateMapping");
    //Visual Information update: Ray Pick add a MechanicalMapping used as VisualMapping
    this->gnode->execute<UpdateMappingVisitor>(params);
//	sofa::helper::AdvancedTimer::step("UpdateMappingEndEvent");
    {
        UpdateMappingEndEvent ev ( dt );
        PropagateEventVisitor act ( params , &ev );
        this->gnode->execute ( act );
    }
    sofa::helper::AdvancedTimer::stepEnd("UpdateMapping");

#ifndef SOFA_NO_UPDATE_BBOX
    sofa::helper::AdvancedTimer::stepBegin("UpdateBBox");
    this->gnode->execute<UpdateBoundingBoxVisitor>(params);
    sofa::helper::AdvancedTimer::stepEnd("UpdateBBox");
#endif
#ifdef SOFA_DUMP_VISITOR_INFO
    simulation::Visitor::printCloseNode("Step");
#endif

}

SOFA_DECL_CLASS(FreeMotionAnimationLoop)

int FreeMotionAnimationLoopClass = core::RegisterObject("Constraint solver")
        .add< FreeMotionAnimationLoop >()
        .addAlias("FreeMotionMasterSolver")
        ;

} // namespace animationloop

} // namespace component

} // namespace sofa
<commit_msg>FIX: FreeMotionAnimationLoop allocates the freeposition / freevelocity first thing in the time step<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, development version     *
*                (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                               SOFA :: Modules                               *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#include <SofaConstraint/FreeMotionAnimationLoop.h>
#include <sofa/core/visual/VisualParams.h>

#include <SofaConstraint/LCPConstraintSolver.h>

#include <sofa/core/ObjectFactory.h>
#include <sofa/core/VecId.h>

#include <sofa/helper/AdvancedTimer.h>

#include <sofa/simulation/BehaviorUpdatePositionVisitor.h>
#include <sofa/simulation/MechanicalOperations.h>
#include <sofa/simulation/SolveVisitor.h>
#include <sofa/simulation/VectorOperations.h>
#include <sofa/simulation/AnimateBeginEvent.h>
#include <sofa/simulation/AnimateEndEvent.h>
#include <sofa/simulation/PropagateEventVisitor.h>
#include <sofa/simulation/UpdateContextVisitor.h>
#include <sofa/simulation/UpdateMappingVisitor.h>
#include <sofa/simulation/UpdateMappingEndEvent.h>
#include <sofa/simulation/UpdateBoundingBoxVisitor.h>

namespace sofa
{

namespace component
{

namespace animationloop
{

using namespace core::behavior;
using namespace sofa::simulation;

FreeMotionAnimationLoop::FreeMotionAnimationLoop(simulation::Node* gnode)
    : Inherit(gnode)
    , m_solveVelocityConstraintFirst(initData(&m_solveVelocityConstraintFirst , false, "solveVelocityConstraintFirst", "solve separately velocity constraint violations before position constraint violations"))
    , constraintSolver(NULL)
    , defaultSolver(NULL)
{
}

FreeMotionAnimationLoop::~FreeMotionAnimationLoop()
{
    if (defaultSolver != NULL)
        defaultSolver.reset();
}

void FreeMotionAnimationLoop::parse ( sofa::core::objectmodel::BaseObjectDescription* arg )
{
    this->simulation::CollisionAnimationLoop::parse(arg);

    defaultSolver = sofa::core::objectmodel::New<constraintset::LCPConstraintSolver>();
    defaultSolver->parse(arg);
}

void FreeMotionAnimationLoop::init()
{

    {
    simulation::common::VectorOperations vop(core::ExecParams::defaultInstance(), this->getContext());
    MultiVecDeriv dx(&vop, core::VecDerivId::dx() ); dx.realloc( &vop, true, true );
    MultiVecDeriv df(&vop, core::VecDerivId::dforce() ); df.realloc( &vop, true, true );
    }

    getContext()->get(constraintSolver, core::objectmodel::BaseContext::SearchDown);
    if (constraintSolver == NULL && defaultSolver != NULL)
    {
        serr << "No ConstraintSolver found, using default LCPConstraintSolver" << sendl;
        this->getContext()->addObject(defaultSolver);
        constraintSolver = defaultSolver.get();
        defaultSolver = NULL;
    }
    else
    {
        defaultSolver.reset();
    }
}

void FreeMotionAnimationLoop::step(const sofa::core::ExecParams* params, SReal dt)
{
    if (dt == 0)
        dt = this->gnode->getDt();

    double startTime = this->gnode->getTime();

    simulation::common::VectorOperations vop(params, this->getContext());
    simulation::common::MechanicalOperations mop(params, this->getContext());

    MultiVecCoord pos(&vop, core::VecCoordId::position() );
    MultiVecDeriv vel(&vop, core::VecDerivId::velocity() );
    MultiVecCoord freePos(&vop, core::VecCoordId::freePosition() );
    MultiVecDeriv freeVel(&vop, core::VecDerivId::freeVelocity() );

    {
        MultiVecDeriv dx(&vop, core::VecDerivId::dx() ); dx.realloc( &vop, true, true );
        MultiVecDeriv df(&vop, core::VecDerivId::dforce() ); df.realloc( &vop, true, true );
    }

    // This solver will work in freePosition and freeVelocity vectors.
    // We need to initialize them if it's not already done.
    sofa::helper::AdvancedTimer::stepBegin("MechanicalVInitVisitor");
    simulation::MechanicalVInitVisitor< core::V_COORD >(params, core::VecCoordId::freePosition(), core::ConstVecCoordId::position(), true).execute(this->gnode);
    simulation::MechanicalVInitVisitor< core::V_DERIV >(params, core::VecDerivId::freeVelocity(), core::ConstVecDerivId::velocity(), true).execute(this->gnode);

    sofa::helper::AdvancedTimer::stepEnd("MechanicalVInitVisitor");

#ifdef SOFA_DUMP_VISITOR_INFO
    simulation::Visitor::printNode("Step");
#endif

    {
        sofa::helper::AdvancedTimer::stepBegin("AnimateBeginEvent");
        AnimateBeginEvent ev ( dt );
        PropagateEventVisitor act ( params, &ev );
        this->gnode->execute ( act );
        sofa::helper::AdvancedTimer::stepEnd("AnimateBeginEvent");
    }

    BehaviorUpdatePositionVisitor beh(params , dt);

    using helper::system::thread::CTime;
    using sofa::helper::AdvancedTimer;

    double time = 0.0;
    //double timeTotal = 0.0;
    double timeScale = 1000.0 / (double)CTime::getTicksPerSec();

    if (displayTime.getValue())
    {
        time = (double) CTime::getTime();
        //timeTotal = (double) CTime::getTime();
    }

    // Update the BehaviorModels
    // Required to allow the RayPickInteractor interaction
    if (f_printLog.getValue())
        serr << "updatePos called" << sendl;

    AdvancedTimer::stepBegin("UpdatePosition");
    this->gnode->execute(&beh);
    AdvancedTimer::stepEnd("UpdatePosition");

    if (f_printLog.getValue())
        serr << "updatePos performed - beginVisitor called" << sendl;

    simulation::MechanicalBeginIntegrationVisitor beginVisitor(params, dt);
    this->gnode->execute(&beginVisitor);

    if (f_printLog.getValue())
        serr << "beginVisitor performed - SolveVisitor for freeMotion is called" << sendl;

    // Free Motion
    AdvancedTimer::stepBegin("FreeMotion");
    simulation::SolveVisitor freeMotion(params, dt, true);
    this->gnode->execute(&freeMotion);
    AdvancedTimer::stepEnd("FreeMotion");

    mop.propagateXAndV(freePos, freeVel, true); // apply projective constraints

    if (f_printLog.getValue())
        serr << " SolveVisitor for freeMotion performed" << sendl;

    if (displayTime.getValue())
    {
        sout << " >>>>> Begin display FreeMotionAnimationLoop time" << sendl;
        sout <<" Free Motion " << ((double)CTime::getTime() - time) * timeScale << " ms" << sendl;

        time = (double)CTime::getTime();
    }

    // Collision detection and response creation
    AdvancedTimer::stepBegin("Collision");
    computeCollision(params);
    AdvancedTimer::stepEnd  ("Collision");

    mop.propagateX(pos, false); // Why is this done at that point ???

    if (displayTime.getValue())
    {
        sout << " computeCollision " << ((double) CTime::getTime() - time) * timeScale << " ms" << sendl;
        time = (double)CTime::getTime();
    }

    // Solve constraints
    if (constraintSolver)
    {
        AdvancedTimer::stepBegin("ConstraintSolver");

        if (m_solveVelocityConstraintFirst.getValue())
        {
            core::ConstraintParams cparams(*params);
            cparams.setX(freePos);
            cparams.setV(freeVel);

            cparams.setOrder(core::ConstraintParams::VEL);
            constraintSolver->solveConstraint(&cparams, vel);

            MultiVecDeriv dv(&vop, constraintSolver->getDx());
            mop.projectResponse(dv);
            mop.propagateDx(dv);

            // xfree += dv * dt
            freePos.eq(freePos, dv, dt);
            mop.propagateX(freePos, false); // ignore projective constraints

            cparams.setOrder(core::ConstraintParams::POS);
            constraintSolver->solveConstraint(&cparams, pos);

            MultiVecDeriv dx(&vop, constraintSolver->getDx());

            mop.propagateV(vel, true); // apply projective constraints
            mop.projectResponse(dx);
            mop.propagateDx(dx, true);

            // "mapped" x = xfree + dx
            simulation::MechanicalVOpVisitor(params, pos, freePos, dx, 1.0 ).setOnlyMapped(true).execute(this->gnode);
        }
        else
        {
            core::ConstraintParams cparams(*params);
            cparams.setX(freePos);
            cparams.setV(freeVel);

            constraintSolver->solveConstraint(&cparams, pos, vel);
            mop.propagateV(vel, true); // apply projective constraints

            MultiVecDeriv dx(&vop, constraintSolver->getDx());
            mop.projectResponse(dx);
            mop.propagateDx(dx, true);

            // "mapped" x = xfree + dx
            simulation::MechanicalVOpVisitor(params, pos, freePos, dx, 1.0 ).setOnlyMapped(true).execute(this->gnode);
        }
        AdvancedTimer::stepEnd("ConstraintSolver");

    }

    if ( displayTime.getValue() )
    {
        sout << " contactCorrections " << ((double)CTime::getTime() - time) * timeScale << " ms" <<sendl;
        sout << "<<<<<< End display FreeMotionAnimationLoop time." << sendl;
    }

    simulation::MechanicalEndIntegrationVisitor endVisitor(params, dt);
    this->gnode->execute(&endVisitor);

    this->gnode->setTime ( startTime + dt );
    this->gnode->execute<UpdateSimulationContextVisitor>(params);  // propagate time

    {
        AnimateEndEvent ev ( dt );
        PropagateEventVisitor act ( params, &ev );
        this->gnode->execute ( act );
    }

    sofa::helper::AdvancedTimer::stepBegin("UpdateMapping");
    //Visual Information update: Ray Pick add a MechanicalMapping used as VisualMapping
    this->gnode->execute<UpdateMappingVisitor>(params);
//	sofa::helper::AdvancedTimer::step("UpdateMappingEndEvent");
    {
        UpdateMappingEndEvent ev ( dt );
        PropagateEventVisitor act ( params , &ev );
        this->gnode->execute ( act );
    }
    sofa::helper::AdvancedTimer::stepEnd("UpdateMapping");

#ifndef SOFA_NO_UPDATE_BBOX
    sofa::helper::AdvancedTimer::stepBegin("UpdateBBox");
    this->gnode->execute<UpdateBoundingBoxVisitor>(params);
    sofa::helper::AdvancedTimer::stepEnd("UpdateBBox");
#endif
#ifdef SOFA_DUMP_VISITOR_INFO
    simulation::Visitor::printCloseNode("Step");
#endif

}

SOFA_DECL_CLASS(FreeMotionAnimationLoop)

int FreeMotionAnimationLoopClass = core::RegisterObject("Constraint solver")
        .add< FreeMotionAnimationLoop >()
        .addAlias("FreeMotionMasterSolver")
        ;

} // namespace animationloop

} // namespace component

} // namespace sofa
<|endoftext|>


<commit_before>//	MIT License
//
//	Copyright (c) 2016 Fabian Lschner
//
//	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 <noname_tools\tools>

#include "catch.hpp"

#include <string>
#include <type_traits>

using namespace noname;

// TODO: Test if void_t really works for its intended use case

TEST_CASE("Testing typetraits")
{
	SECTION("Testing void_t")
	{
		REQUIRE((std::is_same<tools::void_t<bool, int, double>, void>::value == true));
	}

	SECTION("Testing bool_constant")
	{
		REQUIRE((tools::bool_constant<true>::value == true));
		REQUIRE((tools::bool_constant<false>::value == false));
	}

	SECTION("Testing negation")
	{
		REQUIRE((tools::negation<std::true_type>::value == false));
		REQUIRE((tools::negation<std::false_type>::value == true));
	}

	SECTION("Testing conjunction")
	{
		REQUIRE((tools::conjunction<std::true_type, std::true_type>::value == true));
		REQUIRE((tools::conjunction<std::false_type, std::true_type>::value == false));
		REQUIRE((tools::conjunction<std::true_type, std::false_type>::value == false));
		REQUIRE((tools::conjunction<std::false_type, std::false_type>::value == false));
		REQUIRE((tools::conjunction<std::true_type, std::true_type, std::true_type>::value == true));
		REQUIRE((tools::conjunction<std::true_type, std::true_type, std::false_type>::value == false));
		REQUIRE((tools::conjunction<std::false_type, std::false_type, std::true_type>::value == false));
		REQUIRE((tools::disjunction<std::false_type, std::false_type, std::false_type>::value == false));
	}

	SECTION("Testing disjunction")
	{
		REQUIRE((tools::disjunction<std::true_type, std::true_type>::value == true));
		REQUIRE((tools::disjunction<std::false_type, std::true_type>::value == true));
		REQUIRE((tools::disjunction<std::true_type, std::false_type>::value == true));
		REQUIRE((tools::disjunction<std::false_type, std::false_type>::value == false));
		REQUIRE((tools::disjunction<std::true_type, std::true_type, std::true_type>::value == true));
		REQUIRE((tools::disjunction<std::true_type, std::true_type, std::false_type>::value == true));
		REQUIRE((tools::disjunction<std::false_type, std::false_type, std::true_type>::value == true));
		REQUIRE((tools::disjunction<std::false_type, std::false_type, std::false_type>::value == false));
	}

	SECTION("Testing is_referenceable")
	{
		REQUIRE((tools::is_referenceable<double>::value == true));
		REQUIRE((tools::is_referenceable<double&>::value == true));
		REQUIRE((tools::is_referenceable<void>::value == false));
	}

	SECTION("Testing is_swappable")
	{
		REQUIRE((tools::is_swappable_with<double, double>::value == true));
		REQUIRE((tools::is_swappable_with<double, void>::value == false));

		REQUIRE((tools::is_swappable<double>::value == true));
		REQUIRE((tools::is_swappable<void>::value == false));
	}
}

TEST_CASE("Testing utility types")
{
	REQUIRE((std::is_same<tools::nth_element_t<0, int, void, double>, int>::value == true));
	REQUIRE((std::is_same<tools::nth_element_t<1, int, void, double>, void>::value == true));
	REQUIRE((std::is_same<tools::nth_element_t<2, int, void, double>, double>::value == true));

	REQUIRE((tools::element_index_v<int, int, double, void> == 0));
	REQUIRE((tools::element_index_v<double, int, double, void> == 1));
	REQUIRE((tools::element_index_v<void, int, double, void> == 2));
	REQUIRE((tools::element_index_v<std::string, int, double, void> == tools::element_not_found));

	REQUIRE((tools::count_element_v<int, void, double, int, int, char, int> == 3));
	REQUIRE((tools::count_element_v<int> == 0));

	REQUIRE((tools::unique_types_v<int, double, char> == true));
	REQUIRE((tools::unique_types_v<int, double, int, char> == false));
	REQUIRE((tools::unique_types_v<int> == true));
	REQUIRE((tools::unique_types_v<> == false));
	REQUIRE((tools::unique_types_v<void, double> == true));
}
<commit_msg>Added unique_elements test<commit_after>//	MIT License
//
//	Copyright (c) 2016 Fabian Lschner
//
//	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 <noname_tools\tools>

#include "catch.hpp"

#include <string>
#include <type_traits>

using namespace noname;

// TODO: Test if void_t really works for its intended use case

TEST_CASE("Testing typetraits")
{
	SECTION("Testing void_t")
	{
		REQUIRE((std::is_same<tools::void_t<bool, int, double>, void>::value == true));
	}

	SECTION("Testing bool_constant")
	{
		REQUIRE((tools::bool_constant<true>::value == true));
		REQUIRE((tools::bool_constant<false>::value == false));
	}

	SECTION("Testing negation")
	{
		REQUIRE((tools::negation<std::true_type>::value == false));
		REQUIRE((tools::negation<std::false_type>::value == true));
	}

	SECTION("Testing conjunction")
	{
		REQUIRE((tools::conjunction<std::true_type, std::true_type>::value == true));
		REQUIRE((tools::conjunction<std::false_type, std::true_type>::value == false));
		REQUIRE((tools::conjunction<std::true_type, std::false_type>::value == false));
		REQUIRE((tools::conjunction<std::false_type, std::false_type>::value == false));
		REQUIRE((tools::conjunction<std::true_type, std::true_type, std::true_type>::value == true));
		REQUIRE((tools::conjunction<std::true_type, std::true_type, std::false_type>::value == false));
		REQUIRE((tools::conjunction<std::false_type, std::false_type, std::true_type>::value == false));
		REQUIRE((tools::disjunction<std::false_type, std::false_type, std::false_type>::value == false));
	}

	SECTION("Testing disjunction")
	{
		REQUIRE((tools::disjunction<std::true_type, std::true_type>::value == true));
		REQUIRE((tools::disjunction<std::false_type, std::true_type>::value == true));
		REQUIRE((tools::disjunction<std::true_type, std::false_type>::value == true));
		REQUIRE((tools::disjunction<std::false_type, std::false_type>::value == false));
		REQUIRE((tools::disjunction<std::true_type, std::true_type, std::true_type>::value == true));
		REQUIRE((tools::disjunction<std::true_type, std::true_type, std::false_type>::value == true));
		REQUIRE((tools::disjunction<std::false_type, std::false_type, std::true_type>::value == true));
		REQUIRE((tools::disjunction<std::false_type, std::false_type, std::false_type>::value == false));
	}

	SECTION("Testing is_referenceable")
	{
		REQUIRE((tools::is_referenceable<double>::value == true));
		REQUIRE((tools::is_referenceable<double&>::value == true));
		REQUIRE((tools::is_referenceable<void>::value == false));
	}

	SECTION("Testing is_swappable")
	{
		REQUIRE((tools::is_swappable_with<double, double>::value == true));
		REQUIRE((tools::is_swappable_with<double, void>::value == false));

		REQUIRE((tools::is_swappable<double>::value == true));
		REQUIRE((tools::is_swappable<void>::value == false));
	}
}

TEST_CASE("Testing utility types")
{
	REQUIRE((std::is_same<tools::nth_element_t<0, int, void, double>, int>::value == true));
	REQUIRE((std::is_same<tools::nth_element_t<1, int, void, double>, void>::value == true));
	REQUIRE((std::is_same<tools::nth_element_t<2, int, void, double>, double>::value == true));

	REQUIRE((tools::element_index_v<int, int, double, void> == 0));
	REQUIRE((tools::element_index_v<double, int, double, void> == 1));
	REQUIRE((tools::element_index_v<void, int, double, void> == 2));
	REQUIRE((tools::element_index_v<std::string, int, double, void> == tools::element_not_found));

	REQUIRE((tools::count_element_v<int, void, double, int, int, char, int> == 3));
	REQUIRE((tools::count_element_v<int> == 0));

	REQUIRE((tools::unique_elements_v<int, double, char> == true));
	REQUIRE((tools::unique_elements_v<int, double, int, char> == false));
	REQUIRE((tools::unique_elements_v<int> == true));
	REQUIRE((tools::unique_elements_v<> == false));
	REQUIRE((tools::unique_elements_v<void, double> == true));
}
<|endoftext|>


<commit_before><commit_msg>Fixes the issue when right clicking on a text in a scrolled text area results in the wrong word being selected. The solution seems to lie in a tricky webkit hack, which requires the use of point() and localPoint() in different situations.<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "webkit/glue/plugins/plugin_lib.h"

#include <dlfcn.h>

#include "base/string_util.h"
#include "base/sys_string_conversions.h"
#include "webkit/glue/plugins/plugin_list.h"

// These headers must be included in this order to make the declaration gods
// happy.
#include "base/third_party/nspr/prcpucfg_linux.h"
#include "third_party/mozilla/include/nsplugindefs.h"

namespace NPAPI {

bool PluginLib::ReadWebPluginInfo(const FilePath& filename,
                                  WebPluginInfo* info) {
  // The file to reference is:
  // http://mxr.mozilla.org/firefox/source/modules/plugin/base/src/nsPluginsDirUnix.cpp

  void* dl = base::LoadNativeLibrary(filename);
  if (!dl)
    return false;

  info->path = filename;

  // See comments in plugin_lib_mac regarding this symbol.
  typedef const char* (*NP_GetMimeDescriptionType)();
  NP_GetMimeDescriptionType NP_GetMIMEDescription =
      reinterpret_cast<NP_GetMimeDescriptionType>(
          dlsym(dl, "NP_GetMIMEDescription"));
  const char* mime_description = NULL;
  if (NP_GetMIMEDescription)
    mime_description = NP_GetMIMEDescription();

  if (mime_description) {
    // We parse the description here into WebPluginMimeType structures.
    // Description for Flash 10 looks like (all as one string):
    //   "application/x-shockwave-flash:swf:Shockwave Flash;"
    //   "application/futuresplash:spl:FutureSplash Player"
    std::vector<std::string> descriptions;
    SplitString(mime_description, ';', &descriptions);
    for (size_t i = 0; i < descriptions.size(); ++i) {
      std::vector<std::string> fields;
      SplitString(descriptions[i], ':', &fields);
      if (fields.size() != 3) {
        LOG(WARNING) << "Couldn't parse plugin info: " << descriptions[i];
        continue;
      }

      WebPluginMimeType mime_type;
      mime_type.mime_type = fields[0];
      SplitString(fields[1], ',', &mime_type.file_extensions);
      mime_type.description = ASCIIToWide(fields[2]);
      info->mime_types.push_back(mime_type);
    }
  }

  // The plugin name and description live behind NP_GetValue calls.
  typedef NPError (*NP_GetValueType)(void* unused,
                                     nsPluginVariable variable,
                                     void* value_out);
  NP_GetValueType NP_GetValue =
      reinterpret_cast<NP_GetValueType>(dlsym(dl, "NP_GetValue"));
  if (NP_GetValue) {
    const char* name = NULL;
    NP_GetValue(NULL, nsPluginVariable_NameString, &name);
    if (name)
      info->name = ASCIIToWide(name);

    const char* description = NULL;
    NP_GetValue(NULL, nsPluginVariable_DescriptionString, &description);
    if (description)
      info->desc = ASCIIToWide(description);
  }

  return true;
}

}  // namespace NPAPI
<commit_msg>linux plugins: assume UTF-8 for plugin name/description<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "webkit/glue/plugins/plugin_lib.h"

#include <dlfcn.h>

#include "base/string_util.h"
#include "base/sys_string_conversions.h"
#include "webkit/glue/plugins/plugin_list.h"

// These headers must be included in this order to make the declaration gods
// happy.
#include "base/third_party/nspr/prcpucfg_linux.h"
#include "third_party/mozilla/include/nsplugindefs.h"

namespace NPAPI {

bool PluginLib::ReadWebPluginInfo(const FilePath& filename,
                                  WebPluginInfo* info) {
  // The file to reference is:
  // http://mxr.mozilla.org/firefox/source/modules/plugin/base/src/nsPluginsDirUnix.cpp

  void* dl = base::LoadNativeLibrary(filename);
  if (!dl)
    return false;

  info->path = filename;

  // See comments in plugin_lib_mac regarding this symbol.
  typedef const char* (*NP_GetMimeDescriptionType)();
  NP_GetMimeDescriptionType NP_GetMIMEDescription =
      reinterpret_cast<NP_GetMimeDescriptionType>(
          dlsym(dl, "NP_GetMIMEDescription"));
  const char* mime_description = NULL;
  if (NP_GetMIMEDescription)
    mime_description = NP_GetMIMEDescription();

  if (mime_description) {
    // We parse the description here into WebPluginMimeType structures.
    // Description for Flash 10 looks like (all as one string):
    //   "application/x-shockwave-flash:swf:Shockwave Flash;"
    //   "application/futuresplash:spl:FutureSplash Player"
    std::vector<std::string> descriptions;
    SplitString(mime_description, ';', &descriptions);
    for (size_t i = 0; i < descriptions.size(); ++i) {
      if (descriptions[i].empty())
        continue;  // Don't warn if they have trailing semis.

      std::vector<std::string> fields;
      SplitString(descriptions[i], ':', &fields);
      if (fields.size() != 3) {
        LOG(WARNING) << "Couldn't parse plugin info: " << descriptions[i];
        continue;
      }

      WebPluginMimeType mime_type;
      mime_type.mime_type = fields[0];
      SplitString(fields[1], ',', &mime_type.file_extensions);
      mime_type.description = ASCIIToWide(fields[2]);
      info->mime_types.push_back(mime_type);
    }
  }

  // The plugin name and description live behind NP_GetValue calls.
  typedef NPError (*NP_GetValueType)(void* unused,
                                     nsPluginVariable variable,
                                     void* value_out);
  NP_GetValueType NP_GetValue =
      reinterpret_cast<NP_GetValueType>(dlsym(dl, "NP_GetValue"));
  if (NP_GetValue) {
    const char* name = NULL;
    NP_GetValue(NULL, nsPluginVariable_NameString, &name);
    if (name)
      info->name = UTF8ToWide(name);

    const char* description = NULL;
    NP_GetValue(NULL, nsPluginVariable_DescriptionString, &description);
    if (description)
      info->desc = UTF8ToWide(description);
  }

  return true;
}

}  // namespace NPAPI
<|endoftext|>


<commit_before>#include "RenderSystem/Managers/CBackBufferManager.h"

namespace VKE
{
    namespace RenderSystem
    {
        namespace Managers
        {
            CBackBufferManager::CBackBufferManager( CGraphicsContext* pCtx ) :
                m_pCtx( pCtx )
            {

            }

            CBackBufferManager::~CBackBufferManager()
            {
                _Destroy();
            }

            void CBackBufferManager::_Destroy()
            {

            }

            void CBackBufferManager::Destroy()
            {

            }

            Result CBackBufferManager::Create(const SBackBufferManagerDesc& Desc)
            {
                Result res = VKE_OK;
                m_Desc = Desc;
                m_backBufferCount = static_cast< uint32_t >( m_Desc.backBufferCount );
                return res;
            }

            uint32_t CBackBufferManager::AcquireNextBuffer()
            {
                uint16_t currIdx = m_currBackBufferIndex;
                m_currBackBufferIndex = currIdx % m_backBufferCount;
                return m_currBackBufferIndex;
            }

            uint32_t CBackBufferManager::AddCustomData(uint8_t* aData, uint32_t elementSize)
            {
                uint32_t idx = m_customDataIdx++;
                //auto& Data = m_BackBuffers.aCustomData;
                uint8_t* pCurrPtr = aData;
                for( uint32_t i = 0; i < m_backBufferCount; ++i )
                {
                    //idx = Data[ i ].PushBack( pCurrPtr );
                    m_BackBuffers[ i ].CustomData.insert( { idx, pCurrPtr } );
                    pCurrPtr += elementSize;
                }
                return idx;
            }

            void CBackBufferManager::UpdateCustomData(uint32_t backBufferIdx, uint32_t dataIdx, void* pData)
            {
                m_BackBuffers[ backBufferIdx ].CustomData[ dataIdx ] = pData;
            }

            void CBackBufferManager::UpdateCustomData(uint32_t dataIdx, uint8_t* aData, uint32_t elementSize)
            {
                uint8_t* pCurrPtr = aData;
                for( uint32_t i = 0; i < m_backBufferCount; ++i )
                {
                    m_BackBuffers[ i ].CustomData[ dataIdx ] = pCurrPtr;
                    pCurrPtr += elementSize;
                }
            }

            void* CBackBufferManager::GetCustomData(uint32_t idx)
            {
                return m_BackBuffers[ m_currBackBufferIndex ].CustomData[ idx ];
            }

        } // Managers
    } // RenderSystem
} // VKE<commit_msg>back buffer idx fix<commit_after>#include "RenderSystem/Managers/CBackBufferManager.h"

namespace VKE
{
    namespace RenderSystem
    {
        namespace Managers
        {
            CBackBufferManager::CBackBufferManager( CGraphicsContext* pCtx ) :
                m_pCtx( pCtx )
            {

            }

            CBackBufferManager::~CBackBufferManager()
            {
                _Destroy();
            }

            void CBackBufferManager::_Destroy()
            {

            }

            void CBackBufferManager::Destroy()
            {

            }

            Result CBackBufferManager::Create(const SBackBufferManagerDesc& Desc)
            {
                Result res = VKE_OK;
                m_Desc = Desc;
                m_backBufferCount = static_cast< uint32_t >( m_Desc.backBufferCount );
                return res;
            }

            uint32_t CBackBufferManager::AcquireNextBuffer()
            {
                const uint16_t currIdx = m_currBackBufferIndex;
                m_currBackBufferIndex = ( currIdx + 1 ) % m_backBufferCount;
                return m_currBackBufferIndex;
            }

            uint32_t CBackBufferManager::AddCustomData(uint8_t* aData, uint32_t elementSize)
            {
                uint32_t idx = m_customDataIdx++;
                //auto& Data = m_BackBuffers.aCustomData;
                uint8_t* pCurrPtr = aData;
                for( uint32_t i = 0; i < m_backBufferCount; ++i )
                {
                    //idx = Data[ i ].PushBack( pCurrPtr );
                    m_BackBuffers[ i ].CustomData.insert( { idx, pCurrPtr } );
                    pCurrPtr += elementSize;
                }
                return idx;
            }

            void CBackBufferManager::UpdateCustomData(uint32_t backBufferIdx, uint32_t dataIdx, void* pData)
            {
                m_BackBuffers[ backBufferIdx ].CustomData[ dataIdx ] = pData;
            }

            void CBackBufferManager::UpdateCustomData(uint32_t dataIdx, uint8_t* aData, uint32_t elementSize)
            {
                uint8_t* pCurrPtr = aData;
                for( uint32_t i = 0; i < m_backBufferCount; ++i )
                {
                    m_BackBuffers[ i ].CustomData[ dataIdx ] = pCurrPtr;
                    pCurrPtr += elementSize;
                }
            }

            void* CBackBufferManager::GetCustomData(uint32_t idx)
            {
                return m_BackBuffers[ m_currBackBufferIndex ].CustomData[ idx ];
            }

        } // Managers
    } // RenderSystem
} // VKE<|endoftext|>


<commit_before><commit_msg>#i10000# #i81592# warnings = errors<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "webkit/glue/plugins/plugin_lib.h"

#include <dlfcn.h>
#if defined(OS_OPENBSD)
#include <sys/exec_elf.h>
#else
#include <elf.h>
#include <fcntl.h>
#endif
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include "base/eintr_wrapper.h"
#include "base/file_util.h"
#include "base/string_split.h"
#include "base/string_util.h"
#include "base/sys_string_conversions.h"
#include "base/utf_string_conversions.h"
#include "webkit/glue/plugins/plugin_list.h"

// These headers must be included in this order to make the declaration gods
// happy.
#include "base/third_party/nspr/prcpucfg_linux.h"

namespace {

using NPAPI::PluginList;

// Copied from nsplugindefs.h instead of including the file since it has a bunch
// of dependencies.
enum nsPluginVariable {
  nsPluginVariable_NameString        = 1,
  nsPluginVariable_DescriptionString = 2
};

// Read the ELF header and return true if it is usable on
// the current architecture (e.g. 32-bit ELF on 32-bit build).
// Returns false on other errors as well.
bool ELFMatchesCurrentArchitecture(const FilePath& filename) {
  // First make sure we can open the file and it is in fact, a regular file.
  struct stat stat_buf;
  // Open with O_NONBLOCK so we don't block on pipes.
  int fd = open(filename.value().c_str(), O_RDONLY|O_NONBLOCK);
  if (fd < 0)
    return false;
  bool ret = (fstat(fd, &stat_buf) >= 0 && S_ISREG(stat_buf.st_mode));
  if (HANDLE_EINTR(close(fd)) < 0)
    return false;
  if (!ret)
    return false;

  const size_t kELFBufferSize = 5;
  char buffer[kELFBufferSize];
  if (!file_util::ReadFile(filename, buffer, kELFBufferSize))
    return false;

  if (buffer[0] != ELFMAG0 ||
      buffer[1] != ELFMAG1 ||
      buffer[2] != ELFMAG2 ||
      buffer[3] != ELFMAG3) {
    // Not an ELF file, perhaps?
    return false;
  }

  int elf_class = buffer[EI_CLASS];
#if defined(ARCH_CPU_32_BITS)
  if (elf_class == ELFCLASS32)
    return true;
#elif defined(ARCH_CPU_64_BITS)
  if (elf_class == ELFCLASS64)
    return true;
#endif

  return false;
}

// This structure matches enough of nspluginwrapper's NPW_PluginInfo
// for us to extract the real plugin path.
struct __attribute__((packed)) NSPluginWrapperInfo {
  char ident[32];  // NSPluginWrapper magic identifier (includes version).
  char path[PATH_MAX];  // Path to wrapped plugin.
};

// Test a plugin for whether it's been wrapped by NSPluginWrapper, and
// if so attempt to unwrap it.  Pass in an opened plugin handle; on
// success, |dl| and |unwrapped_path| will be filled in with the newly
// opened plugin.  On failure, params are left unmodified.
void UnwrapNSPluginWrapper(void **dl, FilePath* unwrapped_path) {
  NSPluginWrapperInfo* info =
      reinterpret_cast<NSPluginWrapperInfo*>(dlsym(*dl, "NPW_Plugin"));
  if (!info)
    return;  // Not a NSPW plugin.

  // Here we could check the NSPW ident field for the versioning
  // information, but the path field is available in all versions
  // anyway.

  // Grab the path to the wrapped plugin.  Just in case the structure
  // format changes, protect against the path not being null-terminated.
  char* path_end = static_cast<char*>(memchr(info->path, '\0',
                                             sizeof(info->path)));
  if (!path_end)
    path_end = info->path + sizeof(info->path);
  FilePath path = FilePath(std::string(info->path, path_end - info->path));

  if (!ELFMatchesCurrentArchitecture(path)) {
    LOG(WARNING) << path.value() << " is nspluginwrapper wrapping a "
                 << "plugin for a different architecture; it will "
                 << "work better if you instead use a native plugin.";
    return;
  }

  void* newdl = base::LoadNativeLibrary(path);
  if (!newdl) {
    // We couldn't load the unwrapped plugin for some reason, despite
    // being able to load the wrapped one.  Just use the wrapped one.
    LOG_IF(ERROR, PluginList::DebugPluginLoading())
        << "Could not use unwrapped nspluginwrapper plugin "
        << unwrapped_path->value() << ", using the wrapped one.";
    return;
  }

  // Unload the wrapped plugin, and use the wrapped plugin instead.
  LOG_IF(ERROR, PluginList::DebugPluginLoading())
      << "Using unwrapped version " << unwrapped_path->value()
      << " of nspluginwrapper-wrapped plugin.";
  base::UnloadNativeLibrary(*dl);
  *dl = newdl;
  *unwrapped_path = path;
}

}  // anonymous namespace

namespace NPAPI {

bool PluginLib::ReadWebPluginInfo(const FilePath& filename,
                                  WebPluginInfo* info) {
  // The file to reference is:
  // http://mxr.mozilla.org/firefox/source/modules/plugin/base/src/nsPluginsDirUnix.cpp

  // Skip files that aren't appropriate for our architecture.
  if (!ELFMatchesCurrentArchitecture(filename)) {
    LOG_IF(ERROR, PluginList::DebugPluginLoading())
        << "Skipping plugin " << filename.value()
        << " because it doesn't match the current architecture.";
    return false;
  }

  // TODO(thestig) This is for debugging bug 59317. Remove this when done.
  LOG(INFO) << "PluginLib::ReadWebPluginInfo loading " << filename.value();
  void* dl = base::LoadNativeLibrary(filename);
  if (!dl) {
    LOG_IF(ERROR, PluginList::DebugPluginLoading())
        << "While reading plugin info, unable to load library "
        << filename.value() << ", skipping.";
    return false;
  }

  info->path = filename;
  info->enabled = true;

  // Attempt to swap in the wrapped plugin if this is nspluginwrapper.
  UnwrapNSPluginWrapper(&dl, &info->path);

  // See comments in plugin_lib_mac regarding this symbol.
  typedef const char* (*NP_GetMimeDescriptionType)();
  NP_GetMimeDescriptionType NP_GetMIMEDescription =
      reinterpret_cast<NP_GetMimeDescriptionType>(
          dlsym(dl, "NP_GetMIMEDescription"));
  const char* mime_description = NULL;
  if (NP_GetMIMEDescription)
    mime_description = NP_GetMIMEDescription();

  if (mime_description)
    ParseMIMEDescription(mime_description, &info->mime_types);

  // The plugin name and description live behind NP_GetValue calls.
  typedef NPError (*NP_GetValueType)(void* unused,
                                     nsPluginVariable variable,
                                     void* value_out);
  NP_GetValueType NP_GetValue =
      reinterpret_cast<NP_GetValueType>(dlsym(dl, "NP_GetValue"));
  if (NP_GetValue) {
    const char* name = NULL;
    NP_GetValue(NULL, nsPluginVariable_NameString, &name);
    if (name)
      info->name = UTF8ToUTF16(name);

    const char* description = NULL;
    NP_GetValue(NULL, nsPluginVariable_DescriptionString, &description);
    if (description)
      info->desc = UTF8ToUTF16(description);

    LOG_IF(ERROR, PluginList::DebugPluginLoading())
        << "Got info for plugin " << filename.value()
        << " Name = \"" << UTF16ToUTF8(info->name)
        << "\", Description = \"" << UTF16ToUTF8(info->desc) << "\".";
  } else {
    LOG_IF(ERROR, PluginList::DebugPluginLoading())
        << "Plugin " << filename.value()
        << " has no GetValue() and probably won't work.";
  }

  // Intentionally not unloading the plugin here, it can lead to crashes.

  return true;
}

// static
void PluginLib::ParseMIMEDescription(
    const std::string& description,
    std::vector<WebPluginMimeType>* mime_types) {
  // We parse the description here into WebPluginMimeType structures.
  // Naively from the NPAPI docs you'd think you could use
  // string-splitting, but the Firefox parser turns out to do something
  // different: find the first colon, then the second, then a semi.
  //
  // See ParsePluginMimeDescription near
  // http://mxr.mozilla.org/firefox/source/modules/plugin/base/src/nsPluginsDirUtils.h#53

  std::string::size_type ofs = 0;
  for (;;) {
    WebPluginMimeType mime_type;

    std::string::size_type end = description.find(':', ofs);
    if (end == std::string::npos)
      break;
    mime_type.mime_type = description.substr(ofs, end - ofs);
    ofs = end + 1;

    end = description.find(':', ofs);
    if (end == std::string::npos)
      break;
    const std::string extensions = description.substr(ofs, end - ofs);
    base::SplitString(extensions, ',', &mime_type.file_extensions);
    ofs = end + 1;

    end = description.find(';', ofs);
    // It's ok for end to run off the string here.  If there's no
    // trailing semicolon we consume the remainder of the string.
    if (end != std::string::npos) {
      mime_type.description = UTF8ToUTF16(description.substr(ofs, end - ofs));
    } else {
      mime_type.description = UTF8ToUTF16(description.substr(ofs));
    }
    mime_types->push_back(mime_type);
    if (end == std::string::npos)
      break;
    ofs = end + 1;
  }
}

}  // namespace NPAPI
<commit_msg>plugins: revert the logging statement added in r62783<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "webkit/glue/plugins/plugin_lib.h"

#include <dlfcn.h>
#if defined(OS_OPENBSD)
#include <sys/exec_elf.h>
#else
#include <elf.h>
#include <fcntl.h>
#endif
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include "base/eintr_wrapper.h"
#include "base/file_util.h"
#include "base/string_split.h"
#include "base/string_util.h"
#include "base/sys_string_conversions.h"
#include "base/utf_string_conversions.h"
#include "webkit/glue/plugins/plugin_list.h"

// These headers must be included in this order to make the declaration gods
// happy.
#include "base/third_party/nspr/prcpucfg_linux.h"

namespace {

using NPAPI::PluginList;

// Copied from nsplugindefs.h instead of including the file since it has a bunch
// of dependencies.
enum nsPluginVariable {
  nsPluginVariable_NameString        = 1,
  nsPluginVariable_DescriptionString = 2
};

// Read the ELF header and return true if it is usable on
// the current architecture (e.g. 32-bit ELF on 32-bit build).
// Returns false on other errors as well.
bool ELFMatchesCurrentArchitecture(const FilePath& filename) {
  // First make sure we can open the file and it is in fact, a regular file.
  struct stat stat_buf;
  // Open with O_NONBLOCK so we don't block on pipes.
  int fd = open(filename.value().c_str(), O_RDONLY|O_NONBLOCK);
  if (fd < 0)
    return false;
  bool ret = (fstat(fd, &stat_buf) >= 0 && S_ISREG(stat_buf.st_mode));
  if (HANDLE_EINTR(close(fd)) < 0)
    return false;
  if (!ret)
    return false;

  const size_t kELFBufferSize = 5;
  char buffer[kELFBufferSize];
  if (!file_util::ReadFile(filename, buffer, kELFBufferSize))
    return false;

  if (buffer[0] != ELFMAG0 ||
      buffer[1] != ELFMAG1 ||
      buffer[2] != ELFMAG2 ||
      buffer[3] != ELFMAG3) {
    // Not an ELF file, perhaps?
    return false;
  }

  int elf_class = buffer[EI_CLASS];
#if defined(ARCH_CPU_32_BITS)
  if (elf_class == ELFCLASS32)
    return true;
#elif defined(ARCH_CPU_64_BITS)
  if (elf_class == ELFCLASS64)
    return true;
#endif

  return false;
}

// This structure matches enough of nspluginwrapper's NPW_PluginInfo
// for us to extract the real plugin path.
struct __attribute__((packed)) NSPluginWrapperInfo {
  char ident[32];  // NSPluginWrapper magic identifier (includes version).
  char path[PATH_MAX];  // Path to wrapped plugin.
};

// Test a plugin for whether it's been wrapped by NSPluginWrapper, and
// if so attempt to unwrap it.  Pass in an opened plugin handle; on
// success, |dl| and |unwrapped_path| will be filled in with the newly
// opened plugin.  On failure, params are left unmodified.
void UnwrapNSPluginWrapper(void **dl, FilePath* unwrapped_path) {
  NSPluginWrapperInfo* info =
      reinterpret_cast<NSPluginWrapperInfo*>(dlsym(*dl, "NPW_Plugin"));
  if (!info)
    return;  // Not a NSPW plugin.

  // Here we could check the NSPW ident field for the versioning
  // information, but the path field is available in all versions
  // anyway.

  // Grab the path to the wrapped plugin.  Just in case the structure
  // format changes, protect against the path not being null-terminated.
  char* path_end = static_cast<char*>(memchr(info->path, '\0',
                                             sizeof(info->path)));
  if (!path_end)
    path_end = info->path + sizeof(info->path);
  FilePath path = FilePath(std::string(info->path, path_end - info->path));

  if (!ELFMatchesCurrentArchitecture(path)) {
    LOG(WARNING) << path.value() << " is nspluginwrapper wrapping a "
                 << "plugin for a different architecture; it will "
                 << "work better if you instead use a native plugin.";
    return;
  }

  void* newdl = base::LoadNativeLibrary(path);
  if (!newdl) {
    // We couldn't load the unwrapped plugin for some reason, despite
    // being able to load the wrapped one.  Just use the wrapped one.
    LOG_IF(ERROR, PluginList::DebugPluginLoading())
        << "Could not use unwrapped nspluginwrapper plugin "
        << unwrapped_path->value() << ", using the wrapped one.";
    return;
  }

  // Unload the wrapped plugin, and use the wrapped plugin instead.
  LOG_IF(ERROR, PluginList::DebugPluginLoading())
      << "Using unwrapped version " << unwrapped_path->value()
      << " of nspluginwrapper-wrapped plugin.";
  base::UnloadNativeLibrary(*dl);
  *dl = newdl;
  *unwrapped_path = path;
}

}  // anonymous namespace

namespace NPAPI {

bool PluginLib::ReadWebPluginInfo(const FilePath& filename,
                                  WebPluginInfo* info) {
  // The file to reference is:
  // http://mxr.mozilla.org/firefox/source/modules/plugin/base/src/nsPluginsDirUnix.cpp

  // Skip files that aren't appropriate for our architecture.
  if (!ELFMatchesCurrentArchitecture(filename)) {
    LOG_IF(ERROR, PluginList::DebugPluginLoading())
        << "Skipping plugin " << filename.value()
        << " because it doesn't match the current architecture.";
    return false;
  }

  void* dl = base::LoadNativeLibrary(filename);
  if (!dl) {
    LOG_IF(ERROR, PluginList::DebugPluginLoading())
        << "While reading plugin info, unable to load library "
        << filename.value() << ", skipping.";
    return false;
  }

  info->path = filename;
  info->enabled = true;

  // Attempt to swap in the wrapped plugin if this is nspluginwrapper.
  UnwrapNSPluginWrapper(&dl, &info->path);

  // See comments in plugin_lib_mac regarding this symbol.
  typedef const char* (*NP_GetMimeDescriptionType)();
  NP_GetMimeDescriptionType NP_GetMIMEDescription =
      reinterpret_cast<NP_GetMimeDescriptionType>(
          dlsym(dl, "NP_GetMIMEDescription"));
  const char* mime_description = NULL;
  if (NP_GetMIMEDescription)
    mime_description = NP_GetMIMEDescription();

  if (mime_description)
    ParseMIMEDescription(mime_description, &info->mime_types);

  // The plugin name and description live behind NP_GetValue calls.
  typedef NPError (*NP_GetValueType)(void* unused,
                                     nsPluginVariable variable,
                                     void* value_out);
  NP_GetValueType NP_GetValue =
      reinterpret_cast<NP_GetValueType>(dlsym(dl, "NP_GetValue"));
  if (NP_GetValue) {
    const char* name = NULL;
    NP_GetValue(NULL, nsPluginVariable_NameString, &name);
    if (name)
      info->name = UTF8ToUTF16(name);

    const char* description = NULL;
    NP_GetValue(NULL, nsPluginVariable_DescriptionString, &description);
    if (description)
      info->desc = UTF8ToUTF16(description);

    LOG_IF(ERROR, PluginList::DebugPluginLoading())
        << "Got info for plugin " << filename.value()
        << " Name = \"" << UTF16ToUTF8(info->name)
        << "\", Description = \"" << UTF16ToUTF8(info->desc) << "\".";
  } else {
    LOG_IF(ERROR, PluginList::DebugPluginLoading())
        << "Plugin " << filename.value()
        << " has no GetValue() and probably won't work.";
  }

  // Intentionally not unloading the plugin here, it can lead to crashes.

  return true;
}

// static
void PluginLib::ParseMIMEDescription(
    const std::string& description,
    std::vector<WebPluginMimeType>* mime_types) {
  // We parse the description here into WebPluginMimeType structures.
  // Naively from the NPAPI docs you'd think you could use
  // string-splitting, but the Firefox parser turns out to do something
  // different: find the first colon, then the second, then a semi.
  //
  // See ParsePluginMimeDescription near
  // http://mxr.mozilla.org/firefox/source/modules/plugin/base/src/nsPluginsDirUtils.h#53

  std::string::size_type ofs = 0;
  for (;;) {
    WebPluginMimeType mime_type;

    std::string::size_type end = description.find(':', ofs);
    if (end == std::string::npos)
      break;
    mime_type.mime_type = description.substr(ofs, end - ofs);
    ofs = end + 1;

    end = description.find(':', ofs);
    if (end == std::string::npos)
      break;
    const std::string extensions = description.substr(ofs, end - ofs);
    base::SplitString(extensions, ',', &mime_type.file_extensions);
    ofs = end + 1;

    end = description.find(';', ofs);
    // It's ok for end to run off the string here.  If there's no
    // trailing semicolon we consume the remainder of the string.
    if (end != std::string::npos) {
      mime_type.description = UTF8ToUTF16(description.substr(ofs, end - ofs));
    } else {
      mime_type.description = UTF8ToUTF16(description.substr(ofs));
    }
    mime_types->push_back(mime_type);
    if (end == std::string::npos)
      break;
    ofs = end + 1;
  }
}

}  // namespace NPAPI
<|endoftext|>