text:
//==================================================================================================
/*!
    @file

    @Copyright 2016 Numscale SAS
    @copyright 2016 J.T.Lapreste

    Distributed under the Boost Software License, Version 1.0.
    (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_ARCH_X86_SSE1_SIMD_FUNCTION_DETAIL_PATTERNS_HPP_INCLUDED
#define BOOST_SIMD_ARCH_X86_SSE1_SIMD_FUNCTION_DETAIL_PATTERNS_HPP_INCLUDED

#include <boost/simd/function/detail/shuffle.hpp>
#include <boost/simd/function/detail/default_matcher.hpp>
#include <boost/simd/function/detail/interleave_pattern.hpp>
#include <boost/simd/function/detail/broadcast_pattern.hpp>
#include <boost/simd/function/detail/identity_pattern.hpp>
#include <boost/simd/function/detail/reverse_pattern.hpp>
#include <boost/simd/function/detail/repeat_pattern.hpp>
#include <boost/simd/function/detail/zero_pattern.hpp>
#include <boost/simd/function/detail/slide_pattern.hpp>
#include <boost/simd/function/simd/bitwise_cast.hpp>
#include <boost/simd/constant/zero.hpp>
#include <boost/dispatch/meta/as_floating.hpp>
#include <boost/dispatch/meta/as_integer.hpp>
#include <boost/dispatch/attributes.hpp>

namespace boost { namespace simd { namespace ext
{
  //============================================================================
  // SSE shuffle use the general pattern matcher optimizer with some specific
  // patterns tied to SSE intrinsics.
  //============================================================================
  struct sse_matcher
  {
    // This is true for w/e cardinal
    template<int I0, int I1, typename Permutation>
    struct match2 : details::default_matcher::match2<I0,I1,Permutation>
    {};

    template< int I0, int I1, int I2, int I3, typename Permutation>
    struct match4 : details::default_matcher::match4<I0,I1,I2,I3,Permutation>
    {};

    template< int I0, int I1, int I2, int I3
            , int I4, int I5, int I6, int I7
            , typename Permutation
            >
    struct match8 : details::default_matcher
                           ::match8 < I0, I1, I2, I3, I4, I5, I6, I7
                                    , Permutation
                                    >
    {};

    template< int I0 , int I1 , int I2 , int I3
            , int I4 , int I5 , int I6 , int I7
            , int I8 , int I9 , int I10, int I11
            , int I12, int I13, int I14, int I15
            , typename Permutation
            >
    struct match16 : details::default_matcher
                            ::match16 < I0, I1, I2 , I3 , I4 , I5 , I6 , I7
                                      , I8, I9, I10, I11, I12, I13, I14, I15
                                      , Permutation
                                      >
    {};
  };

  //============================================================================
  // Optimized cardinal 2 pattern + zeroing
  //============================================================================
  template<typename Permutation>
  struct sse_matcher::match2<-1,0,Permutation>
  {
    template<typename T, typename P>
    static BOOST_FORCEINLINE T process(T const& a0, P const&)
    {
      typedef typename boost::dispatch::meta::as_integer<T>::type i_t;
      return bitwise_cast<T>(i_t(_mm_slli_si128( bitwise_cast<i_t>(a0), 8)));
    }
  };

  template<typename Permutation>
  struct sse_matcher::match2<1,-1,Permutation>
  {
    template<typename T, typename P>
    static BOOST_FORCEINLINE T process(T const& a0, P const&)
    {
      typedef typename boost::dispatch::meta::as_integer<T>::type i_t;
      return bitwise_cast<T>(i_t(_mm_srli_si128( bitwise_cast<i_t>(a0), 8)));
    }
  };

  //============================================================================
  // Optimized cardinal 4 pattern
  //============================================================================
  template<typename Permutation>
  struct sse_matcher::match4<0,1,4,5,Permutation>
  {
    template<typename T, typename P>
    static BOOST_FORCEINLINE T process(T const& a0,T const& a1, P const&)
    {
      typedef typename boost::dispatch::meta::as_floating<T>::type f_t;
      return bitwise_cast<T>(f_t( _mm_movelh_ps ( bitwise_cast<f_t>(a0)
                                                , bitwise_cast<f_t>(a1)
                                                )
                                )
                            );
    }
  };

  template<typename Permutation>
  struct sse_matcher::match4<4,5,0,1,Permutation>
  {
    template<typename T, typename P>
    static BOOST_FORCEINLINE T process(T const& a0,T const& a1, P const&)
    {
      typedef typename boost::dispatch::meta::as_floating<T>::type f_t;
      return bitwise_cast<T>( f_t(_mm_movelh_ps ( bitwise_cast<f_t>(a1)
                                                , bitwise_cast<f_t>(a0)
                                                )
                                 )
                            );
    }
  };

  template<typename Permutation>
  struct sse_matcher::match4<2,3,6,7,Permutation>
  {
    template<typename T, typename P>
    static BOOST_FORCEINLINE T process(T const& a0,T const& a1, P const&)
    {
      typedef typename boost::dispatch::meta::as_floating<T>::type f_t;
      return bitwise_cast<T>( f_t(_mm_movehl_ps ( bitwise_cast<f_t>(a1)
                                                , bitwise_cast<f_t>(a0)
                                                )
                                 )
                            );
    }
  };

  template<typename Permutation>
  struct sse_matcher::match4<6,7,2,3,Permutation>
  {
    template<typename T, typename P>
    static BOOST_FORCEINLINE T process(T const& a0,T const& a1, P const&)
    {
      typedef typename boost::dispatch::meta::as_floating<T>::type f_t;
      return bitwise_cast<T>( f_t(_mm_movehl_ps ( bitwise_cast<f_t>(a0)
                                               , bitwise_cast<f_t>(a1)
                                               )
                                 )
                            );
    }
  };

  //============================================================================
  // Optimized cardinal 4 pattern + zeroing
  //============================================================================
  template<typename Permutation>
  struct sse_matcher::match4<0,1,-1,-1,Permutation>
  {
    template<typename T, typename P>
    static BOOST_FORCEINLINE T process(T const& a0, P const&)
    {
      typedef typename boost::dispatch::meta::as_floating<T>::type f_t;
      return bitwise_cast<T>( f_t(_mm_movelh_ps ( bitwise_cast<f_t>(a0)
                                                , Zero<f_t>()
                                                )
                                 )
                            );
    }
  };

  template<typename Permutation>
  struct sse_matcher::match4<2,3,-1,-1,Permutation>
  {
    template<typename T, typename P>
    static BOOST_FORCEINLINE T process(T const& a0, P const&)
    {
      typedef typename boost::dispatch::meta::as_floating<T>::type f_t;
      return bitwise_cast<T>( f_t(_mm_movehl_ps ( Zero<f_t>()
                                                , bitwise_cast<f_t>(a0)
                                                )
                                 )
                            );
    }
  };

  template<typename Permutation>
  struct sse_matcher::match4<-1,-1,0,1,Permutation>
  {
    template<typename T, typename P>
    static BOOST_FORCEINLINE T process(T const& a0, P const&)
    {
      typedef typename boost::dispatch::meta::as_floating<T>::type f_t;
      return bitwise_cast<T>( f_t(_mm_movelh_ps ( Zero<f_t>()
                                                , bitwise_cast<f_t>(a0)
                                                )
                                 )
                            );
    }
  };

  template<typename Permutation>
  struct sse_matcher::match4<-1,-1,2,3,Permutation>
  {
    template<typename T, typename P>
    static BOOST_FORCEINLINE T process(T const& a0, P const&)
    {
      typedef typename boost::dispatch::meta::as_floating<T>::type f_t;
      return bitwise_cast<T>( f_t(_mm_movehl_ps ( bitwise_cast<f_t>(a0)
                                                , Zero<f_t>()
                                                )
                                 )
                            );
    }
  };
} } }

#endif


text:
/*
 * BinarySameConstraint.cpp
 * @brief domain constraint
 * @date Mar 20, 2022
 * @author Yoonwoo Kim
 */

#include <gtsam/base/Testable.h>
#include <gtsam/discrete/DecisionTreeFactor.h>
#include <cpp/planning/BinarySameConstraint.h>

#include <boost/make_shared.hpp>
#include <boost/assign.hpp>

using namespace gtsam;
using namespace std;

namespace gtsam_planner {

/* ************************************************************************* */
BinarySameConstraint::BinarySameConstraint() {}

/* ************************************************************************* */
BinarySameConstraint::BinarySameConstraint(const DiscreteKey& key1, const DiscreteKey& key2)
  : DiscreteFactor(boost::assign::cref_list_of<2>(key1.first)(key2.first)){
    cardinality0_ = key1.second;
    cardinality1_ = key2.second;
  }

/* ************************************************************************* */
void BinarySameConstraint::print(const string& s, const KeyFormatter& formatter) const {
    std::cout << s << "BinarySameConstraint on " << formatter(keys_[0]) << " and "
              << formatter(keys_[1]) << std::endl;
}

/* ************************************************************************* */
double BinarySameConstraint::operator()(const DiscreteValues& values) const {
  return (double)(values.at(keys_[0]) == values.at(keys_[1]));
}

/* ************************************************************************* */
DecisionTreeFactor BinarySameConstraint::toDecisionTreeFactor() const {
  DiscreteKeys keys;
  keys.push_back(DiscreteKey(keys_[0], cardinality0_));
  keys.push_back(DiscreteKey(keys_[1], cardinality1_));
  std::vector<double> table;
  for (size_t i1 = 0; i1 < cardinality0_; i1++)
    for (size_t i2 = 0; i2 < cardinality1_; i2++) table.push_back(i1 == i2);
  DecisionTreeFactor converted(keys, table);
  return converted;
}

/* ************************************************************************* */
DecisionTreeFactor BinarySameConstraint::operator*(const DecisionTreeFactor& f) const {
  // TODO: can we do this more efficiently?
  return toDecisionTreeFactor() * f;
}

/* ************************************************************************* */
}  // namespace gtsam

ext: cpp


text:
/*
@copyright Louis Dionne 2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
 */

#ifndef BOOST_HANA_TEST_TEST_AUTO_MONAD_PLUS_HPP
#define BOOST_HANA_TEST_TEST_AUTO_MONAD_PLUS_HPP

#include <boost/hana/monad_plus.hpp>

#include <boost/hana/applicative.hpp>
#include <boost/hana/assert.hpp>
#include <boost/hana/comparable.hpp>
#include <boost/hana/core/models.hpp>
#include <boost/hana/functional/always.hpp>
#include <boost/hana/functional/compose.hpp>
#include <boost/hana/functor.hpp>

#include <test/auto/monad.hpp>
#include <test/auto/base.hpp>
#include <test/injection.hpp>

namespace boost { namespace hana { namespace test {
    template <typename M>
    auto laws<MonadPlus, M> = [] {
        laws<Monad, M>();
        static_assert(_models<MonadPlus, M>{}, "");

        auto f = compose(lift<M>, injection([]{}));

        for_each(objects<M>, [=](auto a) {
        for_each(objects<M>, [=](auto b) {
        for_each(objects<M>, [=](auto c) {
            // left identity
            BOOST_HANA_CHECK(equal(
                concat(empty<M>(), a),
                a
            ));

            // right identity
            BOOST_HANA_CHECK(equal(
                concat(a, empty<M>()),
                a
            ));

            // associativity
            BOOST_HANA_CHECK(equal(
                concat(a, concat(b, c)),
                concat(concat(a, b), c)
            ));

            // absorption
            BOOST_HANA_CHECK(equal(
                bind(empty<M>(), f),
                empty<M>()
            ));

            BOOST_HANA_CHECK(equal(
                bind(a, always(empty<M>())),
                empty<M>()
            ));
        });});});
    };
}}} // end namespace boost::hana::test

#endif // !BOOST_HANA_TEST_TEST_AUTO_MONAD_PLUS_HPP

ext: hpp

max_stars_repo_name: josephwinston/hana

max_issues_repo_name: josephwinston/hana

max_forks_repo_name: josephwinston/hana


text:
#include "catch.hpp"
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp> // for is_any_of

#include "ciCMS/Model.h"

using namespace cms;

TEST_CASE("cms::Model", ""){
    SECTION("each"){
        Model model;
        std::vector<string> result;
        model.set("name", "John");
        model.set("age", "32");

        REQUIRE(boost::algorithm::join(result, ",") == "");
        model.each([&result](const string& attr, const string& val){
            result.push_back(attr+"="+val);
        });

        REQUIRE(boost::algorithm::join(result, ",") == "age=32,name=John");
    }

    SECTION("each lock; modifying operations during i"){
        Model model;

        model.set("name", "John");
        model.set("age", "32");
        REQUIRE(model.size() == 2);
        REQUIRE(model.get("name_copy") == "");
        REQUIRE(model.get("age_copy") == "");

        std::vector<string> result;
        REQUIRE(boost::algorithm::join(result, ",") == "");

        model.each([&model, &result](const string& attr, const string& val){
            // add copy attribute
            model.set(attr+"_copy", val);
            model.set(attr, val+"_updated");
            // get number of attributes (the above new attribute should not be added yet)
            result.push_back(attr+"="+model.get(attr)+"(size:"+std::to_string(model.size())+")");
        });

        // during the iterations, the model didn't change
        REQUIRE(boost::algorithm::join(result, ",") == "age=32(size:2),name=John(size:2)");
        // immediately after the iterations finished, all changes were effected
        REQUIRE(model.size() == 4);
        REQUIRE(model.get("name") == "John_updated");
        REQUIRE(model.get("age") == "32_updated");
        REQUIRE(model.get("name_copy") == "John");
        REQUIRE(model.get("age_copy") == "32");

    }

    SECTION("actively transform specific attribute"){
        Model model;
        model.set("age", "10");

        float result;

        auto signalConnection = model.transformAttribute("age", [&result](const string& value){
            result = std::stof(value) * 100.0f;
        });

        // .transform already processed the existing value
        REQUIRE(result == 1000.0f);
        // change value
        model.set("age", "25");
        // .transform registers change listener and automatically processes updated value
        REQUIRE(result == 2500.0f);

        // stop transformer
        signalConnection.disable();
        // change value
        model.set("age", "1");
        // didn't transform
        REQUIRE(result == 2500.0f);

        // start transformer again
        signalConnection.enable();
        // change value
        model.set("age", "2");
        // DID transform
        REQUIRE(result == 200.0f);
    }

    SECTION("multiple attributes with same transformer"){
        // create a model with three "float" attributes
        Model model;
        model.set("attrA", "1");
        model.set("attrB", "10");
        model.set("attrC", "100");

        int result=0;

        vector<string> strs;
        boost::split(strs,"attrA,attrC",boost::is_any_of(","));

        // register transformer that counts two-out-of-three attributes
        auto signalConnection = model.transformAttributes(strs, [&result](const string& value){
            result += std::stoi(value);
        }, &result);

        // after registering the transformer the current values of the two attributes are already transformed
        REQUIRE(result == 101);

        // change some values
        model.set("attrB", "20"); // doesn't get tranformer
        model.set("attrC", "5"); // new value does get transformed
        REQUIRE(result == 106);

        model.stopAttributeTransform(&result);
        model.set("attrC", "4"); // new value does get transformed
        REQUIRE(result == 106);
    }

    SECTION("getInt"){
        Model model;
        REQUIRE(model.getInt("x") == 0);
        REQUIRE(model.getInt("x", 101) == 101);
        model.set("x", "5");
        REQUIRE(model.getInt("x") == 5);
        REQUIRE(model.getInt("x", 101) == 5);
        model.set("x", "Not-A-Number");
        REQUIRE(model.getInt("x") == 0);
        REQUIRE(model.getInt("x", 101) == 101);
    }

    SECTION("getFloat"){
        Model model;
        REQUIRE(model.getFloat("x") == 0.f);
        REQUIRE(model.getFloat("x", 101.0f) == 101.f);
        model.set("x", "5.5");
        REQUIRE(model.getFloat("x") == 5.5f);
        REQUIRE(model.getFloat("x", 101.f) == 5.5f);
        model.set("x", "Not-A-Number");
        REQUIRE(model.getFloat("x") == 0.f);
        REQUIRE(model.getFloat("x", 101.f) == 101.f);
    }

    SECTION("setBool getBool"){
        Model model;
        REQUIRE(model.getBool("x") == false);
        REQUIRE(model.getBool("x", true) == true);
        model.set("x", "true");
        REQUIRE(model.getBool("x") == true);
        REQUIRE(model.getBool("x", false) == true);
        model.set("x", "Not-A-Bool");
        REQUIRE(model.getBool("x") == false);
        REQUIRE(model.getBool("x", true) == true);
        model.setBool("x", true);
        REQUIRE(model.getBool("x") == true);
        REQUIRE(model.getBool("x", false) == true);
    }

    SECTION("with(bool)"){
        Model model;
        bool target = true;

        model.with("foo", [&target](const bool& val){ target = val; });
        REQUIRE(target == true);

        model.set("foo", "false");
        REQUIRE(target == true);
        model.with("foo", [&target](const bool& val){ target = val; });
        REQUIRE(target == false);

        model.set("foo", "true");
        REQUIRE(target == false);
        model.with("foo", [&target](const bool& val){ target = val; });
        REQUIRE(target == true);
    }

    SECTION("getVec2"){
        Model m;
        REQUIRE(m.getVec2("attr") == glm::vec2(0.0f, 0.0f));
        m.set("someColor", "255,0,0");
        REQUIRE(m.getVec2("someColor") == glm::vec2(0.0f, 0.0f));
        m.set("someColor", "23");
        REQUIRE(m.getVec2("someColor") == glm::vec2(23.0f,23.0f));
        m.set("someColor", "0,100");
        REQUIRE(m.getVec2("someColor") == glm::vec2(0.0f, 100.0f));
    }

    SECTION("getVec3"){
        Model m;
        REQUIRE(m.getVec3("attr") == glm::vec3(0.0f, 0.0f, 0.0f));
        m.set("someColor", "255,0,0");
        REQUIRE(m.getVec3("someColor") == glm::vec3(255.0f, 0.0f, 0.0f));
        m.set("someColor", "23");
        REQUIRE(m.getVec3("someColor") == glm::vec3(23.0f,23.0f,23.0f));
        m.set("someColor", "0,100");
        REQUIRE(m.getVec3("someColor") == glm::vec3(0.0f, 0.0f, 0.0f));
        m.set("someColor", "0,100");
        REQUIRE(m.getVec3("someColor", glm::vec3(0.0f, 0.0f, 1.0f)) == glm::vec3(0.0f, 0.0f, 1.0f));
    }

    SECTION("with(vec3)"){
        Model model;
        glm::vec3 target = glm::vec3(0.0f);

        model.with("foo", [&target](const glm::vec3& val){ target = val; });
        REQUIRE(target == glm::vec3(0.0f));

        model.set("foo", "10,20,30");
        model.with("foo", [&target](const glm::vec3& val){ target = val; });
        REQUIRE(target == glm::vec3(10.0f,20.0f,30.0f));
    }

    SECTION("getColor"){
        Model m;
        REQUIRE(m.getColor("someColor") == ci::ColorAf(1.0f, 1.0f, 1.0f, 1.0f));
        m.set("someColor", "255,0,0");
        REQUIRE(m.getColor("someColor") == ci::ColorAf(1.0f, 0.0f, 0.0f, 1.0f));
        m.set("someColor", "0,100,0,100");
        REQUIRE(m.getColor("someColor") == ci::ColorAf(0.0f, 100.0f/255.0f, 0.0f, 100.0f/255.0f));
        m.set("someColor", "0,100");
        REQUIRE(m.getColor("someColor") == ci::ColorAf(1.0f, 1.0f, 1.0f, 1.0f));
        m.set("someColor", "0,100");
        REQUIRE(m.getColor("someColor", ci::ColorAf(0.0f, 0.0f, 1.0f, 1.0f)) == ci::ColorAf(0.0f, 0.0f, 1.0f, 1.0f));
        m.set("someColor", "10");
        REQUIRE(m.getColor("someColor") == ci::ColorAf(10.0f/255.0f, 10.0f/255.0f, 10.0f/255.0f, 1.0f));
    }

    SECTION(".transform"){
        // setup
        Model m;
        m.set("name", "john");
        string result;

        // transform
        m.transform([&result](ModelBase& model){
            result = model.get("name");
        }, &result);

        // called with current value
        REQUIRE(result == "john");

        // registers change listener
        m.set("name", "bob");
        REQUIRE(result == "bob");

        // stop transform
        m.stopTransform(&result
        );

        // unregisters change listener
        m.set("name", "henk");
        REQUIRE(result == "bob");
    }
}

max_stars_repo_name: markkorput/ciCMS

max_issues_repo_name: markkorput/ciCMS

max_forks_repo_name: markkorput/ciCMS


text:
/*=============================================================================
    Copyright (c) 2002 2004 2006 Joel de Guzman
    Copyright (c) 2004 Eric Niebler
    Copyright (c) 2010 Daniel James
    http://spirit.sourceforge.net/

    Use, modification and distribution is subject to the Boost Software
    License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
    http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#if !defined(BOOST_SPIRIT_QUICKBOOK_GRAMMARS_IMPL_HPP)
#define BOOST_SPIRIT_QUICKBOOK_GRAMMARS_IMPL_HPP

#include "grammar.hpp"
#include "rule_store.hpp"
#include <boost/spirit/include/classic_symbols.hpp>

namespace quickbook
{
    namespace cl = boost::spirit::classic;

    struct element_info
    {
        enum context {
            in_block = 1,
            in_phrase = 2,
            in_conditional = 4,
        };

        enum type_enum {
            block = 1,
            phrase = 2,
            conditional_or_block = 5
        };

        element_info(type_enum t, cl::rule<scanner>* r)
            : type(t), rule(r) {}

        type_enum type;
        cl::rule<scanner>* rule;
    };

    struct quickbook_grammar::impl
    {
        quickbook::actions& actions;
        rule_store store_;

        // Main Grammar
        cl::rule<scanner> block_start;
        cl::rule<scanner> block_skip_initial_spaces;
        cl::rule<scanner> common;
        cl::rule<scanner> simple_phrase;
        cl::rule<scanner> phrase;
        cl::rule<scanner> extended_phrase;
        cl::rule<scanner> inside_paragraph;
        cl::rule<scanner> command_line;

        // Miscellaneous stuff
        cl::rule<scanner> hard_space;
        cl::rule<scanner> space;
        cl::rule<scanner> blank;
        cl::rule<scanner> eol;
        cl::rule<scanner> phrase_end;
        cl::rule<scanner> comment;
        cl::rule<scanner> macro_identifier;

        // Element Symbols
        cl::symbols<element_info> elements;

        // Doc Info
        cl::rule<scanner> doc_info_details;

        impl(quickbook::actions&);

    private:

        void init_main();
        void init_block_elements();
        void init_phrase_elements();
        void init_doc_info();
    };
}

#endif // BOOST_SPIRIT_QUICKBOOK_GRAMMARS_HPP

max_issues_repo_name: ksundberg/boost-svn

max_forks_repo_name: ksundberg/boost-svn


text:
#ifndef WORKQUEUE_COMPONENT_HPP
#define WORKQUEUE_COMPONENT_HPP

#include <hpx/hpx.hpp>
#include <hpx/include/actions.hpp>
#include <hpx/include/lcos.hpp>
#include <hpx/include/components.hpp>
#include <hpx/include/serialization.hpp>
#include <hpx/include/iostreams.hpp>

#include <boost/variant.hpp>

#include <utility>
#include <iostream>
#include <queue>

namespace workstealing
{
  class workqueue : public hpx::components::locking_hook<
    hpx::components::component_base<workqueue>
    >
    {
    private:
      using funcType = hpx::util::function<void()>;
      std::queue<funcType> tasks;

    public:
      funcType steal();
      HPX_DEFINE_COMPONENT_ACTION(workqueue, steal);
      void addWork(funcType task);
      HPX_DEFINE_COMPONENT_ACTION(workqueue, addWork);
    };
}

HPX_REGISTER_ACTION_DECLARATION(workstealing::workqueue::steal_action, workqueue_steal_action);
HPX_REGISTER_ACTION_DECLARATION(workstealing::workqueue::addWork_action, workqueue_addWork_action);

#endif

max_stars_repo_name: BlairArchibald/HPX-Maxclique

max_issues_repo_name: BlairArchibald/HPX-Maxclique

max_forks_repo_name: BlairArchibald/HPX-Maxclique


text:
//--------------------------------------------------------------------------
// Code generated by the SmartSoft MDSD Toolchain
// The SmartSoft Toolchain has been developed by:
//
// Service Robotics Research Center
// University of Applied Sciences Ulm
// Prittwitzstr. 10
// 89075 Ulm (Germany)
//
// Information about the SmartSoft MDSD Toolchain is available at:
// www.servicerobotik-ulm.de
//
// Please do not modify this file. It will be re-generated
// running the code generator.
//--------------------------------------------------------------------------
#include "CommManipulatorObjects/CommGripperStateCore.hh"

// serialization/deserialization operators
//#include "CommManipulatorObjects/CommGripperStateACE.hh"

// include the hash.idl containing the hash constant
#include "hash.hh"
#include <assert.h>
#include <cstring>
#include <iostream>

// SmartUtils used in from_xml method
#include "smartKnuthMorrisPratt.hh"

#ifdef ENABLE_HASH
	#include <boost/functional/hash.hpp>
#endif

namespace CommManipulatorObjects
{
	const char* CommGripperStateCore::getCompiledHash()
	{
		return CommManipulatorObjectsIDL::REPO_HASH;
	}

	void CommGripperStateCore::getAllHashValues(std::list<std::string> &hashes)
	{
		// get own hash value
		hashes.push_back(getCompiledHash());
	}

	void CommGripperStateCore::checkAllHashValues(std::list<std::string> &hashes)
	{
		// check own hash value
		if (strcmp(getCompiledHash(), hashes.front().c_str()) != 0)
		{
			std::cerr << "###################################################" << std::endl;
			std::cerr << "WARNING: HASHES OF COMMUNICATION OBJECTS MISSMATCH!" << std::endl;
			std::cerr << "CommGripperStateCore hash" << std::endl;
			std::cerr << "Expected: " << getCompiledHash() << std::endl;
			std::cerr << "Received: " << hashes.front() << std::endl;
			std::cerr << "###################################################" << std::endl;
		}
		assert(strcmp(getCompiledHash(), hashes.front().c_str()) == 0);
		hashes.pop_front();

	}

	#ifdef ENABLE_HASH
	size_t CommGripperStateCore::generateDataHash(const DATATYPE &data)
	{
		size_t seed = 0;

		std::vector<ACE_CDR::Float>::const_iterator data_posIt;
		for(data_posIt=data.pos.begin(); data_posIt!=data.pos.end(); data_posIt++) {
			boost::hash_combine(seed, *data_posIt);
		}
		boost::hash_combine(seed, data.is_valid);
		boost::hash_combine(seed, data.graspState);
		boost::hash_combine(seed, data.graspState_valid);

		return seed;
	}
	#endif

	// default constructor
	CommGripperStateCore::CommGripperStateCore()
	:	idl_CommGripperState()
	{
		setPos(std::vector<float>());
		setIs_valid(false);
		setGraspState(CommManipulatorObjects::GripperGraspState());
		setGraspState_valid(false);
	}

	CommGripperStateCore::CommGripperStateCore(const DATATYPE &data)
	:	idl_CommGripperState(data)
	{  }

	CommGripperStateCore::~CommGripperStateCore()
	{  }

	void CommGripperStateCore::to_ostream(std::ostream &os) const
	{
	  os << "CommGripperState(";
	  std::vector<float>::const_iterator posIt;
	  std::vector<float> posList = getPosCopy();
	  for(posIt=posList.begin(); posIt!=posList.end(); posIt++) {
	  	os << *posIt << " ";
	  }
	  os << getIs_valid() << " ";
	  getGraspState().to_ostream(os);
	  os << getGraspState_valid() << " ";
	  os << ") ";
	}

	// convert to xml stream
	void CommGripperStateCore::to_xml(std::ostream &os, const std::string &indent) const {
		size_t counter = 0;

		std::vector<float>::const_iterator posIt;
		std::vector<float> posList = getPosCopy();
		counter = 0;
		os << indent << "<posList n=\"" << posList.size() << "\">";
		for(posIt=posList.begin(); posIt!=posList.end(); posIt++) {
			os << indent << "<pos i=\"" << counter++ << "\">" << *posIt << "</pos>";
		}
		os << indent << "</posList>";
		os << indent << "<is_valid>" << getIs_valid() << "</is_valid>";
		os << indent << "<graspState>";
		getGraspState().to_xml(os, indent);
		os << indent << "</graspState>";
		os << indent << "<graspState_valid>" << getGraspState_valid() << "</graspState_valid>";
	}

	// restore from xml stream
	void CommGripperStateCore::from_xml(std::istream &is) {
		size_t counter = 0;

		static const Smart::KnuthMorrisPratt kmp_posList("<posList n=\"");
		static const Smart::KnuthMorrisPratt kmp_pos("\">");
		static const Smart::KnuthMorrisPratt kmp_is_valid("<is_valid>");
		static const Smart::KnuthMorrisPratt kmp_graspState("<graspState>");
		static const Smart::KnuthMorrisPratt kmp_graspState_valid("<graspState_valid>");

		if(kmp_posList.search(is)) {
			size_t numberElements;
			is >> numberElements;
			float posItem;
			std::vector<float> posList;
			kmp_pos.search(is);
			for(counter=0; counter<numberElements; counter++) {
				if(kmp_pos.search(is)) {
					is >> posItem;
					posList.push_back(posItem);
				}
			}
			setPos(posList);
		}
		if(kmp_is_valid.search(is)) {
			bool is_validItem;
			is >> is_validItem;
			setIs_valid(is_validItem);
		}
		if(kmp_graspState.search(is)) {
			CommManipulatorObjects::GripperGraspState graspStateItem;
			graspStateItem.from_xml(is);
			setGraspState(graspStateItem);
		}
		if(kmp_graspState_valid.search(is)) {
			bool graspState_validItem;
			is >> graspState_validItem;
			setGraspState_valid(graspState_validItem);
		}
	}

	/*
	void CommGripperStateCore::get(ACE_Message_Block *&msg) const
	{
		// start with a default internal buffer size(will automatically grow if needed)
		ACE_OutputCDR cdr(ACE_DEFAULT_CDR_BUFSIZE);

		CommManipulatorObjectsIDL::HashList hashes;
		getAllHashValues(hashes);
		cdr << static_cast<ACE_CDR::Long>(hashes.size());
		for(CommManipulatorObjectsIDL::HashList::const_iterator it=hashes.begin(); it!=hashes.end(); it++)
		{
			cdr << ACE_CString(it->c_str());
		}

		// Here the actual serialization takes place using the OutputCDR serialization operator<<
		// (see CommGripperStateACE.hh)
		cdr << idl_CommGripperState;

	#ifdef ENABLE_HASH
		ACE_CDR::ULong data_hash = generateDataHash(idl_CommGripperState);
		cdr << data_hash;
		// std::cout << "CommGripperStateCore: current data hash: " << data_hash << std::endl;
	#endif

		// return a shallow copy of the serialized message
		// (no data is actually copied, only the internal reference counter is incremented)
		// in order to prevent memory leaks the caller of this get(msg) method must
		// manually free the memory by calling the release() method of the message block msg
		msg = cdr.begin()->duplicate();
	}

	void CommGripperStateCore::set(const ACE_Message_Block *msg)
	{
		ACE_InputCDR cdr(msg);

		CommManipulatorObjectsIDL::HashList hashes;
		ACE_CDR::Long hashes_size;
		cdr >> hashes_size;
		for(int i=0; i<hashes_size; ++i)
		{
			ACE_CString hash;
			cdr >> hash;
			hashes.push_back(hash.c_str());
		}
		checkAllHashValues(hashes);

		// Here the actual de-serialization takes place using the InputCDR serialization operator>>
		// (see CommGripperStateACE.hh)
		cdr >> idl_CommGripperState;

	#ifdef ENABLE_HASH
		ACE_CDR::Long data_hash;
		cdr >> data_hash;
		ACE_CDR::Long own_hash = generateDataHash(idl_CommGripperState);
		assert(data_hash == own_hash);
		// std::cout << "CommGripperStateCore: own data hash: " << own_hash << "; received data hash: " << data_hash << std::endl;
	#endif
	}
	*/
} /* namespace CommManipulatorObjects */

ext: cc


text:
// __BEGIN_LICENSE__
// Copyright (C) 2006-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__

/*
  *  GPUProgram.cpp
  *  VWGPU
  *
  *  Created by Ian Saxton on 5/17/06.
  *
  */

 #include <fstream>
 #include <iostream>

 #include <boost/algorithm/string.hpp>

 #include <vw/Core/Exception.h>
 #include <vw/GPU/GPUProgram.h>
 #include <vw/GPU/Utilities.h>

using std::string;
using std::pair;
using std::vector;
using std::map;

namespace vw { namespace GPU {

  int maxErrorLength = 2048;

  char errorString[2048];

  string shader_base_path = "";

  bool shader_assembly_cache_enabled = false;

  string shader_assembly_cache_path = "";

  ShaderCompilationStatusEnum shaderCompilationStatus = SHADER_COMPILATION_STATUS_SUCCESS;

  //########################################################################
  //#    GLSL - Program
  //########################################################################

  bool GPUProgram_GLSL::Link(GPUVertexShader_GLSL& vertex, GPUFragmentShader_GLSL& fragment) {
    program = glCreateProgramObjectARB();
    if(vertex.is_compiled())
      glAttachObjectARB(program, vertex.get_shader());
    if(fragment.is_compiled())
      glAttachObjectARB(program, fragment.get_shader());
    glLinkProgramARB(program);
    GLsizei errorStringLength;
    GLint isCompiled;
    glGetInfoLogARB(program, maxErrorLength, &errorStringLength, errorString);
    glGetObjectParameterivARB(program, GL_OBJECT_LINK_STATUS_ARB, &isCompiled);
    if(!isCompiled) {
      printf("***PROGRAM LINKER***\n%s\n", errorString);
      program = 0;
      return false;
    }
    return true;
  }

  //########################################################################
  //#    GLSL - Vertex Shader
  //########################################################################

  bool GPUVertexShader_GLSL::compile(const string& vertexString) {
    const char* cStr = vertexString.c_str();
    shader = glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB);
    glShaderSourceARB(shader, 1, (const GLcharARB**) &cStr, NULL);
    glCompileShaderARB(shader);
    GLsizei errorStringLength;
    GLint isCompiled;
    glGetInfoLogARB(shader, maxErrorLength, &errorStringLength, errorString);
    glGetObjectParameterivARB(shader, GL_OBJECT_COMPILE_STATUS_ARB, &isCompiled);
    if(!isCompiled) {
      gpu_log("\n*********GLSL Vertex Shader Compilation Error*********\n");
      gpu_log(errorString);
      gpu_log("********************************************************\n");
      gpu_log(vertexString.c_str());
      gpu_log("******************************************************\n");
      return false;
    }
    return true;
  }

  //########################################################################
  //#    GLSL - Fragment Shader
  //########################################################################

  bool GPUFragmentShader_GLSL::compile(const string& fragmentString) {
    const char* cStr = fragmentString.c_str();
    shader = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);
    glShaderSourceARB(shader, 1, (const GLcharARB**) &cStr, NULL);

    glCompileShaderARB(shader);
    GLint isCompiled;
    GLsizei errorStringLength;
    glGetInfoLogARB(shader, maxErrorLength, &errorStringLength, errorString);
    glGetObjectParameterivARB(shader, GL_OBJECT_COMPILE_STATUS_ARB, &isCompiled);
    if(!isCompiled) {
      gpu_log("\n*********GLSL Fragment Shader Compilation Error*********\n");
      gpu_log(errorString);
      gpu_log("********************************************************\n");
      gpu_log(fragmentString.c_str());
      gpu_log("\n********************************************************\n");

      return false;
    }
    return true;
  }

  //########################################################################
  //#    CG Specific Code
  //########################################################################

#if defined(VW_HAVE_PKG_CG) && VW_HAVE_PKG_CG==1

  CGerror CGCheckError();

  //########################################################################
  //#    GPUShader_CG
  //########################################################################

  CGcontext cgContext = NULL;
  void InitCGContext();
  void CGErrorCallback();

  GPUShader_CG::GPUShader_CG() {
    program = NULL;
  }

  GPUShader_CG::~GPUShader_CG() {
    if(program)
      cgDestroyProgram(program);
  }

  bool GPUShader_CG::compile_source_with_string(const char *sourceString, CGprofile profile, const char *entry, const char **args) {
    InitCGContext();
    // Delete old program object
    if(program)
      cgDestroyProgram(program);
    // Compile
    GPUShader_CG::profile = profile;
    program = cgCreateProgram(cgContext, CG_SOURCE, sourceString, profile, entry, args);
    // Check for errors
    CGerror error = cgGetError();
    if(!cgIsProgramCompiled(program)) {
      program = NULL;
      return false;
    }
    // Load into cgGL
    cgGLLoadProgram(program);
    return true;
  }

  bool GPUShader_CG::compile_source_with_file(const char *sourceString, CGprofile profile, const char *entry, const char **args) {
    InitCGContext();
    // Delete old program object
    if(program)
      cgDestroyProgram(program);
    // Compile
    program = cgCreateProgramFromFile(cgContext, CG_SOURCE, sourceString, profile, entry, args);
    GPUShader_CG::profile = profile;
    // printf("%s", cgGetLastListing(cgContext));
    // Check for errors
    CGerror error = cgGetError();
    if(!cgIsProgramCompiled(program)) {
      printf("*** ERROR (GPUShader_CG::compile_source_with_string()  Compile Failed. Exiting...\n");
      program = NULL;
      exit(0);
    }
    // Load into cgGL
    cgGLLoadProgram(program);
    return true;
  }

  bool GPUShader_CG::save_compiled_file(const char *file) {
    std::ofstream outFile(file);
    if(!outFile) {
      return false;
    }
    if(!is_compiled()) {
      return false;
    }
    const char *entryString = cgGetProgramString(program, CG_PROGRAM_ENTRY);
    outFile << entryString << " ";
    const char *profileString = cgGetProgramString(program, CG_PROGRAM_PROFILE);
    outFile << profileString << " ";
    const char *objectString = cgGetProgramString(program, CG_COMPILED_PROGRAM);
    outFile << objectString;

    outFile.close();
    return true;
  }

  bool GPUShader_CG::load_compiled_file(const char *file) {
    InitCGContext();
    // Input File
    std::ifstream inFile(file);
    if(!inFile) {
      return false;
    }
    // Read Entry and Profile Strings
    string entryString;
    inFile >> entryString;
    string profileString;
    inFile >> profileString;

    CGprofile profile = cgGetProfile(profileString.c_str());
    if(profile == CG_PROFILE_UNKNOWN) {
      return false;
    }
    // Read Object String
    int objectStringStart = ((int) inFile.tellg()) + 1;
    inFile.seekg(0, std::ios::end);
    int objectStringLength = ((int) inFile.tellg()) - objectStringStart;
    inFile.seekg(objectStringStart, std::ios::beg);
    char *objectString = (char*) malloc(objectStringLength + 1);
    inFile.read(objectString, objectStringLength);
    inFile.close();
    objectString[objectStringLength] = 0;
    // Delete old program object
    if(program)
      cgDestroyProgram(program);
    CGCheckError();
    program = cgCreateProgram(cgContext, CG_OBJECT, objectString, profile, entryString.c_str(), NULL);
    GPUShader_CG::profile = profile;
    // Check for errors
    if(!is_compiled() || CGCheckError()) {
      program = NULL;
      return false;
    }
    CGCheckError();
    cgGLLoadProgram(program);
    if(CGCheckError()) {
      return false;
    }
    return true;
  }

  void GPUShader_CG::install() {
    //cgGLEnableProfile(CG_PROFILE_FP30);
    cgGLEnableProfile(profile);
    cgGLBindProgram(program);
  }

  void GPUShader_CG::uninstall() {
    cgGLDisableProfile(profile);
  }

  //########################################################################
  //#                           CG - Internal Globals                      #
  //########################################################################

  CGerror CGCurrentError = (CGerror) 0;

  void InitCGContext() {
    if(!cgContext) {
      //cgSetErrorCallback(&CGErrorCallback);
      cgContext = cgCreateContext();
    }
  }

  void CGErrorCallback() {
    while(1) {
      CGerror error = cgGetError();
      if(error == 0)
        break;
      else {
        CGCurrentError = error;
        printf("***CG ERROR:   %s \n", cgGetErrorString(error));
      }
    }
  }

  CGerror CGCheckError() {
    CGerror temp = CGCurrentError;
    CGCurrentError = (CGerror) 0;
    return temp;
  }

#endif // ifdef VW_HAVE_PKG_CG___

  //#############################################################################################
  //#    Creation Free Functions - GLSL
  //#############################################################################################

  typedef pair<pair<string, string>, pair<vector<int>, vector<int> > > GPUProgramKey;

  GPUProgram_GLSL* create_gpu_program_glsl_string(const string& fragmentString, const vector<int>& fragmentAttributes,
                                                  const string& vertexString, const vector<int>& vertexAttributes)
  {
    shaderCompilationStatus = SHADER_COMPILATION_STATUS_SUCCESS_FILE;
    static char charBuffer1[32];
    static char charBuffer2[32];
    // Vertex
    GPUVertexShader_GLSL vertexShader;
    if(!vertexString.empty()) {
      string vertReplacedString;
      const string* sourceString = &vertexString;
      if(vertexAttributes.size()) {
        TokenReplacer tr;
        for(unsigned i=0; i < vertexAttributes.size(); i++) {
          sprintf(charBuffer1, "%i", i+1);
          sprintf(charBuffer2, "%i", vertexAttributes[i]);
          tr.AddVariable(charBuffer1, charBuffer2);
        }
        tr.Replace(vertexString, vertReplacedString);
        sourceString = &vertReplacedString;
      }
      if(!vertexShader.compile(*sourceString)) {
        shaderCompilationStatus = SHADER_COMPILATION_STATUS_ERROR_COMPILE;
        throw(Exception("GPUProgram creation failed."));
      }
    }
    // Fragment
    GPUFragmentShader_GLSL fragmentShader;
    if(!fragmentString.empty()) {
      string fragReplacedString;
      const string* sourceString = &fragmentString;
      if(fragmentAttributes.size()) {
        TokenReplacer tr;
        string variable;
        for(unsigned i=0; i < fragmentAttributes.size(); i++) {
          sprintf(charBuffer1, "%i", i+1);
          sprintf(charBuffer2, "%i", fragmentAttributes[i]);
          tr.AddVariable(charBuffer1, charBuffer2);
        }
        tr.Replace(fragmentString, fragReplacedString);
        sourceString = &fragReplacedString;
      }
      if(!fragmentShader.compile(*sourceString)) {
        shaderCompilationStatus = SHADER_COMPILATION_STATUS_ERROR_COMPILE;
        throw(Exception("GPUProgram creation failed."));
      }
    }
    // Program
    GPUProgram_GLSL* program = new GPUProgram_GLSL;
    if(!program->Link(vertexShader, fragmentShader)) {
      shaderCompilationStatus = SHADER_COMPILATION_STATUS_ERROR_LINK;
      delete program;
      throw(Exception("GPUProgram creation failed."));
    }
    return program;
  }

  static std::map<GPUProgramKey, GPUProgram_GLSL*> program_cache_glsl;

  GPUProgram_GLSL* create_gpu_program_glsl(const string& fragmentPath, const vector<int>& fragmentAttributes,
                                           const string& vertexPath, const vector<int>& vertexAttributes)
  {
    // Static
    // Check cache
    GPUProgramKey programKey = GPUProgramKey(pair<string, string>(fragmentPath, vertexPath), pair<vector<int>, vector<int> >(fragmentAttributes, vertexAttributes));
    map<GPUProgramKey, GPUProgram_GLSL*>::iterator iter_prog;
    iter_prog = program_cache_glsl.find(programKey);
    if(iter_prog != program_cache_glsl.end()) {
      shaderCompilationStatus = SHADER_COMPILATION_STATUS_SUCCESS_CACHE;
      return (*iter_prog).second;
    }
    // Vertex File Read
    string vertexString;
    GPUVertexShader_GLSL vertexShader;
    if(!vertexPath.empty()) {
      std::map<std::string, const char*>::iterator iter_map = standard_shaders_map.find((vertexPath).c_str());
      if(iter_map != standard_shaders_map.end()) {
        vertexString = (*iter_map).second;
      }
      else if(!ReadFileAsString(shader_base_path + vertexPath, vertexString)) {
        shaderCompilationStatus = SHADER_COMPILATION_STATUS_ERROR_FILE;
        throw(Exception("GPUProgram creation failed."));
      }
    }
    // Fragment File Read
    string fragmentString;
    if(!fragmentPath.empty()) {
      std::map<std::string, const char*>::iterator iter_map = standard_shaders_map.find((fragmentPath).c_str());
      if(iter_map != standard_shaders_map.end()) {
        fragmentString = (*iter_map).second;
      }
      else if(!ReadFileAsString(shader_base_path + fragmentPath, fragmentString)) {
        shaderCompilationStatus = SHADER_COMPILATION_STATUS_ERROR_FILE;
        throw(Exception("GPUProgram creation failed."));
      }
    }
    // Compile Strings
    GPUProgram_GLSL* program = create_gpu_program_glsl_string(fragmentString, fragmentAttributes, vertexString, vertexAttributes);
    if(program)
      program_cache_glsl[programKey] = program;
    return program;
  }

  //#############################################################################################
  //#    Creation Free Functions - CG
  //#############################################################################################

#if defined(VW_HAVE_PKG_CG) && VW_HAVE_PKG_CG==1

  GPUProgram_CG* create_gpu_program_cg_string(const string& fragmentString, const vector<int>& fragmentAttributes,
                                              const string& vertexString, const vector<int>& vertexAttributes)
  {
    std::auto_ptr<GPUShader_CG> vertexShader(NULL);
    std::auto_ptr<GPUShader_CG> fragmentShader(NULL);
    static char charBuffer1[32];
    static char charBuffer2[32];
    // VERTEX
    if(!vertexString.empty()) {
      vertexShader.reset(new GPUShader_CG());
      string vertReplacedString;
      const string* sourceString = &vertexString;
      if(vertexAttributes.size()) {     // Specialize String
        TokenReplacer tr;
        string variable;
        for(int i=0; i < vertexAttributes.size(); i++) {
          sprintf(charBuffer1, "%i", i+1);
          sprintf(charBuffer2, "%i", vertexAttributes[i]);
          tr.AddVariable(charBuffer1, charBuffer2);
        }
        tr.Replace(vertexString, vertReplacedString);
        sourceString = &vertReplacedString;
      }
      if(!vertexShader->compile_source_with_string(sourceString->c_str(), CG_PROFILE_VP30, "main", NULL)) {
        shaderCompilationStatus = SHADER_COMPILATION_STATUS_ERROR_COMPILE;
        throw(Exception("GPUProgram creation failed."));
      }
    }
    // FRAGMENT
    if(!fragmentString.empty()) {
      fragmentShader.reset(new GPUShader_CG());
      string fragReplacedString;
      const string* sourceString = &fragmentString;
      if(fragmentAttributes.size()) {     // Specialize String
        TokenReplacer tr;
        string variable;
        for(int i=0; i < fragmentAttributes.size(); i++) {
          sprintf(charBuffer1, "%i", i+1);
          sprintf(charBuffer2, "%i", fragmentAttributes[i]);
          tr.AddVariable(charBuffer1, charBuffer2);
        }
        tr.Replace(fragmentString, fragReplacedString);
        sourceString = &fragReplacedString;
      }
      if(!fragmentShader->compile_source_with_string(sourceString->c_str(), CG_PROFILE_FP30, "main", NULL)) {
        shaderCompilationStatus = SHADER_COMPILATION_STATUS_ERROR_COMPILE;
        throw(Exception("GPUProgram creation failed."));
      }
    }
    // PROGRAM - Make new program, put in cache and return it
    GPUProgram_CG* program = new GPUProgram_CG(vertexShader.get(), fragmentShader.get());
    vertexShader.release();
    fragmentShader.release();
    shaderCompilationStatus = SHADER_COMPILATION_STATUS_SUCCESS_FILE;
    return program;
  }

  std::map<GPUProgramKey, GPUProgram_CG*> program_cache_cg;

  GPUProgram_CG* create_gpu_program_cg(const string& fragmentPath, const vector<int>& fragmentAttributes,
                                       const string& vertexPath, const vector<int>& vertexAttributes)
  {

    char charBuffer1[256];
    char charBuffer2[32];
    shaderCompilationStatus = SHADER_COMPILATION_STATUS_SUCCESS_FILE;
    // Check cache for program
    GPUProgramKey programKey = GPUProgramKey(pair<string, string>(fragmentPath, vertexPath), pair<vector<int>, vector<int> >(fragmentAttributes, vertexAttributes));
    map<GPUProgramKey, GPUProgram_CG*>::iterator iter_prog;
    iter_prog = program_cache_cg.find(programKey);
    if(iter_prog != program_cache_cg.end()) {
      shaderCompilationStatus = SHADER_COMPILATION_STATUS_SUCCESS_CACHE;
      return (*iter_prog).second;
    }

    //
    std::auto_ptr<GPUShader_CG> vertexShader(NULL);
    std::auto_ptr<GPUShader_CG> fragmentShader(NULL);
    // Get Source Strings - Try to find in STD virtual directory, then try the real path
    string vertRawString;
    string fragRawString;
    string fragAssemblyFilePath;
    bool fragComplete = false;
    bool fail = false;
    // VERTEX
    if(!vertexPath.empty()) {
      std::map<std::string, const char*>::iterator iter_map = standard_shaders_map.find((vertexPath).c_str());
      if(iter_map != standard_shaders_map.end()) {
        vertRawString = (*iter_map).second;
      }
      else if(!ReadFileAsString(shader_base_path + vertexPath, vertRawString)) {
        shaderCompilationStatus = SHADER_COMPILATION_STATUS_ERROR_FILE;
        fail = true;
      }
    }
    // FRAGMENT
    if(!fail && !fragmentPath.empty()) {
      // If using assembly caching, create assembly path and attempt to load it.
      if(shader_assembly_cache_enabled) {
        string modifiedFragmentPath = fragmentPath;
        boost::algorithm::replace_all(modifiedFragmentPath, "/", "_");
        fragAssemblyFilePath = shader_assembly_cache_path + modifiedFragmentPath;
        for(int i=0; i < fragmentAttributes.size(); i++) {
          sprintf(charBuffer1, "_%i", fragmentAttributes[i]);
          fragAssemblyFilePath += charBuffer1;
        }
        fragAssemblyFilePath += ".cache";
        if(fragmentShader->load_compiled_file(fragAssemblyFilePath.c_str())) {
          fragComplete = true;
        }
      }
      // If necessary, read source string from file
      if(!fragComplete) {
        std::map<std::string, const char*>::iterator iter_map = standard_shaders_map.find((fragmentPath).c_str());
        if(iter_map != standard_shaders_map.end()) {
          fragRawString = (*iter_map).second;
        }
        else if(!ReadFileAsString(shader_base_path + fragmentPath, fragRawString)) {
          shaderCompilationStatus = SHADER_COMPILATION_STATUS_ERROR_FILE;
          fail = true;
        }
      }
    }
    // Specialize Strings and Compile Shaders
    // VERTEX
    if(!fail && !vertexPath.empty()) {
      vertexShader.reset(new GPUShader_CG);
      string vertReplacedString;
      string& sourceString = vertRawString;
      if(vertexAttributes.size()) {     // Specialize String
        TokenReplacer tr;
        string variable;
        for(int i=0; i < vertexAttributes.size(); i++) {
          sprintf(charBuffer1, "%i", i+1);
          sprintf(charBuffer2, "%i", vertexAttributes[i]);
          tr.AddVariable(charBuffer1, charBuffer2);
        }
        tr.Replace(vertRawString, vertReplacedString);
        sourceString = vertReplacedString;
      }
      if(!vertexShader->compile_source_with_string(sourceString.c_str(), CG_PROFILE_VP30, "main", NULL)) {
        shaderCompilationStatus = SHADER_COMPILATION_STATUS_ERROR_COMPILE;
        return NULL;
      }
    }
    // FRAGMENT
    if(!fail && !fragmentPath.empty() && !fragComplete) {
      fragmentShader.reset(new GPUShader_CG);
      string fragReplacedString;
      string& sourceString = fragRawString;
      if(fragmentAttributes.size()) {     // Specialize String
        TokenReplacer tr;
        string variable;
        for(int i=0; i < fragmentAttributes.size(); i++) {
          sprintf(charBuffer1, "%i", i+1);
          sprintf(charBuffer2, "%i", fragmentAttributes[i]);
          tr.AddVariable(charBuffer1, charBuffer2);
        }
        tr.Replace(fragRawString, fragReplacedString);
        sourceString = fragReplacedString;
      }
      if(!fragmentShader->compile_source_with_string(sourceString.c_str(), CG_PROFILE_FP30, "main", NULL)) {
        shaderCompilationStatus = SHADER_COMPILATION_STATUS_ERROR_COMPILE;
        fail = true;
      }
      if(shader_assembly_cache_enabled) {
        if(fragmentShader->save_compiled_file(fragAssemblyFilePath.c_str())) {
        }
      }
    }

    if(fail)
      throw(Exception("GPUProgram creation failed."));
    // PROGRAM - Make new program, put in cache and return it
    GPUProgram_CG* program = new GPUProgram_CG(vertexShader.get(), fragmentShader.get());
    vertexShader.release();
    fragmentShader.release();

    program_cache_cg[programKey] = program;
    return program;
  }

#endif

  //#############################################################################################
  //#    Creation Free Functions - Base
  //#############################################################################################

  GPUProgram* create_gpu_program(const string& fragmentPath, const vector<int>& fragmentAttributes,
                                 const string& vertexPath, const vector<int>& vertexAttributes) {
    // LOGGING
    static char  buffer1[256];
    static char buffer2[256];
    buffer1[0] = 0;
    if(vertexAttributes.size()) {
      sprintf(buffer1, "< ");
      for(size_t i=0; i<vertexAttributes.size(); i++)
        sprintf(buffer1, "%s%i ", buffer1, vertexAttributes[i]);
      sprintf(buffer1, "%s>", buffer1);
    }
    buffer2[0] = 0;
    if(fragmentAttributes.size()) {
      sprintf(buffer2, "< ");
      for(size_t i=0; i<fragmentAttributes.size(); i++)
        sprintf(buffer2, "%s%i ", buffer2, fragmentAttributes[i]);
      sprintf(buffer2, "%s>", buffer2);
    }

    static char buffer3[512];
    GPUProgram* program = NULL;
    sprintf(buffer3, "[create_gpu_program] FRAGMENT: %s%s, VERTEX: %s%s }    ", fragmentPath.c_str(), buffer2, vertexPath.c_str(), buffer1 );
    gpu_log(buffer3);
    // FIND PROGRAM

    gpu_log(get_string_for_shader_language_choice_enum(shaderLanguageChoice));
    gpu_log("  ");
#if defined(VW_HAVE_PKG_CG) && VW_HAVE_PKG_CG==1
    if(shaderLanguageChoice == SHADER_LANGUAGE_CHOICE_CG_GLSL || shaderLanguageChoice == SHADER_LANGUAGE_CHOICE_CG) {
      try {
        program = create_gpu_program_cg(fragmentPath  + ".cg", fragmentAttributes,
                                        vertexPath.empty() ? "" : vertexPath + ".cg", vertexAttributes);
      }
      catch(...) { program = NULL; }
      gpu_log("Trying CG... ");
    }
#endif

    if(!program && shaderLanguageChoice != SHADER_LANGUAGE_CHOICE_CG) {
      try {
        program = create_gpu_program_glsl(fragmentPath + ".glsl", fragmentAttributes,
                                          vertexPath.empty() ? "" : vertexPath + ".glsl", vertexAttributes);
      }
      catch(...) {  program = NULL; }
      gpu_log("Trying GLSL... ");
    }

#if defined(VW_HAVE_PKG_CG) && VW_HAVE_PKG_CG==1

    if(!program && shaderLanguageChoice == SHADER_LANGUAGE_CHOICE_GLSL_CG) {
      try {
        program = create_gpu_program_cg(fragmentPath  + ".cg", fragmentAttributes,
                                        vertexPath.empty() ? "" : vertexPath + ".cg", vertexAttributes);
      }
      catch(...) {  program = NULL; }

      gpu_log("Trying CG... ");
    }
#endif

    if(program) {
      if(get_shader_compilation_status() == SHADER_COMPILATION_STATUS_SUCCESS_FILE)
        gpu_log("SUCCESS (From File)\n");
      if(get_shader_compilation_status() == SHADER_COMPILATION_STATUS_SUCCESS_CACHE)
        gpu_log("SUCCESS (From Cache)\n");
    }
    else {
      if(get_shader_compilation_status() == SHADER_COMPILATION_STATUS_ERROR_FILE)
        gpu_log("*** FAILED (File Error) ***\n");
      if(get_shader_compilation_status() == SHADER_COMPILATION_STATUS_ERROR_COMPILE)
        gpu_log("*** FAILED (Compile Error) ***\n");
      if(get_shader_compilation_status() == SHADER_COMPILATION_STATUS_ERROR_LINK)
        gpu_log("*** FAILED (Link Error) ***\n");

      throw(Exception("GPUProgram creation failed."));
    }

    return program;
  }

  void clear_gpu_program_cache() {
    for(map<GPUProgramKey, GPUProgram_GLSL*>::iterator iter = program_cache_glsl.begin(); iter != program_cache_glsl.end(); iter++)
      delete (*iter).second;
    program_cache_glsl.clear();

#if defined(VW_HAVE_PKG_CG) && VW_HAVE_PKG_CG==1
    for(map<GPUProgramKey, GPUProgram_CG*>::iterator iter = program_cache_cg.begin(); iter != program_cache_cg.end(); iter++)
      delete (*iter).second;
    program_cache_cg.clear();
#endif

  }

} } // namespaces GPU, vw

max_stars_repo_name: tkeemon/visionworkbench

max_issues_repo_name: tkeemon/visionworkbench

max_forks_repo_name: tkeemon/visionworkbench


text:
/*
Copyright 2018 Glen Joseph Fernandes
(glenjofe@gmail.com)

Distributed under the Boost Software License, Version 1.0.
(http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_TYPEOF_CONSTANT_HPP
#define BOOST_TYPEOF_CONSTANT_HPP

#include <boost/config.hpp>

namespace boost {
namespace type_of {

template<class T, T N>
struct constant {
    typedef constant<T, N> type;
    typedef constant<T, N + 1> next;
    BOOST_STATIC_CONSTANT(T, value=N);
};

} /* type_of */
} /* boost */

#endif