text:
/**
 * Orthanc - A Lightweight, RESTful DICOM Store
 * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics
 * Department, University Hospital of Liege, Belgium
 * Copyright (C) 2017-2020 Osimis S.A., Belgium
 *
 * This program 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 3 of
 * the License, or (at your option) any later version.
 *
 * This program 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 program. If not, see
 * <http://www.gnu.org/licenses/>.
 **/

#include "../PrecompiledHeaders.h"
#include "FilesystemHttpHandler.h"

#include "../OrthancException.h"
#include "../SystemToolbox.h"
#include "FilesystemHttpSender.h"

#include <boost/filesystem.hpp>

namespace Orthanc
{
  struct FilesystemHttpHandler::PImpl
  {
    UriComponents baseUri_;
    boost::filesystem::path root_;
  };

  static void OutputDirectoryContent(HttpOutput& output,
                                     const IHttpHandler::Arguments& headers,
                                     const UriComponents& uri,
                                     const boost::filesystem::path& p)
  {
    namespace fs = boost::filesystem;

    std::string s;
    s += "";
    s += "  ";
    s += "
Subdirectories
";
    s += "
";

    if (uri.size() > 0)
    {
      std::string h = Toolbox::FlattenUri(uri) + "/..";
      s += "
..
";
    }

    fs::directory_iterator end;
    for (fs::directory_iterator it(p) ; it != end; ++it)
    {
#if BOOST_HAS_FILESYSTEM_V3 == 1
      std::string f = it->path().filename().string();
#else
      std::string f = it->path().filename();
#endif

      std::string h = Toolbox::FlattenUri(uri) + "/" + f;
      if (fs::is_directory(it->status()))
        s += "
" + f + "
";
    }

    s += "
";
    s += "
Files
";
    s += "
";

    for (fs::directory_iterator it(p) ; it != end; ++it)
    {
#if BOOST_HAS_FILESYSTEM_V3 == 1
      std::string f = it->path().filename().string();
#else
      std::string f = it->path().filename();
#endif

      std::string h = Toolbox::FlattenUri(uri) + "/" + f;
      if (SystemToolbox::IsRegularFile(it->path().string()))
      {
        s += "
" + f + "
";
      }
    }

    s += "
";
    s += "  ";
    s += "";

    output.SetContentType(MimeType_Html);
    output.Answer(s);
  }

  FilesystemHttpHandler::FilesystemHttpHandler(const std::string& baseUri,
                                               const std::string& root) : pimpl_(new PImpl)
  {
    Toolbox::SplitUriComponents(pimpl_->baseUri_, baseUri);
    pimpl_->root_ = root;
    listDirectoryContent_ = false;

    namespace fs = boost::filesystem;
    if (!fs::exists(pimpl_->root_) ||
        !fs::is_directory(pimpl_->root_))
    {
      throw OrthancException(ErrorCode_DirectoryExpected);
    }
  }

  bool FilesystemHttpHandler::Handle(
    HttpOutput& output,
    RequestOrigin /*origin*/,
    const char* /*remoteIp*/,
    const char* /*username*/,
    HttpMethod method,
    const UriComponents& uri,
    const Arguments& headers,
    const GetArguments& arguments,
    const void* /*bodyData*/,
    size_t /*bodySize*/)
  {
    if (!Toolbox::IsChildUri(pimpl_->baseUri_, uri))
    {
      // This URI is not served by this handler
      return false;
    }

    if (method != HttpMethod_Get)
    {
      output.SendMethodNotAllowed("GET");
      return true;
    }

    namespace fs = boost::filesystem;

    fs::path p = pimpl_->root_;
    for (size_t i = pimpl_->baseUri_.size(); i < uri.size(); i++)
    {
      p /= uri[i];
    }

    if (SystemToolbox::IsRegularFile(p.string()))
    {
      FilesystemHttpSender sender(p);
      sender.SetContentType(SystemToolbox::AutodetectMimeType(p.string()));
      output.Answer(sender);   // TODO COMPRESSION
    }
    else if (listDirectoryContent_ &&
             fs::exists(p) &&
             fs::is_directory(p))
    {
      OutputDirectoryContent(output, headers, uri, p);
    }
    else
    {
      output.SendStatus(HttpStatus_404_NotFound);
    }

    return true;
  }
}


text:
#include <game/remote_game_client.hpp>
#include <game/game_server.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <world/world.hpp>

RemoteGameClient::RemoteGameClient():
  server(nullptr)
{
}

RemoteGameClient::~RemoteGameClient()
{
}

void RemoteGameClient::set_game_server(GameServer* server)
{
  this->server = server;
}

void RemoteGameClient::on_connection_closed()
{
  this->server->remove_client(this);
}

void RemoteGameClient::install_callbacks()
{
  this->install_callback("MOVE", std::bind(&GameServer::on_move_request, this->server, std::placeholders::_1));
  this->install_callback("CAST", std::bind(&GameServer::on_cast_request, this->server, std::placeholders::_1));
}

ext: cpp

max_stars_repo_name: louiz/batajelo

max_issues_repo_name: louiz/batajelo

max_forks_repo_name: louiz/batajelo


text:
#include <gazebo/gazebo.hh>
#include <gazebo/physics/physics.hh>
#include <gazebo/common/common.hh>

#include <boost/bind.hpp>
#include <gazebo/msgs/msgs.hh>
#include <gazebo/transport/transport.hh>

#include <thread>
#include "ros/ros.h"
#include "ros/callback_queue.h"
#include "ros/subscribe_options.h"
#include "std_msgs/Float32.h"

namespace gazebo
{
	class SolenoidElectromagnetSpringPlugin : public ModelPlugin
	{
		public: SolenoidElectromagnetSpringPlugin() {}

		private:
			physics::ModelPtr model;
			sdf::ElementPtr sdf;

			physics::JointPtr joint;

			common::PID pid;

			int forceIteration;

			// Set point
			double setPoint;

			// Spring constant
			double kx;

			// Pointer to update event connection
			event::ConnectionPtr updateConnection;

		public: void Load(physics::ModelPtr _model, sdf::ElementPtr _sdf)
		{
			// Safety check
			if (_model->GetJointCount() == 0)
			{
				std::cerr << "You have zero joints! Something is wrong! Not loading plugin." << std::endl;
				return;
			}

			// Store model pointer
			this->model = _model;

			// Store the SDF pointer
			this->sdf = _sdf;

			if (_sdf->HasElement("joint"))
				this->joint = _model->GetJoint(_sdf->Get<std::string>("joint"));
			else
				std::cerr << "Must specify joint to apply a solenoid electromagnet spring at!\n";

			this->kx = 0.0;
			if (_sdf->HasElement("kx"))
				this->kx = _sdf->Get<double>("kx");
			else
				printf("Solenoid electromagnet spring coefficient not specified! Defaulting to: %f\n", this->kx);

			this->setPoint = -0.01;

			if (_sdf->HasElement("set_point"))
				this->setPoint = _sdf->Get<double>("set_point");
			else
				printf("Set point not specified! Defaulting to: %f\n", this->setPoint);

			// Create the node
			this->node = transport::NodePtr(new transport::Node());
			this->node->Init(this->model->GetWorld()->Name());

			// Create a topic name
			std::string topicName = "~/" + this->model->GetName() + "/SolenoidElectromagnet/vel_cmd";

			//std::cout << "topicName: " << topicName << std::endl;

			// Subscribe to the topic, and register a callback
			this->sub = this->node->Subscribe(topicName,
			   &SolenoidElectromagnetSpringPlugin::OnMsg, this);
			//std::cout << "Subscribed to " << this->sub << std::endl;

			this->forceIteration = 0;

			// Initialize ros, if it has not already bee initialized.
		if (!ros::isInitialized())
		{
		  int argc = 0;
		  char **argv = NULL;
		  ros::init(argc, argv, "gazebo_client",
		      ros::init_options::NoSigintHandler);
		}

		// Create our ROS node. This acts in a similar manner to
		// the Gazebo node
		this->rosNode.reset(new ros::NodeHandle("gazebo_client"));

		// Create a named topic, and subscribe to it.
		ros::SubscribeOptions so =
		  ros::SubscribeOptions::create<std_msgs::Float32>(
		      "/" + this->model->GetName() + "/SolenoidElectromagnet/vel_cmd",
		      1,
		      boost::bind(&SolenoidElectromagnetSpringPlugin::OnRosMsg, this, _1),
		      ros::VoidPtr(), &this->rosQueue);
		this->rosSub = this->rosNode->subscribe(so);

		// Spin up the queue helper thread.
		this->rosQueueThread =
		  std::thread(std::bind(&SolenoidElectromagnetSpringPlugin::QueueThread, this));
			std::cout << "Loaded gazebo_joint_solenoid_electromagnet_spring." << std::endl;
		}

		/// \brief A node use for ROS transport
		private: std::unique_ptr<ros::NodeHandle> rosNode;

		/// \brief A ROS subscriber
		private: ros::Subscriber rosSub;

		/// \brief A ROS callbackqueue that helps process messages
		private: ros::CallbackQueue rosQueue;

		/// \brief A thread the keeps running the rosQueue
		private: std::thread rosQueueThread;

		/// \brief Handle an incoming message from ROS
		/// \param[in] _msg A float value that is used to set the velocity
		/// of the Velodyne.
		public: void OnRosMsg(const std_msgs::Float32ConstPtr &_msg)
		{
		  std::cout << "_msg->data: " << _msg->data << std::endl;

		  for (int i = 0; i < 10; i++)
		  	this->joint->SetForce(0, 1000 * float(_msg->data));
		}

		/// \brief ROS helper function that processes messages
		private: void QueueThread()
		{
		  static const double timeout = 0.01;
		  while (this->rosNode->ok())
		  {
		    this->rosQueue.callAvailable(ros::WallDuration(timeout));
		  }
		}

		public: void SetVelocity(const double &_vel)
		{
		  // Set the joint's target velocity.
		  this->model->GetJointController()->SetVelocityTarget(
		      this->joint->GetScopedName(), _vel);
		}

	    private: void OnMsg(ConstVector3dPtr &_msg)
	    {
	      this->SetVelocity(_msg->x());
	    }

		public: void Init()
		{
			// Listen to update event
			this->updateConnection = event::Events::ConnectWorldUpdateBegin(
				std::bind (&SolenoidElectromagnetSpringPlugin::OnUpdate, this) );
		}

		protected: void OnUpdate()
		{
			double current_angle = this->joint->Position(0);
			for (int i = 0; i < 5; i++)
				this->joint->SetForce(0, (this->kx * (this->setPoint - current_angle)));
		}

		/// \brief A node used for transport
	    private: transport::NodePtr node;

	    /// \brief A subscriber to a named topic.
	    private: transport::SubscriberPtr sub;
	};

	GZ_REGISTER_MODEL_PLUGIN(SolenoidElectromagnetSpringPlugin)
}


text:
//==============================================================================
//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_TOOLBOX_BESSEL_FUNCTIONS_SCALAR_JNI_HPP_INCLUDED
#define NT2_TOOLBOX_BESSEL_FUNCTIONS_SCALAR_JNI_HPP_INCLUDED
#include <nt2/toolbox/bessel/functions/jni.hpp>
#include <nt2/include/constants/digits.hpp>
#include <nt2/include/functions/scalar/j0.hpp>
#include <nt2/include/functions/scalar/j1.hpp>
#include <nt2/include/functions/scalar/cospi.hpp>
#include <nt2/sdk/meta/adapted_traits.hpp>
#include <nt2/include/functions/scalar/is_less.hpp>
#include <nt2/include/functions/scalar/is_greater.hpp>
#include <nt2/include/functions/scalar/splat.hpp>
#include <boost/simd/sdk/math.hpp>

/////////////////////////////////////////////////////////////////////////////
// Implementation when type A1 is arithmetic_
/////////////////////////////////////////////////////////////////////////////
namespace nt2 { namespace ext
{
  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::jni_, tag::cpu_
                            , (A0)(A1)
                            , (scalar_< integer_<A0> >)(scalar_< arithmetic_<A1> >)
                            )
  {

    typedef typename boost::dispatch::meta::as_floating<A0,A1>::type result_type;

    NT2_FUNCTOR_CALL(2)
    {
      return nt2::jni(a0, result_type(a1));
    }
  };
} }

/////////////////////////////////////////////////////////////////////////////
// Implementation when type A1 is double
/////////////////////////////////////////////////////////////////////////////
namespace nt2 { namespace ext
{
  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::jni_, tag::cpu_
                            , (A0)(A1)
                            , (scalar_< integer_<A0> >)(scalar_< double_<A1> >)
                            )
  {

    typedef A1 result_type;

    NT2_FUNCTOR_CALL(2)
    {
      if (is_inf(a1)) return Zero<A1>();
    #if defined(BOOST_SIMD_HAS__JN)
      return ::_jn(a0, a1);
    #elif defined(BOOST_SIMD_HAS_JN)
      return ::jn(a0, a1);
    #else
      #error jn not supported
    #endif
    }
  };
} }

/////////////////////////////////////////////////////////////////////////////
// Implementation when type A1 is float
/////////////////////////////////////////////////////////////////////////////
namespace nt2 { namespace ext
{
  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::jni_, tag::cpu_
                            , (A0)(A1)
                            , (scalar_< integer_<A0> >)(scalar_< single_<A1> >)
                            )
  {
    typedef A1 result_type;
    NT2_FUNCTOR_CALL(2)
    {
      result_type x = a1;
      const size_t n1 = nt2::abs(a0);
      result_type sign = a0<Zero<A0>()?cospi(n1):One<A0>();
      if( n1 == 0 )
        return( sign * nt2::j0(x) );
      if( n1 == 1 )
        return( sign * nt2::j1(x) );
      if( n1 == 2 )
        return mul(sign, (mul(Two<result_type>(), nt2::j1(x) / x)  -  nt2::j0(x)) );

      /* continued fraction */
      ptrdiff_t k = 24;
      result_type pk = Two<result_type>()*(result_type(n1) + result_type(k));
      result_type ans = pk;
      result_type xk = sqr(x);
      do {
        pk  = pk - Two<result_type>();
        ans = pk - (xk/ans);
      }
      while( --k > 0 );
      /* backward recurrence */

      pk = One<result_type>();
      /*pkm1 = 1.0/ans;*/
      result_type xinv = rec(x);
      result_type pkm1 = ans * xinv;
      k = n1-1;
      result_type r = 2.0f*k;

      do{
        const result_type pkm2 = (pkm1 * r  -  pk * x) * xinv;
        pk = pkm1;
        pkm1 = pkm2;
        r -= Two<result_type>();
      }
      while( --k > 0 );
      return sign*select(gt(abs(pk), nt2::abs(pkm1)),nt2::j1(x)/pk, nt2::j0(x)/pkm1);
      //     return ::jnf(a0, a1);
    }
  };
} }

#endif

ext: hpp


text:
#include "mex.h"
#include <Eigen/Dense>
#include <cmath>
#include <iostream>
#include "drakeMexUtil.h"
#include "Polynomial.h"

using namespace Eigen;
using namespace std;
/*
 * c++ version of
 *     function xdot = dynamicsRHS(~,~,x,~)
 */

template <typename DerivedA, typename DerivedB>
void dynamicsRHS(const MatrixBase<DerivedA> &x, MatrixBase<DerivedB> &xdot)
{
  xdot << x(1), -x(0)-x(1)*(x(0)*x(0)-1);
}

void mexFunction( int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[] )
{
  if (mxIsDouble(prhs[2])) {
    Map<Vector2d> x(mxGetPrSafe(prhs[2]));
    plhs[0] = mxCreateDoubleMatrix(2,1,mxREAL);
    Map<Vector2d> xdot(mxGetPr(plhs[0]));
    dynamicsRHS(x,xdot);
  } else if (isa(prhs[2],"msspoly")) {
    auto x = msspolyToEigen(prhs[2]);
    Matrix< Polynomiald, 2, 1> xdot;
    dynamicsRHS(x,xdot);
//    cout << xdot << endl;
    plhs[0] = eigenToMSSPoly<2,1>(xdot);
//    plhs[0] = mxCreateDoubleMatrix(2,1,mxREAL);
  } else {
    mexErrMsgIdAndTxt("Drake:VanDerPolCpp:UnknownType","don't know how to handle the datatype passed in for x (yet)");
  }
}

max_stars_repo_name: jhu-asco/drake

max_issues_repo_name: jhu-asco/drake

max_forks_repo_name: jhu-asco/drake


text:
/*
 * Copyright (c) 2017, Niklas Gürtler
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
 * following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
 *    disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
 *    following disclaimer in the documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef LTL_OUTPUT_HH_
#define LTL_OUTPUT_HH_

#include <string>
#include <cstddef>
#include <fstream>

#include <boost/filesystem.hpp>
#include "ltl.hh"
#include "../sysstring.hh"

namespace LTL {
	class Output {
		public:
			Output (const sysstring& outputFilename);
			~Output ();

			void output (Algorithm& result);
			void finish ();
		private:
			std::size_t m_serial;
			boost::filesystem::path m_outputPath, m_tmpPath, m_lxPath;
			std::ofstream m_osLatex;
	};
}

#endif /* LTL_OUTPUT_HH_ */

ext: hh


text:
#include <csapex/model/node.h>

#include <csapex/model/node_modifier.h>
#include <csapex/msg/generic_value_message.hpp>
#include <csapex/msg/generic_vector_message.hpp>
#include <csapex/msg/io.h>
#include <csapex/msg/output.h>
#include <csapex/param/interval_parameter.h>
#include <csapex/param/parameter_factory.h>
#include <csapex/utility/register_apex_plugin.h>

#include <csapex_opencv/roi_message.h>
#include <csapex_point_cloud/msg/indices_message.h>
#include <csapex_point_cloud/msg/point_cloud_message.h>

#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <set>

namespace csapex
{
using namespace connection_types;

class FilterIndicesByRoiClassification : public Node
{
public:
    void setupParameters(csapex::Parameterizable& parameters) override
    {
        parameters.addParameter(param::factory::declareValue<std::string>("classes", param::ParameterDescription("Comma separated list of allowed classification labels"), "0,1"),
                                std::bind(&FilterIndicesByRoiClassification::updateLabels, this));
    }

    void setup(csapex::NodeModifier& node_modifier) override
    {
        in_indices_ = node_modifier.addMultiInput<GenericVectorMessage, pcl::PointIndices>("indices");
        in_rois_ = node_modifier.addInput<GenericVectorMessage, RoiMessage>("rois");
        out_indices_ = node_modifier.addOutput<GenericVectorMessage, pcl::PointIndices>("filtered rois");
    }

    void process() override
    {
        std::shared_ptr<std::vector<pcl::PointIndices> const> in_indices = msg::getMessage<GenericVectorMessage, pcl::PointIndices>(in_indices_);
        std::shared_ptr<std::vector<RoiMessage> const> in_rois = msg::getMessage<GenericVectorMessage, RoiMessage>(in_rois_);
        std::shared_ptr<std::vector<pcl::PointIndices>> out_indices(new std::vector<pcl::PointIndices>);

        if (in_indices->size() != in_rois->size()) {
            throw std::runtime_error("Indices and roi counts do not match!");
        }

        const std::size_t size = in_indices->size();
        for (std::size_t i = 0; i < size; ++i) {
            if (labels_.find(in_rois->at(i).value.classification()) != labels_.end()) {
                out_indices->emplace_back(in_indices->at(i));
            }
        }

        msg::publish<GenericVectorMessage, pcl::PointIndices>(out_indices_, out_indices);
    }

private:
    csapex::Input* in_indices_;
    csapex::Input* in_rois_;
    csapex::Output* out_indices_;
    std::set<int> labels_;

    void updateLabels()
    {
        std::string label_string = readParameter<std::string>("classes");

        labels_.clear();

        std::vector<std::string> labels;
        boost::algorithm::split(labels, label_string, boost::is_any_of(","));
        try {
            std::transform(labels.begin(), labels.end(), std::inserter(labels_, labels_.begin()), [](const std::string& text) { return boost::lexical_cast<int>(text); });
        } catch (boost::bad_lexical_cast ex) {
            node_modifier_->setError("Invalid label in sequence, must be an integer");
            return;
        }
        node_modifier_->setNoError();
    }
};
}  // namespace csapex

CSAPEX_REGISTER_CLASS(csapex::FilterIndicesByRoiClassification, csapex::Node)


text:
// Boost.Bimap
//
// Copyright (c) 2006-2007 Matias Capeletto
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

/// \file tags/support/value_type_of.hpp
/// \brief Consistent way to access the value type of a tagged or untagged type.

#ifndef BOOST_BIMAP_TAGS_SUPPORT_VALUE_TYPE_OF_HPP
#define BOOST_BIMAP_TAGS_SUPPORT_VALUE_TYPE_OF_HPP

#if defined(_MSC_VER)
#pragma once
#endif

#include <boost/config.hpp>

#include <boost/bimap/tags/tagged.hpp>

/** \struct boost::bimaps::tags::support::value_type_of
\brief Metafunction to work with tagged and untagged type uniformly

\code
template< class Type >
struct value_type_of
{
    typedef {UntaggedType} type;
};
\endcode

If the type is tagged this metafunction returns Type::value_type, and if it is not
tagged it return the same type. This allows to work consistenly with tagged and
untagged types.

See also tagged, tag_of.
                                                                                **/

#ifndef BOOST_BIMAP_DOXYGEN_WILL_NOT_PROCESS_THE_FOLLOWING_LINES

namespace boost {
namespace bimaps {
namespace tags {
namespace support {

// value_type_of metafunction

template< class Type >
struct value_type_of
{
    typedef Type type;
};

template< class Type, class Tag >
struct value_type_of< tagged< Type, Tag > >
{
    typedef Type type;
};

} // namespace support
} // namespace tags
} // namespace bimaps
} // namespace boost

#endif // BOOST_BIMAP_DOXYGEN_WILL_NOT_PROCESS_THE_FOLLOWING_LINES

#endif // BOOST_BIMAP_TAGS_SUPPORT_VALUE_TYPE_OF_HPP

max_stars_repo_name: cpp-pm/boost


text: #include <boost/vmd/array/to_tuple.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include "render/mesh/MeshFactory.h"
#include "math/Defines.h"

#include <cmath>

#include <boost/format.hpp>

namespace epsilon
{
	ParametricData Parametric::Sphere(int slices, int stacks)
	{
		ParametricData data;
		float theta, phi;
		int v = 0;
		int next = 0;

		// Generate Vertices
		for (int x = 0; x < (slices+1); x++)
		{
			theta = x * PI / slices;
			for( int y = 0; y < stacks; y++)
			{
				phi = y * TWOPI / stacks;
				float px = sin(theta) * cos(phi);
				float py = cos(theta);
				float pz = -sin(theta) * sin(phi);
				data.vertices.push_back( Vector3( px, py, pz) );
				data.normals.push_back( Vector3( px, py, pz).Normalised() );
			}
		}

		// Generate Faces/Indices
		for (int x = 0; x < slices; x++ )
		{
			for (int y = 0; y < stacks; y++ )
			{
				next = ( y + 1 ) % stacks;
				// first triangle
				data.indices.push_back( v + y + stacks );
				data.indices.push_back( v + next );
				data.indices.push_back( v + y );

				// second triangle
				data.indices.push_back( v + y + stacks );
				data.indices.push_back( v + next + stacks);
				data.indices.push_back( v + next );
			}
			v += stacks;
		}

		return data;
	}

	ParametricData Parametric::Plane(int rows, int columns)
	{
		ParametricData data;

		float c, r;
		int tl, tr, bl, br;
		int v = 0;

		// Generate Vertices
		for ( int x = 0; x < (columns + 1); x++ )
		{
			c = x * ( 1.0f / columns );
			for ( int y = 0; y < (rows + 1); y++ )
			{
				r = y * ( 1.0f / rows );
				data.vertices.push_back( Vector3( (-0.5f + c),
												  0.0f,
												  (-0.5f + r) ) );
			}
		}

		// Generate Normals
		for ( int n = 0; n < ((rows + 1) * (columns + 1)); n++ )
		{
			//data.normals.push_back(Vector3::UP);
			data.normals.push_back(Vector3(0.0f, 1.0f, 0.0f));
			data.colours.push_back(Vector4(1.0f, 1.0f, 1.0f, 1.0f));
		}

		// Generate Faces/Indices
		for ( int x = 0; x < columns; x++ )
		{
			for ( int y = 0; y < rows; y++ )
			{
				bl = v + x + y;
				tl = bl + 1;
				tr = tl + rows + 1;
				br = tr - 1;
				data.indices.push_back(bl);
				data.indices.push_back(tl);
				data.indices.push_back(tr);

				data.indices.push_back(bl);
				data.indices.push_back(tr);
				data.indices.push_back(br);
			}
			v += rows;
		}

		// Generate Texture Coordinates
		for (int x = 0; x < (columns + 1); x++ )
		{
			c = x * ( 1.0f / columns);
			for ( int y = 0; y < (rows + 1); y++ )
			{
				r = y * ( 1.0f / rows );
				data.texCoords.push_back(Vector2(c, r));
			}
		}

		return data;
	}

	MeshFactory::MeshFactory(void)
	{
	}

	MeshFactory::~MeshFactory(void)
	{
	}
	Mesh::Ptr MeshFactory::GenerateGrid(int size, int resolution)
	{
		Mesh::Ptr newGrid = Mesh::Create(GL_LINES);

        newGrid->SetMeshType("GRID");
        newGrid->SetMeshParameters(str(format("size=%d|resolution=%d") % size % resolution));

		VerticesAttrib::List verts;
		//ColourAttrib::List
		float halfWidth = size / 2.0f;

		// if the resolution doesn't evenly divide into the size
		if ( (size % resolution) > 0.0f )
		{
			float diff = (float)(size % resolution);

			// modify the size so that the resolution evenly fits
			halfWidth -= diff / 2.0f;
		}

		// Impossible to have a grid smaller than its resolution
		if ( size > resolution )
		{
			float resStep =  (float)resolution;// / halfWidth;

			// 'Vertical' Lines first
			for ( float x = -halfWidth; x < halfWidth; x += resStep)
			{
				verts.push_back(Vector3(x,0,-halfWidth));
				verts.push_back(Vector3(x,0,halfWidth));
			}

			// 'Horizontal' lines
			for ( float z = -halfWidth; z < halfWidth; z += resStep)
			{
				verts.push_back(Vector3(-halfWidth,0,z));
				verts.push_back(Vector3(halfWidth,0,z));
			}

			// Border
			// TL -> TR
			verts.push_back(Vector3(-halfWidth,0,halfWidth));
			verts.push_back(Vector3(halfWidth,0,halfWidth));
			// TR - BR
			verts.push_back(Vector3(halfWidth,0,halfWidth));
			verts.push_back(Vector3(halfWidth,0,-halfWidth));
			// BR -> BL
			verts.push_back(Vector3(halfWidth,0,-halfWidth));
			verts.push_back(Vector3(-halfWidth,0,-halfWidth));
			// BL -> TL
			verts.push_back(Vector3(-halfWidth,0,-halfWidth));
			verts.push_back(Vector3(-halfWidth,0,halfWidth));
		}

		newGrid->VertexData()
			   ->SetVertices(verts);
			   //->BuildBuffers();

		return newGrid;
	}

	Mesh::Ptr MeshFactory::GenerateCube()
	{
		Mesh::Ptr newCube =  Mesh::Create();

        newCube->SetMeshType("CUBE");

		VerticesAttrib::List verts;
		NormalAttrib::List norms;
		//TexCoordAttrib::List texCoords;
		VertexIndicesBuffer::List faces;

		verts.push_back(Vector3(-0.5, -0.5, -0.5));
        norms.push_back(Vector3(-0.5, -0.5, -0.5));

        verts.push_back(Vector3(-0.5, -0.5, 0.5));
        norms.push_back(Vector3(-0.5, -0.5, 0.5));

        verts.push_back(Vector3(-0.5, 0.5, -0.5));
        norms.push_back(Vector3(-0.5, 0.5, -0.5));

        verts.push_back(Vector3(-0.5, 0.5, 0.5));
        norms.push_back(Vector3(-0.5, 0.5, 0.5));

        verts.push_back(Vector3(0.5, -0.5, -0.5));
        norms.push_back(Vector3(0.5, -0.5, -0.5));

        verts.push_back(Vector3(0.5, -0.5, 0.5));
        norms.push_back(Vector3(0.5, -0.5, 0.5));

        verts.push_back(Vector3(0.5, 0.5, -0.5));
        norms.push_back(Vector3(0.5, 0.5, -0.5));

        verts.push_back(Vector3(0.5, 0.5, 0.5));
        norms.push_back(Vector3(0.5, 0.5, 0.5));

		// left
		faces.push_back(0);
		faces.push_back(1);
		faces.push_back(3);
		faces.push_back(3);
		faces.push_back(2);
		faces.push_back(0);

		// right
		faces.push_back(4);
		faces.push_back(6);
		faces.push_back(7);
		faces.push_back(7);
		faces.push_back(5);
		faces.push_back(4);

		// front
		faces.push_back(7);
		faces.push_back(3);
		faces.push_back(1);
		faces.push_back(1);
		faces.push_back(5);
		faces.push_back(7);

		// back
		faces.push_back(0);
		faces.push_back(2);
		faces.push_back(6);
		faces.push_back(6);
		faces.push_back(4);
		faces.push_back(0);

		// top
		faces.push_back(3);
		faces.push_back(7);
		faces.push_back(2);
		faces.push_back(7);
		faces.push_back(6);
		faces.push_back(2);

		// bottom
		faces.push_back(5);
		faces.push_back(1);
		faces.push_back(4);
		faces.push_back(1);
		faces.push_back(0);
		faces.push_back(4);

		newCube->VertexData()
			   ->SetVertices(verts)
               ->SetNormals(norms)
			   ->SetIndices(faces);

		return newCube;
	}

	Mesh::Ptr MeshFactory::GenerateWireCube()
	{
		Mesh::Ptr newCube = Mesh::Create(GL_LINES);

		VerticesAttrib::List verts;

		verts.push_back(Vector3(-0.5, -0.5, -0.5));
		verts.push_back(Vector3(-0.5, -0.5, 0.5));

		verts.push_back(Vector3(-0.5, -0.5, 0.5));
		verts.push_back(Vector3( 0.5, -0.5, 0.5));

		verts.push_back(Vector3(-0.5, 0.5, -0.5));
		verts.push_back(Vector3(-0.5, 0.5, 0.5));

		verts.push_back(Vector3(-0.5, 0.5, 0.5));
		verts.push_back(Vector3( 0.5, 0.5, 0.5));

		verts.push_back(Vector3(0.5, -0.5, -0.5));
		verts.push_back(Vector3(0.5, -0.5, 0.5));

		verts.push_back(Vector3(-0.5, 0.5, -0.5));
		verts.push_back(Vector3( 0.5, 0.5, -0.5));

		verts.push_back(Vector3(0.5, 0.5, -0.5));
		verts.push_back(Vector3(0.5, 0.5, 0.5));

		verts.push_back(Vector3(-0.5, -0.5, -0.5));
		verts.push_back(Vector3(0.5,  -0.5, -0.5));

		// Corner Verticals
		verts.push_back(Vector3(-0.5, -0.5, -0.5));
		verts.push_back(Vector3(-0.5,  0.5, -0.5));

		verts.push_back(Vector3(0.5, -0.5, -0.5));
		verts.push_back(Vector3(0.5,  0.5, -0.5));

		verts.push_back(Vector3(0.5, -0.5, 0.5));
		verts.push_back(Vector3(0.5, 0.5,  0.5));

		verts.push_back(Vector3(-0.5, -0.5, 0.5));
		verts.push_back(Vector3(-0.5,  0.5, 0.5));

		newCube->VertexData()
			->SetVertices(verts);

		return newCube;
	}

	Mesh::Ptr MeshFactory::GenerateSphere(int slices, int stacks)
	{
		VerticesAttrib::List verts;
		NormalAttrib::List norms;
		ColourAttrib::List colours;

		TexCoordAttrib::List texCoords;
		VertexIndicesBuffer::List faces;

		// This is used purely for normal generation as it requires random access
		VecVec raverts;

		Mesh::Ptr newSphere = Mesh::Create();

        newSphere->SetMeshType("SPHERE");
        newSphere->SetMeshParameters(str(format("slices=%d|stacks=%d") % slices % stacks));

		int vi, next;
		float x, y, z, u, v, theta, phi, a;

		// Calculate Verts and Tex coords
		for ( int i = 0; i < (slices + 1); i++ )
		{
			theta = i * PI / stacks;
			for ( int j = 0; j < stacks; j++ )
			{
				phi = j * 2.0f * PI / stacks;

				// vertices
				x = std::sin(theta) * std::cos(phi);
				y = std::cos(theta);
				z = -std::sin(theta) * std::sin(phi);
				verts.push_back( Vector3(x, y, z) );

                norms.push_back( Vector3(x, y, z) );

				colours.push_back( Vector4(1.0f) );

				raverts.push_back( Vector3(x, y, z) );
				// Tex Coord
				v = std::acos(z) / PI;

                a = x / (std::sin(PI*(v)));

                if (y >= 0)
                {
					u = std::acos( a ) / TWOPI;
                }
				else
                {
					u = (PI + std::acos( a ) ) / TWOPI;
                }
				texCoords.push_back( Vector2(u, v) );
			}
		}

		// Calculate Faces
		vi = 0;
		for ( int i = 0; i < slices; i++ )
		{
			for ( int j = 0; j < stacks; j++ )
			{
				next = (j + 1) % stacks;

				faces.push_back( vi + j + stacks);
				faces.push_back( vi + next);
				faces.push_back( vi + j );

				faces.push_back( vi + j + stacks);
				faces.push_back( vi + next + stacks);
				faces.push_back( vi + next);
			}
			vi += stacks;
		}

		//norms = MeshFactory::GenerateNormals(raverts, faces);

		//newSphere->SetMeshData(verts, norms, texCoords, faces);
		newSphere->VertexData()
				 ->SetVertices(verts)
				 ->SetNormals(norms)
				 ->SetColours(colours)
				 ->SetTexCoords(texCoords)
				 ->SetIndices(faces);
				 //->BuildBuffers();

		return newSphere;
	}

	Mesh::Ptr MeshFactory::GenerateWireSphere()
	{
		Mesh::Ptr newSphere = Mesh::Create(GL_LINES);
		VerticesAttrib::List verts;

		ParametricData data;
		int slices = 8;
		int stacks = 8;
		float theta, phi;

		Vector3 last;
		Vector3 now;
		Vector3 first;
		// Generate Vertices

		for (int x = 0; x < (slices + 1); x++)
		{
			theta = x * PI / slices;
			for (int y = 0; y < stacks; y++)
			{
				phi = y * TWOPI / stacks;
				float px = sin(theta) * cos(phi);
				float py = cos(theta);
				float pz = -sin(theta) * sin(phi);

				now = Vector3(px, py, pz);

				if (y == 0)
				{
					first = now;
				}
				else if ( y % 2 == 0)
				{
					verts.push_back(last);
					verts.push_back(now);
				}
				else if (y == (stacks - 1))
				{
					verts.push_back(now);
					verts.push_back(first);
				}
				verts.push_back(now);

				last = now;
			}
		}

		newSphere->VertexData()
				 ->SetVertices(verts);

		return newSphere;
	}

	Mesh::Ptr MeshFactory::GeneratePlane(int widthSegments, int heightSegments)
	{
		Mesh::Ptr newPlane = Mesh::Create();

		newPlane->SetMeshType("PLANE");
		newPlane->SetMeshParameters(str(format("width_segs=%d|height_segs=%d") % widthSegments % heightSegments));

		ParametricData planeData = Parametric::Plane(heightSegments, widthSegments);

		newPlane->VertexData()
				->SetVertices(planeData.vertices)
				->SetNormals(planeData.normals)
				->SetColours(planeData.colours)
				->SetTexCoords(planeData.texCoords)
				->SetIndices(planeData.indices);
				//->BuildBuffers();

		return newPlane;
	}

	Mesh::Ptr MeshFactory::GenerateTriangle()
	{
		// Create a triangle
		VerticesAttrib::List verts;
		NormalAttrib::List norms;
		ColourAttrib::List colours;
		TexCoordAttrib::List tc;
		VertexIndicesBuffer::List inds;

		Mesh::Ptr newTriangle = Mesh::Create();

		verts.push_back(Vector3(-0.5,-0.5,0));
		verts.push_back(Vector3(0,0.5,0));
		verts.push_back(Vector3(0.5,-0.5,0));

		norms.push_back(Vector3(0,0,-1));
		norms.push_back(Vector3(0,0,-1));
		norms.push_back(Vector3(0,0,-1));

		colours.push_back(Vector4(1,0,0,1));
		colours.push_back(Vector4(0,1,0,1));
		colours.push_back(Vector4(0,0,1,1));

		tc.push_back(Vector2(0,0));
		tc.push_back(Vector2(0,0));
		tc.push_back(Vector2(0,0));

		inds.push_back(0);
		inds.push_back(1);
		inds.push_back(2);

		//newTriangle->SetMeshData(verts, norms, colours, tc, inds);
		newTriangle->VertexData()
				   ->SetVertices(verts)
				   ->SetNormals(norms)
				   ->SetTexCoords(tc)
				   ->SetIndices(inds);
				   //->BuildBuffers();

		return newTriangle;
	}

	Mesh::Ptr MeshFactory::GenerateIcoHedron()
	{
		return Mesh::Create();
	}

	Mesh::Ptr MeshFactory::GenerateOctohedron()
	{
		return Mesh::Create();
	}

	NormalAttrib::List MeshFactory::GenerateNormals(VerticesAttrib::List verts, VertexIndicesBuffer::List indices)
	{
		NormalAttrib::List norms;// = VecVec(verts.size());
		std::vector<VecVec> vertNorms = std::vector<VecVec>(verts.size());
		VerticesAttrib::List faceNormals;
		Vector3 faceNormal, v0, v1, v2, a, b;
		int vec0, vec1, vec2;
		bool found;

		// Generate face normals
		for (VertexIndicesBuffer::List::iterator ind = indices.begin(); ind != indices.end(); ind++ )
		{
			vec0 = *ind++;
			vec1 = *ind++;
			vec2 = *ind++;

			v0 = verts[vec0];
			v1 = verts[vec1];
			v2 = verts[vec2];

			a = v0 - v1;
			b = v2 - v1;
			b.Cross(a).Normalise();

			// add face normal to the vec positions list in vec0, vec1, vec2
			found = false;
			for (VecVec::iterator vnIt = vertNorms[vec0].begin(); vnIt != vertNorms[vec0].end(); vnIt++ )
			{
				if ( *vnIt == b )
				{
					found = true;
					break;
				}
			}

			if ( !found )
			{
				vertNorms[vec0].push_back(b);
			}

			found = false;
			for (VecVec::iterator vnIt = vertNorms[vec1].begin(); vnIt != vertNorms[vec1].end(); vnIt++ )
			{
				if ( *vnIt == b )
				{
					found = true;
					break;
				}
			}

			if ( !found )
			{
				vertNorms[vec1].push_back(b);
			}

			found = false;
			for (VecVec::iterator vnIt = vertNorms[vec2].begin(); vnIt != vertNorms[vec2].end(); vnIt++ )
			{
				if ( *vnIt == b )
				{
					found = true;
					break;
				}
			}

			if ( !found )
			{
				vertNorms[vec2].push_back(b);
			}
		}

		// Calculate the average for all of the face normals for each of the vectors
		for ( std::vector<VecVec>::iterator vnIt = vertNorms.begin(); vnIt != vertNorms.end(); vnIt++ )
		{
			faceNormal = Vector3();

			for (VecVec::iterator vnFnIt = (*vnIt).begin(); vnFnIt != (*vnIt).end(); vnFnIt++ )
			{
				faceNormal += *vnFnIt;
			}
			faceNormal.Normalise();
			norms.push_back(faceNormal);
		}

		return norms;

		 /*normals = list( MeshUtilities.face_normal(vertices, face) for face in faces )

            # Normal Generation

            # Calculate the normals once for each unique vertex and after calcs done,
            # rebuild the vertex list
            vertex_normals = []

            # for each vertex
            for v_inc in range(len(vertices)):
                face_normals = []
                vert_norm = Vector3()

                # for each face
                for f_inc in range(len(faces)):

                    # if the face contains the current vertex
                    if v_inc in faces[f_inc]:
                        # and the faces normal isn't already stored i.e. ignore co-planar face normals
                        if normals[f_inc] not in face_normals:
                            # Store it
                            face_normals.append(normals[f_inc])

                # Calculate the average for all of the face normals found

                for f_norm in face_normals:
                    vert_norm += f_norm
                vert_norm.normalize()

                vertex_normals.append(vert_norm)

            for vi in range(len(self._vert_index)):
                v_ind = self._vert_index[vi]
                self._normals.append(vertex_normals[v_ind])*/
	}

}

max_stars_repo_name: freneticmonkey/epsilonc

max_issues_repo_name: freneticmonkey/epsilonc

max_forks_repo_name: freneticmonkey/epsilonc