<commit_before>// Copyright (c) 2014-2019 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/

#ifndef TAO_PEGTL_INTERNAL_DUSELTRONIK_HPP
#define TAO_PEGTL_INTERNAL_DUSELTRONIK_HPP

#include "../apply_mode.hpp"
#include "../config.hpp"
#include "../rewind_mode.hpp"

#include "dusel_mode.hpp"

namespace TAO_PEGTL_NAMESPACE::internal
{
   template< typename Rule,
             apply_mode A,
             rewind_mode M,
             template< typename... >
             class Action,
             template< typename... >
             class Control,
             dusel_mode = dusel_mode::nothing >
   struct duseltronik;

   template< typename Rule,
             apply_mode A,
             rewind_mode M,
             template< typename... >
             class Action,
             template< typename... >
             class Control >
   struct duseltronik< Rule, A, M, Action, Control, dusel_mode::nothing >
   {
      template< typename Input, typename... States >
      [[nodiscard]] static auto match( Input& in, States&&... st )
         -> decltype( Rule::template match< A, M, Action, Control >( in, st... ) )
      {
         return Rule::template match< A, M, Action, Control >( in, st... );
      }

      template< typename Input, typename... States, int = 1 >
      [[nodiscard]] static auto match( Input& in, States&&... /*unused*/ )
         -> decltype( Rule::match( in ) )
      {
         return Rule::match( in );
      }
   };

   template< typename Rule,
             apply_mode A,
             rewind_mode M,
             template< typename... >
             class Action,
             template< typename... >
             class Control >
   struct duseltronik< Rule, A, M, Action, Control, dusel_mode::control >
   {
      template< typename Input, typename... States >
      [[nodiscard]] static bool match( Input& in, States&&... st )
      {
         Control< Rule >::start( static_cast< const Input& >( in ), st... );

         if( duseltronik< Rule, A, M, Action, Control, dusel_mode::nothing >::match( in, st... ) ) {
            Control< Rule >::success( static_cast< const Input& >( in ), st... );
            return true;
         }
         Control< Rule >::failure( static_cast< const Input& >( in ), st... );
         return false;
      }
   };

   template< typename Rule,
             apply_mode A,
             rewind_mode M,
             template< typename... >
             class Action,
             template< typename... >
             class Control >
   struct duseltronik< Rule, A, M, Action, Control, dusel_mode::control_and_apply_void >
   {
      template< typename Input, typename... States >
      [[nodiscard]] static bool match( Input& in, States&&... st )
      {
         auto m = in.template mark< rewind_mode::required >();

         Control< Rule >::start( static_cast< const Input& >( in ), st... );

         if( duseltronik< Rule, A, rewind_mode::active, Action, Control, dusel_mode::nothing >::match( in, st... ) ) {
            Control< Rule >::template apply< Action >( m.iterator(), static_cast< const Input& >( in ), st... );
            Control< Rule >::success( static_cast< const Input& >( in ), st... );
            return m( true );
         }
         Control< Rule >::failure( static_cast< const Input& >( in ), st... );
         return false;
      }
   };

   template< typename Rule,
             apply_mode A,
             rewind_mode M,
             template< typename... >
             class Action,
             template< typename... >
             class Control >
   struct duseltronik< Rule, A, M, Action, Control, dusel_mode::control_and_apply_bool >
   {
      template< typename Input, typename... States >
      [[nodiscard]] static bool match( Input& in, States&&... st )
      {
         auto m = in.template mark< rewind_mode::required >();

         Control< Rule >::start( static_cast< const Input& >( in ), st... );

         if( duseltronik< Rule, A, rewind_mode::active, Action, Control, dusel_mode::nothing >::match( in, st... ) ) {
            if( Control< Rule >::template apply< Action >( m.iterator(), static_cast< const Input& >( in ), st... ) ) {
               Control< Rule >::success( static_cast< const Input& >( in ), st... );
               return m( true );
            }
         }
         Control< Rule >::failure( static_cast< const Input& >( in ), st... );
         return false;
      }
   };

   template< typename Rule,
             apply_mode A,
             rewind_mode M,
             template< typename... >
             class Action,
             template< typename... >
             class Control >
   struct duseltronik< Rule, A, M, Action, Control, dusel_mode::control_and_apply0_void >
   {
      template< typename Input, typename... States >
      [[nodiscard]] static bool match( Input& in, States&&... st )
      {
         Control< Rule >::start( static_cast< const Input& >( in ), st... );

         if( duseltronik< Rule, A, M, Action, Control, dusel_mode::nothing >::match( in, st... ) ) {
            Control< Rule >::template apply0< Action >( static_cast< const Input& >( in ), st... );
            Control< Rule >::success( static_cast< const Input& >( in ), st... );
            return true;
         }
         Control< Rule >::failure( static_cast< const Input& >( in ), st... );
         return false;
      }
   };

   template< typename Rule,
             apply_mode A,
             rewind_mode M,
             template< typename... >
             class Action,
             template< typename... >
             class Control >
   struct duseltronik< Rule, A, M, Action, Control, dusel_mode::control_and_apply0_bool >
   {
      template< typename Input, typename... States >
      [[nodiscard]] static bool match( Input& in, States&&... st )
      {
         auto m = in.template mark< rewind_mode::required >();

         Control< Rule >::start( static_cast< const Input& >( in ), st... );

         if( duseltronik< Rule, A, rewind_mode::active, Action, Control, dusel_mode::nothing >::match( in, st... ) ) {
            if( Control< Rule >::template apply0< Action >( static_cast< const Input& >( in ), st... ) ) {
               Control< Rule >::success( static_cast< const Input& >( in ), st... );
               return m( true );
            }
         }
         Control< Rule >::failure( static_cast< const Input& >( in ), st... );
         return false;
      }
   };

}  // namespace TAO_PEGTL_NAMESPACE::internal

#endif
<commit_msg>Silence some useless MSVC warnings<commit_after>// Copyright (c) 2014-2019 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/

#ifndef TAO_PEGTL_INTERNAL_DUSELTRONIK_HPP
#define TAO_PEGTL_INTERNAL_DUSELTRONIK_HPP

#include "../apply_mode.hpp"
#include "../config.hpp"
#include "../rewind_mode.hpp"

#include "dusel_mode.hpp"

#ifdef _MSC_VER
#pragma warning( push )
#pragma warning( disable : 4702 )
#endif

namespace TAO_PEGTL_NAMESPACE::internal
{
   template< typename Rule,
             apply_mode A,
             rewind_mode M,
             template< typename... >
             class Action,
             template< typename... >
             class Control,
             dusel_mode = dusel_mode::nothing >
   struct duseltronik;

   template< typename Rule,
             apply_mode A,
             rewind_mode M,
             template< typename... >
             class Action,
             template< typename... >
             class Control >
   struct duseltronik< Rule, A, M, Action, Control, dusel_mode::nothing >
   {
      template< typename Input, typename... States >
      [[nodiscard]] static auto match( Input& in, States&&... st )
         -> decltype( Rule::template match< A, M, Action, Control >( in, st... ) )
      {
         return Rule::template match< A, M, Action, Control >( in, st... );
      }

      template< typename Input, typename... States, int = 1 >
      [[nodiscard]] static auto match( Input& in, States&&... /*unused*/ )
         -> decltype( Rule::match( in ) )
      {
         return Rule::match( in );
      }
   };

   template< typename Rule,
             apply_mode A,
             rewind_mode M,
             template< typename... >
             class Action,
             template< typename... >
             class Control >
   struct duseltronik< Rule, A, M, Action, Control, dusel_mode::control >
   {
      template< typename Input, typename... States >
      [[nodiscard]] static bool match( Input& in, States&&... st )
      {
         Control< Rule >::start( static_cast< const Input& >( in ), st... );

         if( duseltronik< Rule, A, M, Action, Control, dusel_mode::nothing >::match( in, st... ) ) {
            Control< Rule >::success( static_cast< const Input& >( in ), st... );
            return true;
         }
         Control< Rule >::failure( static_cast< const Input& >( in ), st... );
         return false;
      }
   };

   template< typename Rule,
             apply_mode A,
             rewind_mode M,
             template< typename... >
             class Action,
             template< typename... >
             class Control >
   struct duseltronik< Rule, A, M, Action, Control, dusel_mode::control_and_apply_void >
   {
      template< typename Input, typename... States >
      [[nodiscard]] static bool match( Input& in, States&&... st )
      {
         auto m = in.template mark< rewind_mode::required >();

         Control< Rule >::start( static_cast< const Input& >( in ), st... );

         if( duseltronik< Rule, A, rewind_mode::active, Action, Control, dusel_mode::nothing >::match( in, st... ) ) {
            Control< Rule >::template apply< Action >( m.iterator(), static_cast< const Input& >( in ), st... );
            Control< Rule >::success( static_cast< const Input& >( in ), st... );
            return m( true );
         }
         Control< Rule >::failure( static_cast< const Input& >( in ), st... );
         return false;
      }
   };

   template< typename Rule,
             apply_mode A,
             rewind_mode M,
             template< typename... >
             class Action,
             template< typename... >
             class Control >
   struct duseltronik< Rule, A, M, Action, Control, dusel_mode::control_and_apply_bool >
   {
      template< typename Input, typename... States >
      [[nodiscard]] static bool match( Input& in, States&&... st )
      {
         auto m = in.template mark< rewind_mode::required >();

         Control< Rule >::start( static_cast< const Input& >( in ), st... );

         if( duseltronik< Rule, A, rewind_mode::active, Action, Control, dusel_mode::nothing >::match( in, st... ) ) {
            if( Control< Rule >::template apply< Action >( m.iterator(), static_cast< const Input& >( in ), st... ) ) {
               Control< Rule >::success( static_cast< const Input& >( in ), st... );
               return m( true );
            }
         }
         Control< Rule >::failure( static_cast< const Input& >( in ), st... );
         return false;
      }
   };

   template< typename Rule,
             apply_mode A,
             rewind_mode M,
             template< typename... >
             class Action,
             template< typename... >
             class Control >
   struct duseltronik< Rule, A, M, Action, Control, dusel_mode::control_and_apply0_void >
   {
      template< typename Input, typename... States >
      [[nodiscard]] static bool match( Input& in, States&&... st )
      {
         Control< Rule >::start( static_cast< const Input& >( in ), st... );

         if( duseltronik< Rule, A, M, Action, Control, dusel_mode::nothing >::match( in, st... ) ) {
            Control< Rule >::template apply0< Action >( static_cast< const Input& >( in ), st... );
            Control< Rule >::success( static_cast< const Input& >( in ), st... );
            return true;
         }
         Control< Rule >::failure( static_cast< const Input& >( in ), st... );
         return false;
      }
   };

   template< typename Rule,
             apply_mode A,
             rewind_mode M,
             template< typename... >
             class Action,
             template< typename... >
             class Control >
   struct duseltronik< Rule, A, M, Action, Control, dusel_mode::control_and_apply0_bool >
   {
      template< typename Input, typename... States >
      [[nodiscard]] static bool match( Input& in, States&&... st )
      {
         auto m = in.template mark< rewind_mode::required >();

         Control< Rule >::start( static_cast< const Input& >( in ), st... );

         if( duseltronik< Rule, A, rewind_mode::active, Action, Control, dusel_mode::nothing >::match( in, st... ) ) {
            if( Control< Rule >::template apply0< Action >( static_cast< const Input& >( in ), st... ) ) {
               Control< Rule >::success( static_cast< const Input& >( in ), st... );
               return m( true );
            }
         }
         Control< Rule >::failure( static_cast< const Input& >( in ), st... );
         return false;
      }
   };

}  // namespace TAO_PEGTL_NAMESPACE::internal

#ifdef _MSC_VER
#pragma warning( pop )
#endif

#endif
<|endoftext|>


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

#include <pcl/io/openni_camera/openni_device_oni.h>
#include <pcl/io/openni_camera/openni_image_rgb24.h>

using namespace std;
using namespace boost;

namespace openni_wrapper
{

DeviceONI::DeviceONI(xn::Context& context, const std::string& file_name, bool repeat, bool streaming)
  : OpenNIDevice(context)
  , streaming_ (streaming)
  , depth_stream_running_ (false)
  , image_stream_running_ (false)
  , ir_stream_running_ (false)
{
  XnStatus status;
  status = context_.OpenFileRecording(file_name.c_str());
  if (status != XN_STATUS_OK)
    THROW_OPENNI_EXCEPTION("Could not open ONI file. Reason: %s", xnGetStatusString(status));

  status = context.FindExistingNode(XN_NODE_TYPE_DEPTH, depth_generator_);
  if (status != XN_STATUS_OK)
    THROW_OPENNI_EXCEPTION("could not find depth stream in file %s. Reason: %s", file_name.c_str(), xnGetStatusString(status));
  else
  {
    available_depth_modes_.push_back(getDepthOutputMode());
    depth_generator_.RegisterToNewDataAvailable ((xn::StateChangedHandler)NewONIDepthDataAvailable, this, depth_callback_handle_);
  }

  status = context.FindExistingNode(XN_NODE_TYPE_IMAGE, image_generator_);
  if (status == XN_STATUS_OK)
  {
    available_image_modes_.push_back(getImageOutputMode());
    image_generator_.RegisterToNewDataAvailable ((xn::StateChangedHandler)NewONIImageDataAvailable, this, image_callback_handle_);
  }

  status = context.FindExistingNode(XN_NODE_TYPE_IR, ir_generator_);
  if (status == XN_STATUS_OK)
    ir_generator_.RegisterToNewDataAvailable ((xn::StateChangedHandler)NewONIIRDataAvailable, this, ir_callback_handle_);

  status = context.FindExistingNode(XN_NODE_TYPE_PLAYER, player_);
  if (status != XN_STATUS_OK)
    THROW_OPENNI_EXCEPTION("Failed to find player node: %s\n", xnGetStatusString(status));

  device_node_info_ = player_.GetInfo();

  Init ();

  player_.SetRepeat(repeat);
  if (streaming_)
    player_thread_ = boost::thread (&DeviceONI::PlayerThreadFunction, this);
}

DeviceONI::~DeviceONI() throw ()
{
  if (streaming_)
  {
    quit_ = true;
    player_thread_.join();
  }
}

void DeviceONI::startImageStream ()
{
  if (hasImageStream() && !image_stream_running_)
    image_stream_running_ = true;
}

void DeviceONI::stopImageStream ()
{
  if (hasImageStream() && image_stream_running_)
    image_stream_running_ = false;
}

void DeviceONI::startDepthStream ()
{
  if (hasDepthStream() && !depth_stream_running_)
    depth_stream_running_ = true;
}

void DeviceONI::stopDepthStream ()
{
  if (hasDepthStream() && depth_stream_running_)
    depth_stream_running_ = false;
}

void DeviceONI::startIRStream ()
{
  if (hasIRStream() && !ir_stream_running_)
    ir_stream_running_ = true;
}

void DeviceONI::stopIRStream ()
{
  if (hasIRStream() && ir_stream_running_)
    ir_stream_running_ = false;
}

bool DeviceONI::isImageStreamRunning () const throw ()
{
 return image_stream_running_;
}

bool DeviceONI::isDepthStreamRunning () const throw ()
{
  return depth_stream_running_;
}

bool DeviceONI::isIRStreamRunning () const throw ()
{
  return ir_stream_running_;
}

bool DeviceONI::trigger ()
{
  if (player_.IsEOF())
    return false;

  if (streaming_)
    THROW_OPENNI_EXCEPTION ("Virtual device is in streaming mode. Trigger not available.");

  player_.ReadNext();
  return true;
}

bool DeviceONI::isStreaming () const throw ()
{
  return streaming_;
}

void DeviceONI::PlayerThreadFunction()
{
  quit_ = false;
  while (!quit_)
    player_.ReadNext();
}

void __stdcall DeviceONI::NewONIDepthDataAvailable (xn::ProductionNode& node, void* cookie) throw ()
{
  DeviceONI* device = reinterpret_cast<DeviceONI*>(cookie);
  if (device->depth_stream_running_)
    device->depth_condition_.notify_all ();
}

void __stdcall DeviceONI::NewONIImageDataAvailable (xn::ProductionNode& node, void* cookie) throw ()
{
  DeviceONI* device = reinterpret_cast<DeviceONI*>(cookie);
  if (device->image_stream_running_)
    device->image_condition_.notify_all ();
}

void __stdcall DeviceONI::NewONIIRDataAvailable (xn::ProductionNode& node, void* cookie) throw ()
{
  DeviceONI* device = reinterpret_cast<DeviceONI*>(cookie);
  if (device->ir_stream_running_)
    device->ir_condition_.notify_all ();
}

boost::shared_ptr<Image> DeviceONI::getCurrentImage(boost::shared_ptr<xn::ImageMetaData> image_meta_data) const throw ()
{
  return boost::shared_ptr<Image > (new ImageRGB24(image_meta_data));
}

bool DeviceONI::isImageResizeSupported(unsigned input_width, unsigned input_height, unsigned output_width, unsigned output_height) const throw ()
{
  return ImageRGB24::resizingSupported (input_width, input_height, output_width, output_height);
}

}

#endif //HAVE_OPENNI

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

#include <pcl/io/openni_camera/openni_device_oni.h>
#include <pcl/io/openni_camera/openni_image_rgb24.h>

using namespace std;
using namespace boost;

namespace openni_wrapper
{

DeviceONI::DeviceONI(xn::Context& context, const std::string& file_name, bool repeat, bool streaming)
  : OpenNIDevice(context)
  , streaming_ (streaming)
  , depth_stream_running_ (false)
  , image_stream_running_ (false)
  , ir_stream_running_ (false)
{
  XnStatus status;
#if (XN_MINOR_VERSION >= 3)
  status = context_.OpenFileRecording(file_name.c_str(), player_);
  if (status != XN_STATUS_OK)
    THROW_OPENNI_EXCEPTION("Could not open ONI file. Reason: %s", xnGetStatusString(status));
#else
  status = context_.OpenFileRecording(file_name.c_str());
  if (status != XN_STATUS_OK)
    THROW_OPENNI_EXCEPTION("Could not open ONI file. Reason: %s", xnGetStatusString(status));

  status = context.FindExistingNode(XN_NODE_TYPE_PLAYER, player_);
  if (status != XN_STATUS_OK)
    THROW_OPENNI_EXCEPTION("Failed to find player node: %s\n", xnGetStatusString(status));
#endif

  status = context.FindExistingNode(XN_NODE_TYPE_DEPTH, depth_generator_);
  if (status != XN_STATUS_OK)
    THROW_OPENNI_EXCEPTION("could not find depth stream in file %s. Reason: %s", file_name.c_str(), xnGetStatusString(status));
  else
  {
    available_depth_modes_.push_back(getDepthOutputMode());
    depth_generator_.RegisterToNewDataAvailable ((xn::StateChangedHandler)NewONIDepthDataAvailable, this, depth_callback_handle_);
  }

  status = context.FindExistingNode(XN_NODE_TYPE_IMAGE, image_generator_);
  if (status == XN_STATUS_OK)
  {
    available_image_modes_.push_back(getImageOutputMode());
    image_generator_.RegisterToNewDataAvailable ((xn::StateChangedHandler)NewONIImageDataAvailable, this, image_callback_handle_);
  }

  status = context.FindExistingNode(XN_NODE_TYPE_IR, ir_generator_);
  if (status == XN_STATUS_OK)
    ir_generator_.RegisterToNewDataAvailable ((xn::StateChangedHandler)NewONIIRDataAvailable, this, ir_callback_handle_);

  device_node_info_ = player_.GetInfo();

  Init ();

  player_.SetRepeat(repeat);
  if (streaming_)
    player_thread_ = boost::thread (&DeviceONI::PlayerThreadFunction, this);
}

DeviceONI::~DeviceONI() throw ()
{
  if (streaming_)
  {
    quit_ = true;
    player_thread_.join();
  }
}

void DeviceONI::startImageStream ()
{
  if (hasImageStream() && !image_stream_running_)
    image_stream_running_ = true;
}

void DeviceONI::stopImageStream ()
{
  if (hasImageStream() && image_stream_running_)
    image_stream_running_ = false;
}

void DeviceONI::startDepthStream ()
{
  if (hasDepthStream() && !depth_stream_running_)
    depth_stream_running_ = true;
}

void DeviceONI::stopDepthStream ()
{
  if (hasDepthStream() && depth_stream_running_)
    depth_stream_running_ = false;
}

void DeviceONI::startIRStream ()
{
  if (hasIRStream() && !ir_stream_running_)
    ir_stream_running_ = true;
}

void DeviceONI::stopIRStream ()
{
  if (hasIRStream() && ir_stream_running_)
    ir_stream_running_ = false;
}

bool DeviceONI::isImageStreamRunning () const throw ()
{
 return image_stream_running_;
}

bool DeviceONI::isDepthStreamRunning () const throw ()
{
  return depth_stream_running_;
}

bool DeviceONI::isIRStreamRunning () const throw ()
{
  return ir_stream_running_;
}

bool DeviceONI::trigger ()
{
  if (player_.IsEOF())
    return false;

  if (streaming_)
    THROW_OPENNI_EXCEPTION ("Virtual device is in streaming mode. Trigger not available.");

  player_.ReadNext();
  return true;
}

bool DeviceONI::isStreaming () const throw ()
{
  return streaming_;
}

void DeviceONI::PlayerThreadFunction()
{
  quit_ = false;
  while (!quit_)
    player_.ReadNext();
}

void __stdcall DeviceONI::NewONIDepthDataAvailable (xn::ProductionNode& node, void* cookie) throw ()
{
  DeviceONI* device = reinterpret_cast<DeviceONI*>(cookie);
  if (device->depth_stream_running_)
    device->depth_condition_.notify_all ();
}

void __stdcall DeviceONI::NewONIImageDataAvailable (xn::ProductionNode& node, void* cookie) throw ()
{
  DeviceONI* device = reinterpret_cast<DeviceONI*>(cookie);
  if (device->image_stream_running_)
    device->image_condition_.notify_all ();
}

void __stdcall DeviceONI::NewONIIRDataAvailable (xn::ProductionNode& node, void* cookie) throw ()
{
  DeviceONI* device = reinterpret_cast<DeviceONI*>(cookie);
  if (device->ir_stream_running_)
    device->ir_condition_.notify_all ();
}

boost::shared_ptr<Image> DeviceONI::getCurrentImage(boost::shared_ptr<xn::ImageMetaData> image_meta_data) const throw ()
{
  return boost::shared_ptr<Image > (new ImageRGB24(image_meta_data));
}

bool DeviceONI::isImageResizeSupported(unsigned input_width, unsigned input_height, unsigned output_width, unsigned output_height) const throw ()
{
  return ImageRGB24::resizingSupported (input_width, input_height, output_width, output_height);
}

}

#endif //HAVE_OPENNI

<|endoftext|>


<commit_before>/*
** Copyright 2013-2015 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker 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
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/

#include <algorithm>
#include <memory>
#include <QStringList>
#include <sstream>
#include "com/centreon/broker/bbdo/acceptor.hh"
#include "com/centreon/broker/bbdo/internal.hh"
#include "com/centreon/broker/bbdo/stream.hh"
#include "com/centreon/broker/bbdo/version_response.hh"
#include "com/centreon/broker/exceptions/msg.hh"
#include "com/centreon/broker/io/events.hh"
#include "com/centreon/broker/io/protocols.hh"
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/multiplexing/publisher.hh"
#include "com/centreon/broker/multiplexing/subscriber.hh"
#include "com/centreon/broker/processing/feeder.hh"

using namespace com::centreon::broker;
using namespace com::centreon::broker::bbdo;

/**************************************
*                                     *
*           Public Methods            *
*                                     *
**************************************/

/**
 *  Constructor.
 *
 *  @param[in] name                    The name to build temporary.
 *  @param[in] is_out                  true if the acceptor is an output
 *                                     acceptor.
 *  @param[in] negociate               true if feature negociation is
 *                                     allowed.
 *  @param[in] extensions              Available extensions.
 *  @param[in] timeout                 Connection timeout.
 *  @param[in] one_peer_retention_mode True to enable the "one peer
 *                                     retention mode" (TM).
 *  @param[in] coarse                  If the acceptor is coarse or not.
 */
acceptor::acceptor(
            QString const& name,
            bool is_out,
            bool negociate,
            QString const& extensions,
            time_t timeout,
            bool one_peer_retention_mode,
            bool coarse)
  : io::endpoint(!one_peer_retention_mode),
    _coarse(coarse),
    _extensions(extensions),
    _is_out(is_out),
    _name(name),
    _negociate(negociate),
    _one_peer_retention_mode(one_peer_retention_mode),
    _timeout(timeout) {
  if ((_timeout == (time_t)-1) || (_timeout == 0))
    _timeout = 3;
}

/**
 *  Copy constructor.
 *
 *  @param[in] right Object to copy.
 */
acceptor::acceptor(acceptor const& right)
  : QObject(),
    io::endpoint(right),
    _coarse(right._coarse),
    _extensions(right._extensions),
    _is_out(right._is_out),
    _name(right._name),
    _negociate(right._negociate),
    _one_peer_retention_mode(right._one_peer_retention_mode),
    _timeout(right._timeout) {}

/**
 *  Destructor.
 */
acceptor::~acceptor() {
  _from.clear();
  for (QList<QThread*>::iterator
         it(_clients.begin()),
         end(_clients.end());
       it != end;
       ++it) {
    (*it)->wait();
    delete *it;
  }
  for (QList<QThread*>::iterator
         it(_threads.begin()),
         end(_threads.end());
       it != end;
       ++it)
    (*it)->wait();
}

/**
 *  Assignment operator.
 *
 *  @param[in] right Object to copy.
 *
 *  @return This object.
 */
acceptor& acceptor::operator=(acceptor const& right) {
  if (this != &right) {
    io::endpoint::operator=(right);
    _coarse = right._coarse;
    _extensions = right._extensions;
    _is_out = right._is_out;
    _name = right._name;
    _negociate = right._negociate;
    _one_peer_retention_mode = right._one_peer_retention_mode;
    _timeout = right._timeout;
  }
  return (*this);
}

/**
 *  Clone the acceptor.
 *
 *  @return This object.
 */
io::endpoint* acceptor::clone() const {
  std::auto_ptr<acceptor> copy(new acceptor(*this));
  if (_from.isNull())
    copy->_from = _from->clone();
  return (copy.release());
}

/**
 *  Close the acceptor.
 */
void acceptor::close() {
  if (!_from.isNull())
    _from->close();
  return ;
}

/**
 *  Wait for incoming connection.
 *
 *  @return Always return null stream. A new thread will be launched to
 *          process the incoming connection.
 */
misc::shared_ptr<io::stream> acceptor::open() {
  // Clean client threads.
  for (QList<QThread*>::iterator
         it(_clients.begin()),
         end(_clients.end());
       it != end;) {
    if ((*it)->wait(0)) {
      QList<QThread*>::iterator to_delete(it);
      ++it;
      delete *to_delete;
      _clients.erase(to_delete);
    }
    else
      ++it;
  }

  // Wait for client from the lower layer.
  if (!_from.isNull()) {
    if (_one_peer_retention_mode) {
      misc::shared_ptr<io::stream> s(_from->open());
      if (!s.isNull()) {
        misc::shared_ptr<bbdo::stream>
          my_bbdo(_is_out
                  ? new bbdo::stream(false, true)
                  : new bbdo::stream(true, false));
        my_bbdo->read_from(s);
        my_bbdo->write_to(s);
        _negociate_features(s, my_bbdo);
        return (my_bbdo);
      }
    }
    else {
      misc::shared_ptr<io::stream> s(_open(_from->open()));
      if (!s.isNull()) {
        _clients.push_back(new helper(this, s));
        _clients.last()->start();
      }
    }
  }

  return (misc::shared_ptr<io::stream>());
}

/**
 *  Wait for incoming connection.
 *
 *  @return Always return null stream. A new thread will be launched to
 *          process the incoming connection.
 */
misc::shared_ptr<io::stream> acceptor::open(QString const& id) {
  // Clean client threads.
  for (QList<QThread*>::iterator
         it(_clients.begin()),
         end(_clients.end());
       it != end;) {
    if ((*it)->wait(0)) {
      QList<QThread*>::iterator to_delete(it);
      ++it;
      delete *to_delete;
      _clients.erase(to_delete);
    }
    else
      ++it;
  }

  // Wait for client from the lower layer.
  if (!_from.isNull()) {
    if (_one_peer_retention_mode) {
      misc::shared_ptr<io::stream> s(_from->open(id));
      if (!s.isNull()) {
        misc::shared_ptr<bbdo::stream>
          my_bbdo(_is_out
                  ? new bbdo::stream(false, true)
                  : new bbdo::stream(true, false));
        my_bbdo->read_from(s);
        my_bbdo->write_to(s);
        _negociate_features(s, my_bbdo);
        return (my_bbdo);
      }
    }
    else {
      misc::shared_ptr<io::stream> s(_open(_from->open(id)));
      if (!s.isNull()) {
        _clients.push_back(new helper(this, s));
        _clients.last()->start();
      }
    }
  }

  return (misc::shared_ptr<io::stream>());
}

/**
 *  Get BBDO statistics.
 *
 *  @param[out] tree Properties tree.
 */
void acceptor::stats(io::properties& tree) {
  io::property& p(tree["one_peer_retention_mode"]);
  p.set_perfdata(_one_peer_retention_mode
                 ? "one peer retention mode=true"
                 : "one peer retention mode=false");
  p.set_graphable(false);
  if (!_from.isNull())
    _from->stats(tree);
  return ;
}

/**************************************
*                                     *
*           Private Methods           *
*                                     *
**************************************/

/**
 *  Negociate stream features.
 *
 *  @param[in]     stream   Base stream (no BBDO).
 *  @param[in,out] my_bbdo  BBDO stream being processed.
 *
 *  @return Instance ID of the negociated stream.
 */
unsigned int acceptor::_negociate_features(
                         misc::shared_ptr<io::stream> stream,
                         misc::shared_ptr<bbdo::stream> my_bbdo) {
  // Coarse peer don't expect any salutation either.
  if (_coarse)
    return (0);

  // Read initial packet.
  misc::shared_ptr<io::data> d;
  my_bbdo->read_any(d, time(NULL) + _timeout);
  if (d.isNull() || (d->type() != version_response::static_type()))
    throw (exceptions::msg()
           << "BBDO: invalid protocol header, aborting connection");

  // Handle protocol version.
  misc::shared_ptr<version_response>
    v(d.staticCast<version_response>());
  if (v->bbdo_major != BBDO_VERSION_MAJOR)
    throw (exceptions::msg()
           << "BBDO: peer is using protocol version " << v->bbdo_major
           << "." << v->bbdo_minor << "." << v->bbdo_patch
           << " whereas we're using protocol version "
           << BBDO_VERSION_MAJOR << "." << BBDO_VERSION_MINOR << "."
           << BBDO_VERSION_PATCH);
  logging::info(logging::medium)
    << "BBDO: peer is using protocol version " << v->bbdo_major
    << "." << v->bbdo_minor << "." << v->bbdo_patch
    << ", we're using version " << BBDO_VERSION_MAJOR << "."
    << BBDO_VERSION_MINOR << "." << BBDO_VERSION_PATCH;

  // Send self version packet.
  misc::shared_ptr<version_response>
    welcome_packet(new version_response);
  if (_negociate)
    welcome_packet->extensions = _extensions;
  my_bbdo->output::write(welcome_packet);
  my_bbdo->output::write(misc::shared_ptr<io::data>());

  // Negociation.
  if (_negociate) {
    // Apply negociated extensions.
    logging::info(logging::medium)
      << "BBDO: we have extensions '"
      << _extensions << "' and peer has '" << v->extensions << "'";
    QStringList own_ext(_extensions.split(' '));
    QStringList peer_ext(v->extensions.split(' '));
    for (QStringList::const_iterator
           it(own_ext.begin()),
           end(own_ext.end());
         it != end;
         ++it) {
      // Find matching extension in peer extension list.
      QStringList::const_iterator
        peer_it(std::find(peer_ext.begin(), peer_ext.end(), *it));
      // Apply extension if found.
      if (peer_it != peer_ext.end()) {
        logging::info(logging::medium)
          << "BBDO: applying extension '" << *it << "'";
        for (QMap<QString, io::protocols::protocol>::const_iterator
               proto_it(io::protocols::instance().begin()),
               proto_end(io::protocols::instance().end());
             proto_it != proto_end;
             ++proto_it)
          if (proto_it.key() == *it) {
            misc::shared_ptr<io::stream>
              s(proto_it->endpntfactry->new_stream(
                                          stream,
                                          true,
                                          *it));
              my_bbdo->read_from(s);
              my_bbdo->write_to(s);
              break ;
          }
      }
    }
  }
  return (d->source_id);
}

/**
 *  Called when a thread terminates.
 */
void acceptor::_on_thread_termination() {
  QThread* th(static_cast<QThread*>(QObject::sender()));
  QMutexLocker lock(&_threadsm);
  _threads.removeAll(th);
  return ;
}

/**
 *  Wait for incoming connection.
 *
 *  @param[in] stream  Lower-layer stream.
 *
 *  @return Always return null stream. A new thread will be launched to
 *          process the incoming connection.
 */
misc::shared_ptr<io::stream> acceptor::_open(
                                          misc::shared_ptr<io::stream> stream) {
  if (!stream.isNull()) {
    // In and out objects.
    misc::shared_ptr<io::stream> in;
    misc::shared_ptr<io::stream> out;

    // Create input and output objects.
    misc::shared_ptr<bbdo::stream> my_bbdo;
    if (!_is_out) {
      my_bbdo = misc::shared_ptr<bbdo::stream>(
                        new bbdo::stream(true, false));
      in = my_bbdo;
      in->read_from(stream);
      in->write_to(stream);
      out = misc::shared_ptr<io::stream>(new multiplexing::publisher);
    }
    else {
      misc::shared_ptr<multiplexing::subscriber> sbcr(
        new multiplexing::subscriber(_name));
      sbcr->set_filters(_filter);
      logging::error(logging::high)
        << "TEST: setting multiplexing filter for " <<_filter.size();
      in = sbcr;
      my_bbdo = misc::shared_ptr<bbdo::stream>(
                        new bbdo::stream(false, true));
      out = my_bbdo;
      out->read_from(stream);
      out->write_to(stream);
    }

    // Negociate features.
    unsigned int instance_id;
    try {
      instance_id = _negociate_features(stream, my_bbdo);
    }
    catch (exceptions::msg const& e) {
      logging::info(logging::high) << e.what();
      return (misc::shared_ptr<io::stream>());
    }

    // Feeder thread.
    std::auto_ptr<processing::feeder> feedr(new processing::feeder);
    std::ostringstream oss;
    oss << "instance #" << instance_id;
    feedr->prepare(oss.str(), in, out);
    QObject::connect(
               feedr.get(),
               SIGNAL(finished()),
               this,
               SLOT(_on_thread_termination()));
    {
      QMutexLocker lock(&_threadsm);
      _threads.push_back(feedr.get());
    }
    QObject::connect(
               feedr.get(),
               SIGNAL(finished()),
               feedr.get(),
               SLOT(deleteLater()));
    feedr.release()->start();
  }

  return (misc::shared_ptr<io::stream>());
}

/**************************************
*                                     *
*           Helper Methods            *
*                                     *
**************************************/

/**
 *  Constructor.
 *
 *  @param[in] accptr Acceptor object.
 *  @param[in] s      Stream object.
 */
acceptor::helper::helper(
                    acceptor* accptr,
                    misc::shared_ptr<io::stream> s)
  : _acceptor(accptr), _stream(s) {}

/**
 *  Thread entry point.
 */
void acceptor::helper::run() {
  try {
    _acceptor->_open(_stream);
  }
  catch (std::exception const& e) {
    logging::error(logging::high)
      << "BBDO: client handshake failed: " << e.what();
  }
  catch (...) {
    logging::error(logging::high)
      << "BBDO: client handshake failed: unknown error";
  }
  return ;
}
<commit_msg>Core: remove test printing.<commit_after>/*
** Copyright 2013-2015 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker 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
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/

#include <algorithm>
#include <memory>
#include <QStringList>
#include <sstream>
#include "com/centreon/broker/bbdo/acceptor.hh"
#include "com/centreon/broker/bbdo/internal.hh"
#include "com/centreon/broker/bbdo/stream.hh"
#include "com/centreon/broker/bbdo/version_response.hh"
#include "com/centreon/broker/exceptions/msg.hh"
#include "com/centreon/broker/io/events.hh"
#include "com/centreon/broker/io/protocols.hh"
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/multiplexing/publisher.hh"
#include "com/centreon/broker/multiplexing/subscriber.hh"
#include "com/centreon/broker/processing/feeder.hh"

using namespace com::centreon::broker;
using namespace com::centreon::broker::bbdo;

/**************************************
*                                     *
*           Public Methods            *
*                                     *
**************************************/

/**
 *  Constructor.
 *
 *  @param[in] name                    The name to build temporary.
 *  @param[in] is_out                  true if the acceptor is an output
 *                                     acceptor.
 *  @param[in] negociate               true if feature negociation is
 *                                     allowed.
 *  @param[in] extensions              Available extensions.
 *  @param[in] timeout                 Connection timeout.
 *  @param[in] one_peer_retention_mode True to enable the "one peer
 *                                     retention mode" (TM).
 *  @param[in] coarse                  If the acceptor is coarse or not.
 */
acceptor::acceptor(
            QString const& name,
            bool is_out,
            bool negociate,
            QString const& extensions,
            time_t timeout,
            bool one_peer_retention_mode,
            bool coarse)
  : io::endpoint(!one_peer_retention_mode),
    _coarse(coarse),
    _extensions(extensions),
    _is_out(is_out),
    _name(name),
    _negociate(negociate),
    _one_peer_retention_mode(one_peer_retention_mode),
    _timeout(timeout) {
  if ((_timeout == (time_t)-1) || (_timeout == 0))
    _timeout = 3;
}

/**
 *  Copy constructor.
 *
 *  @param[in] right Object to copy.
 */
acceptor::acceptor(acceptor const& right)
  : QObject(),
    io::endpoint(right),
    _coarse(right._coarse),
    _extensions(right._extensions),
    _is_out(right._is_out),
    _name(right._name),
    _negociate(right._negociate),
    _one_peer_retention_mode(right._one_peer_retention_mode),
    _timeout(right._timeout) {}

/**
 *  Destructor.
 */
acceptor::~acceptor() {
  _from.clear();
  for (QList<QThread*>::iterator
         it(_clients.begin()),
         end(_clients.end());
       it != end;
       ++it) {
    (*it)->wait();
    delete *it;
  }
  for (QList<QThread*>::iterator
         it(_threads.begin()),
         end(_threads.end());
       it != end;
       ++it)
    (*it)->wait();
}

/**
 *  Assignment operator.
 *
 *  @param[in] right Object to copy.
 *
 *  @return This object.
 */
acceptor& acceptor::operator=(acceptor const& right) {
  if (this != &right) {
    io::endpoint::operator=(right);
    _coarse = right._coarse;
    _extensions = right._extensions;
    _is_out = right._is_out;
    _name = right._name;
    _negociate = right._negociate;
    _one_peer_retention_mode = right._one_peer_retention_mode;
    _timeout = right._timeout;
  }
  return (*this);
}

/**
 *  Clone the acceptor.
 *
 *  @return This object.
 */
io::endpoint* acceptor::clone() const {
  std::auto_ptr<acceptor> copy(new acceptor(*this));
  if (_from.isNull())
    copy->_from = _from->clone();
  return (copy.release());
}

/**
 *  Close the acceptor.
 */
void acceptor::close() {
  if (!_from.isNull())
    _from->close();
  return ;
}

/**
 *  Wait for incoming connection.
 *
 *  @return Always return null stream. A new thread will be launched to
 *          process the incoming connection.
 */
misc::shared_ptr<io::stream> acceptor::open() {
  // Clean client threads.
  for (QList<QThread*>::iterator
         it(_clients.begin()),
         end(_clients.end());
       it != end;) {
    if ((*it)->wait(0)) {
      QList<QThread*>::iterator to_delete(it);
      ++it;
      delete *to_delete;
      _clients.erase(to_delete);
    }
    else
      ++it;
  }

  // Wait for client from the lower layer.
  if (!_from.isNull()) {
    if (_one_peer_retention_mode) {
      misc::shared_ptr<io::stream> s(_from->open());
      if (!s.isNull()) {
        misc::shared_ptr<bbdo::stream>
          my_bbdo(_is_out
                  ? new bbdo::stream(false, true)
                  : new bbdo::stream(true, false));
        my_bbdo->read_from(s);
        my_bbdo->write_to(s);
        _negociate_features(s, my_bbdo);
        return (my_bbdo);
      }
    }
    else {
      misc::shared_ptr<io::stream> s(_open(_from->open()));
      if (!s.isNull()) {
        _clients.push_back(new helper(this, s));
        _clients.last()->start();
      }
    }
  }

  return (misc::shared_ptr<io::stream>());
}

/**
 *  Wait for incoming connection.
 *
 *  @return Always return null stream. A new thread will be launched to
 *          process the incoming connection.
 */
misc::shared_ptr<io::stream> acceptor::open(QString const& id) {
  // Clean client threads.
  for (QList<QThread*>::iterator
         it(_clients.begin()),
         end(_clients.end());
       it != end;) {
    if ((*it)->wait(0)) {
      QList<QThread*>::iterator to_delete(it);
      ++it;
      delete *to_delete;
      _clients.erase(to_delete);
    }
    else
      ++it;
  }

  // Wait for client from the lower layer.
  if (!_from.isNull()) {
    if (_one_peer_retention_mode) {
      misc::shared_ptr<io::stream> s(_from->open(id));
      if (!s.isNull()) {
        misc::shared_ptr<bbdo::stream>
          my_bbdo(_is_out
                  ? new bbdo::stream(false, true)
                  : new bbdo::stream(true, false));
        my_bbdo->read_from(s);
        my_bbdo->write_to(s);
        _negociate_features(s, my_bbdo);
        return (my_bbdo);
      }
    }
    else {
      misc::shared_ptr<io::stream> s(_open(_from->open(id)));
      if (!s.isNull()) {
        _clients.push_back(new helper(this, s));
        _clients.last()->start();
      }
    }
  }

  return (misc::shared_ptr<io::stream>());
}

/**
 *  Get BBDO statistics.
 *
 *  @param[out] tree Properties tree.
 */
void acceptor::stats(io::properties& tree) {
  io::property& p(tree["one_peer_retention_mode"]);
  p.set_perfdata(_one_peer_retention_mode
                 ? "one peer retention mode=true"
                 : "one peer retention mode=false");
  p.set_graphable(false);
  if (!_from.isNull())
    _from->stats(tree);
  return ;
}

/**************************************
*                                     *
*           Private Methods           *
*                                     *
**************************************/

/**
 *  Negociate stream features.
 *
 *  @param[in]     stream   Base stream (no BBDO).
 *  @param[in,out] my_bbdo  BBDO stream being processed.
 *
 *  @return Instance ID of the negociated stream.
 */
unsigned int acceptor::_negociate_features(
                         misc::shared_ptr<io::stream> stream,
                         misc::shared_ptr<bbdo::stream> my_bbdo) {
  // Coarse peer don't expect any salutation either.
  if (_coarse)
    return (0);

  // Read initial packet.
  misc::shared_ptr<io::data> d;
  my_bbdo->read_any(d, time(NULL) + _timeout);
  if (d.isNull() || (d->type() != version_response::static_type()))
    throw (exceptions::msg()
           << "BBDO: invalid protocol header, aborting connection");

  // Handle protocol version.
  misc::shared_ptr<version_response>
    v(d.staticCast<version_response>());
  if (v->bbdo_major != BBDO_VERSION_MAJOR)
    throw (exceptions::msg()
           << "BBDO: peer is using protocol version " << v->bbdo_major
           << "." << v->bbdo_minor << "." << v->bbdo_patch
           << " whereas we're using protocol version "
           << BBDO_VERSION_MAJOR << "." << BBDO_VERSION_MINOR << "."
           << BBDO_VERSION_PATCH);
  logging::info(logging::medium)
    << "BBDO: peer is using protocol version " << v->bbdo_major
    << "." << v->bbdo_minor << "." << v->bbdo_patch
    << ", we're using version " << BBDO_VERSION_MAJOR << "."
    << BBDO_VERSION_MINOR << "." << BBDO_VERSION_PATCH;

  // Send self version packet.
  misc::shared_ptr<version_response>
    welcome_packet(new version_response);
  if (_negociate)
    welcome_packet->extensions = _extensions;
  my_bbdo->output::write(welcome_packet);
  my_bbdo->output::write(misc::shared_ptr<io::data>());

  // Negociation.
  if (_negociate) {
    // Apply negociated extensions.
    logging::info(logging::medium)
      << "BBDO: we have extensions '"
      << _extensions << "' and peer has '" << v->extensions << "'";
    QStringList own_ext(_extensions.split(' '));
    QStringList peer_ext(v->extensions.split(' '));
    for (QStringList::const_iterator
           it(own_ext.begin()),
           end(own_ext.end());
         it != end;
         ++it) {
      // Find matching extension in peer extension list.
      QStringList::const_iterator
        peer_it(std::find(peer_ext.begin(), peer_ext.end(), *it));
      // Apply extension if found.
      if (peer_it != peer_ext.end()) {
        logging::info(logging::medium)
          << "BBDO: applying extension '" << *it << "'";
        for (QMap<QString, io::protocols::protocol>::const_iterator
               proto_it(io::protocols::instance().begin()),
               proto_end(io::protocols::instance().end());
             proto_it != proto_end;
             ++proto_it)
          if (proto_it.key() == *it) {
            misc::shared_ptr<io::stream>
              s(proto_it->endpntfactry->new_stream(
                                          stream,
                                          true,
                                          *it));
              my_bbdo->read_from(s);
              my_bbdo->write_to(s);
              break ;
          }
      }
    }
  }
  return (d->source_id);
}

/**
 *  Called when a thread terminates.
 */
void acceptor::_on_thread_termination() {
  QThread* th(static_cast<QThread*>(QObject::sender()));
  QMutexLocker lock(&_threadsm);
  _threads.removeAll(th);
  return ;
}

/**
 *  Wait for incoming connection.
 *
 *  @param[in] stream  Lower-layer stream.
 *
 *  @return Always return null stream. A new thread will be launched to
 *          process the incoming connection.
 */
misc::shared_ptr<io::stream> acceptor::_open(
                                          misc::shared_ptr<io::stream> stream) {
  if (!stream.isNull()) {
    // In and out objects.
    misc::shared_ptr<io::stream> in;
    misc::shared_ptr<io::stream> out;

    // Create input and output objects.
    misc::shared_ptr<bbdo::stream> my_bbdo;
    if (!_is_out) {
      my_bbdo = misc::shared_ptr<bbdo::stream>(
                        new bbdo::stream(true, false));
      in = my_bbdo;
      in->read_from(stream);
      in->write_to(stream);
      out = misc::shared_ptr<io::stream>(new multiplexing::publisher);
    }
    else {
      misc::shared_ptr<multiplexing::subscriber> sbcr(
        new multiplexing::subscriber(_name));
      sbcr->set_filters(_filter);
      in = sbcr;
      my_bbdo = misc::shared_ptr<bbdo::stream>(
                        new bbdo::stream(false, true));
      out = my_bbdo;
      out->read_from(stream);
      out->write_to(stream);
    }

    // Negociate features.
    unsigned int instance_id;
    try {
      instance_id = _negociate_features(stream, my_bbdo);
    }
    catch (exceptions::msg const& e) {
      logging::info(logging::high) << e.what();
      return (misc::shared_ptr<io::stream>());
    }

    // Feeder thread.
    std::auto_ptr<processing::feeder> feedr(new processing::feeder);
    std::ostringstream oss;
    oss << "instance #" << instance_id;
    feedr->prepare(oss.str(), in, out);
    QObject::connect(
               feedr.get(),
               SIGNAL(finished()),
               this,
               SLOT(_on_thread_termination()));
    {
      QMutexLocker lock(&_threadsm);
      _threads.push_back(feedr.get());
    }
    QObject::connect(
               feedr.get(),
               SIGNAL(finished()),
               feedr.get(),
               SLOT(deleteLater()));
    feedr.release()->start();
  }

  return (misc::shared_ptr<io::stream>());
}

/**************************************
*                                     *
*           Helper Methods            *
*                                     *
**************************************/

/**
 *  Constructor.
 *
 *  @param[in] accptr Acceptor object.
 *  @param[in] s      Stream object.
 */
acceptor::helper::helper(
                    acceptor* accptr,
                    misc::shared_ptr<io::stream> s)
  : _acceptor(accptr), _stream(s) {}

/**
 *  Thread entry point.
 */
void acceptor::helper::run() {
  try {
    _acceptor->_open(_stream);
  }
  catch (std::exception const& e) {
    logging::error(logging::high)
      << "BBDO: client handshake failed: " << e.what();
  }
  catch (...) {
    logging::error(logging::high)
      << "BBDO: client handshake failed: unknown error";
  }
  return ;
}
<|endoftext|>


<commit_before>#include "graphe.h"

#include <set>
#include <chrono>
#include <ctime>

graphe::graphe(string cheminVersFichier)
{
	DATA.open(cheminVersFichier.c_str(), ios::in|ios::binary);
	if(!DATA.is_open()) {
		cout << "Erreur d'ouverture du fichier, celui-ci n'existe pas." << endl;
		exit(1);
	} else {
		DATA >> nom;
		DATA.ignore(1);
		DATA >> nbNOEUDS;
		DATA.ignore(1);
		DATA >> architecture;
		DATA.ignore(1);

		DEBUT = DATA.tellg();

// Afficher une description du graphe si on est en debug
#ifdef _DEBUG
		cout << "Description du graphe : " << endl;
		cout << "Nom: " << nom <<endl;
		cout << "NbNoeuds: " << nbNOEUDS << endl;
		cout << "Architecture fichier: ";

		if(architecture == 0) {
			cout << "BigEndian";
		} else if (architecture == 1) {
			cout << "LittleEndian";
		}

		cout << endl << "Architecture machine: ";
		if(this->architectureMachine() == __LITTLE_ENDIAN) {
			cout << "LittleEndian";
		} else {
			cout << "BigEndian";
		}

		cout << endl;
		cout << "----------------------------------------" << endl;
#endif

	}
}

graphe::~graphe()
{
	// Fermer le fichier a la sortie du programme.
	if (DATA.is_open()) {
		DATA.close();
	}
}

void graphe::lire_noeud(uint32_t noeud)
{
	if(noeud < nbNOEUDS) {
		// Si le noeud n'a jamais été lu, alors il va l'être !
		if(lesNoeuds[noeud].partieVariable == 0) {

			// Lecture des données statiques du noeud
			DATA.seekg(DEBUT + (28 * noeud), ios::beg);
			this->lire(lesNoeuds[noeud].partieVariable);
			this->lire(lesNoeuds[noeud].latitude);
			this->lire(lesNoeuds[noeud].longitude);
			for(int i = 0; i < 4; ++i) {
				this->lire(lesNoeuds[noeud].futur[i]);
			}

			// Lecture des données variable du noeud
			DATA.seekg(lesNoeuds[noeud].partieVariable);
			this->lire(lesNoeuds[noeud].nbArcs);
			for(int i = 0; i < lesNoeuds[noeud].nbArcs; ++i) {
				uint32_t numero;
				this->lire(numero);
				this->lire(lesNoeuds[noeud].liens[numero]);
		  }

			uint16_t nombreDeCaracteres;
			this->lire(nombreDeCaracteres);

			char* nom = new char[nombreDeCaracteres];
			DATA.read(nom, nombreDeCaracteres);
			lesNoeuds[noeud].nom = nom;

			delete nom;
	  }
	}
}

void graphe::lire(uint16_t& noeud)
{
	DATA.read(reinterpret_cast<char*>(&noeud), 2);

	// Si l'architecture diffère du fichier, on swap les bits.
	int architectureMachine = this->architectureMachine();
	if((architecture == 1 && architectureMachine != __LITTLE_ENDIAN) ||
		(architecture == 0 && architectureMachine != __BIG_ENDIAN)) {
			// http://stackoverflow.com/a/2182184
			noeud = (noeud >> 8) | (noeud << 8);
	}
}

void graphe::lire(uint32_t& noeud)
{
	DATA.read(reinterpret_cast<char*>(&noeud), 4);

	// Si l'architecture diffère du fichier, on swap les bits.
	int architectureMachine = this->architectureMachine();
	if((architecture == 1 && architectureMachine != __LITTLE_ENDIAN) ||
		(architecture == 0 && architectureMachine != __BIG_ENDIAN)) {
			// http://stackoverflow.com/a/13001420
			noeud = (noeud >> 24) | ((noeud << 8) & 0x00FF0000) | ((noeud >> 8) & 0x0000FF00) | (noeud << 24);
	}
}

void graphe::lire(float& a)
{
	DATA.read(reinterpret_cast<char*>(&a), 4);

	// Si l'architecture diffère du fichier, on swap les bits.
	int architectureMachine = this->architectureMachine();
	if((architecture == 1 && architectureMachine != __LITTLE_ENDIAN) ||
		(architecture == 0 && architectureMachine != __BIG_ENDIAN)) {
			char *floatToConvert = ( char* ) & a; // http://stackoverflow.com/a/2782742
			swap(floatToConvert[0], floatToConvert[3]);
			swap(floatToConvert[1], floatToConvert[2]);
	}
}

const uint32_t graphe::size() const
{
	return this->nbNOEUDS;
}

void graphe::afficher_noeud(uint32_t noeud)
{
	this->lire_noeud(noeud);

	auto leNoeud = lesNoeuds[noeud];

	cout << "+--------------------------------------------------------------------+" << endl;
	cout << " Noeud #" << noeud << endl;
	cout << " - PartieVariable: " << leNoeud.partieVariable << endl;
	cout << " - Latitude: " << leNoeud.latitude << endl;
	cout << " - Longitude: " << leNoeud.longitude << endl;
	cout << " - Nom: " << leNoeud.nom << endl;
	for(int i = 0; i < 4; ++i) {
		cout << " -> Future[" << i << "]: " << leNoeud.futur[i] << endl;
	}
	cout << " - Nombre d'arcs: " << leNoeud.nbArcs << endl;
	for(map<uint32_t, float>::iterator it = leNoeud.liens.begin(); it != leNoeud.liens.end(); ++it) {
		cout << " -> Arc vers le noeud " << it->first << " avec un poids de " << it->second << endl;
	}
	cout << "+--------------------------------------------------------------------+" << endl;
}

const int graphe::architectureMachine() const
{
	short int word = 0x0001;
	char *byte = (char *) &word;
	return(byte[0] ? __LITTLE_ENDIAN : __BIG_ENDIAN);
}

void graphe::trouver_chemin_optimal(uint32_t premierNoeud, uint32_t secondNoeud)
{
	map<uint32_t, uint32_t> predecesseurs;			// Noeud, prédécesseur du noeud
	map<uint32_t, float> total;								  // Noeud, poids
	multimap<float, uint32_t> totalInverse;		  // Poids, Noeuds
	set<uint32_t> noeudsObserve;								// Les noeuds déjà observés
  uint32_t noeudCourant = premierNoeud;

	// On va ajouter 0 dans le total et le total inversé afin d'éviter de faire du
	// code custom juste pour la première boucle.
	total[premierNoeud] = 0;
	totalInverse.insert(pair<float, uint32_t>(0, premierNoeud));

	// Chrono
	chrono::time_point<chrono::system_clock> debut, fin;
	debut = chrono::system_clock::now();

	// Boucle afin de déterminer le chemin le plus optimal pour se rendre entre
	// le premier noeud et le deuxième.
	while(noeudCourant != secondNoeud) {

			// Aller chercher le noeud avec le poids le plus petit en partant
			while(noeudsObserve.find(noeudCourant) != noeudsObserve.end() && totalInverse.size() > 0) {
				noeudCourant = totalInverse.begin()->second;
				totalInverse.erase(totalInverse.begin());
			}

			// Si TotalInverse est vide et qu'on n'est plus sur le premier noeud,
			// alors on a fait le tour du graphe et on peut maintenant savoir le
			// chemin le plus efficace à l'aide du map des prédécesseurs.
			if(totalInverse.size() == 0 && noeudCourant != premierNoeud) {
				break;
			}

			// Puisqu'on a trouvé un noeud qu'on a pas encore parcouru, on l'ajoute a
			// la liste des noeuds parcourus et on le retire de TotalInverse.
			noeudsObserve.insert(noeudCourant);
			totalInverse.erase(totalInverse.begin());

			// Si on est rendu au noeud qu'on voulait trouver, on a trouvé le chemin
			// le plus optimal !
			if(noeudCourant != secondNoeud) {
				this->lire_noeud(noeudCourant);
				//cout << "Noeud Courant : " << noeudCourant << " | Prédécesseur: " << predecesseurs[noeudCourant] << endl;

				for(map<uint32_t, float>::iterator it = lesNoeuds[noeudCourant].liens.begin(); it != lesNoeuds[noeudCourant].liens.end(); ++it) {

					// On conserve seulement le chemin avec le plus petit poids
					float poidsTotal = it->second + total[noeudCourant];
					//cout << "Noeud: " << it->first << " | Poids: " << poidsTotal << endl;

					if(total[it->first] == 0 || total[it->first] > poidsTotal) {
						//cout << " -> Mise à jour prédécesseur # Noeud: " << it->first << " | Ancien: " << predecesseurs[noeudCourant] << " | Nouveau: " << noeudCourant << endl;
						total[it->first] = poidsTotal;
						totalInverse.insert(pair<float, uint32_t>(poidsTotal, it->first));
						predecesseurs[it->first] = noeudCourant;
					}
				}

				/*for(multimap<float, uint32_t>::iterator it = totalInverse.begin(); it != totalInverse.end(); ++it) {
					cout << "TotalInverse Noeud: " << it->second << " | Poids: " << it->first << endl;
				}
				cout << "# ------------------------------------ #" << endl;*/
			}

	}

	// On veut savoir le temps qu'a pris la méthode pour trouver le chemin le
	// plus optimal.
	fin = chrono::system_clock::now();
	chrono::duration<double> tempsEcoule = fin - debut;
	cout << "Temps pour trouvé le meilleur chemin = " << tempsEcoule.count() << "s." << endl;
}
<commit_msg>Future -> Futur<commit_after>#include "graphe.h"

#include <set>
#include <chrono>
#include <ctime>

graphe::graphe(string cheminVersFichier)
{
	DATA.open(cheminVersFichier.c_str(), ios::in|ios::binary);
	if(!DATA.is_open()) {
		cout << "Erreur d'ouverture du fichier, celui-ci n'existe pas." << endl;
		exit(1);
	} else {
		DATA >> nom;
		DATA.ignore(1);
		DATA >> nbNOEUDS;
		DATA.ignore(1);
		DATA >> architecture;
		DATA.ignore(1);

		DEBUT = DATA.tellg();

// Afficher une description du graphe si on est en debug
#ifdef _DEBUG
		cout << "Description du graphe : " << endl;
		cout << "Nom: " << nom <<endl;
		cout << "NbNoeuds: " << nbNOEUDS << endl;
		cout << "Architecture fichier: ";

		if(architecture == 0) {
			cout << "BigEndian";
		} else if (architecture == 1) {
			cout << "LittleEndian";
		}

		cout << endl << "Architecture machine: ";
		if(this->architectureMachine() == __LITTLE_ENDIAN) {
			cout << "LittleEndian";
		} else {
			cout << "BigEndian";
		}

		cout << endl;
		cout << "----------------------------------------" << endl;
#endif

	}
}

graphe::~graphe()
{
	// Fermer le fichier a la sortie du programme.
	if (DATA.is_open()) {
		DATA.close();
	}
}

void graphe::lire_noeud(uint32_t noeud)
{
	if(noeud < nbNOEUDS) {
		// Si le noeud n'a jamais été lu, alors il va l'être !
		if(lesNoeuds[noeud].partieVariable == 0) {

			// Lecture des données statiques du noeud
			DATA.seekg(DEBUT + (28 * noeud), ios::beg);
			this->lire(lesNoeuds[noeud].partieVariable);
			this->lire(lesNoeuds[noeud].latitude);
			this->lire(lesNoeuds[noeud].longitude);
			for(int i = 0; i < 4; ++i) {
				this->lire(lesNoeuds[noeud].futur[i]);
			}

			// Lecture des données variable du noeud
			DATA.seekg(lesNoeuds[noeud].partieVariable);
			this->lire(lesNoeuds[noeud].nbArcs);
			for(int i = 0; i < lesNoeuds[noeud].nbArcs; ++i) {
				uint32_t numero;
				this->lire(numero);
				this->lire(lesNoeuds[noeud].liens[numero]);
		  }

			uint16_t nombreDeCaracteres;
			this->lire(nombreDeCaracteres);

			char* nom = new char[nombreDeCaracteres];
			DATA.read(nom, nombreDeCaracteres);
			lesNoeuds[noeud].nom = nom;

			delete nom;
	  }
	}
}

void graphe::lire(uint16_t& noeud)
{
	DATA.read(reinterpret_cast<char*>(&noeud), 2);

	// Si l'architecture diffère du fichier, on swap les bits.
	int architectureMachine = this->architectureMachine();
	if((architecture == 1 && architectureMachine != __LITTLE_ENDIAN) ||
		(architecture == 0 && architectureMachine != __BIG_ENDIAN)) {
			// http://stackoverflow.com/a/2182184
			noeud = (noeud >> 8) | (noeud << 8);
	}
}

void graphe::lire(uint32_t& noeud)
{
	DATA.read(reinterpret_cast<char*>(&noeud), 4);

	// Si l'architecture diffère du fichier, on swap les bits.
	int architectureMachine = this->architectureMachine();
	if((architecture == 1 && architectureMachine != __LITTLE_ENDIAN) ||
		(architecture == 0 && architectureMachine != __BIG_ENDIAN)) {
			// http://stackoverflow.com/a/13001420
			noeud = (noeud >> 24) | ((noeud << 8) & 0x00FF0000) | ((noeud >> 8) & 0x0000FF00) | (noeud << 24);
	}
}

void graphe::lire(float& a)
{
	DATA.read(reinterpret_cast<char*>(&a), 4);

	// Si l'architecture diffère du fichier, on swap les bits.
	int architectureMachine = this->architectureMachine();
	if((architecture == 1 && architectureMachine != __LITTLE_ENDIAN) ||
		(architecture == 0 && architectureMachine != __BIG_ENDIAN)) {
			char *floatToConvert = ( char* ) & a; // http://stackoverflow.com/a/2782742
			swap(floatToConvert[0], floatToConvert[3]);
			swap(floatToConvert[1], floatToConvert[2]);
	}
}

const uint32_t graphe::size() const
{
	return this->nbNOEUDS;
}

void graphe::afficher_noeud(uint32_t noeud)
{
	this->lire_noeud(noeud);

	auto leNoeud = lesNoeuds[noeud];

	cout << "+--------------------------------------------------------------------+" << endl;
	cout << " Noeud #" << noeud << endl;
	cout << " - PartieVariable: " << leNoeud.partieVariable << endl;
	cout << " - Latitude: " << leNoeud.latitude << endl;
	cout << " - Longitude: " << leNoeud.longitude << endl;
	cout << " - Nom: " << leNoeud.nom << endl;
	for(int i = 0; i < 4; ++i) {
		cout << " -> Futur[" << i << "]: " << leNoeud.futur[i] << endl;
	}
	cout << " - Nombre d'arcs: " << leNoeud.nbArcs << endl;
	for(map<uint32_t, float>::iterator it = leNoeud.liens.begin(); it != leNoeud.liens.end(); ++it) {
		cout << " -> Arc vers le noeud " << it->first << " avec un poids de " << it->second << endl;
	}
	cout << "+--------------------------------------------------------------------+" << endl;
}

const int graphe::architectureMachine() const
{
	short int word = 0x0001;
	char *byte = (char *) &word;
	return(byte[0] ? __LITTLE_ENDIAN : __BIG_ENDIAN);
}

void graphe::trouver_chemin_optimal(uint32_t premierNoeud, uint32_t secondNoeud)
{
	map<uint32_t, uint32_t> predecesseurs;			// Noeud, prédécesseur du noeud
	map<uint32_t, float> total;								  // Noeud, poids
	multimap<float, uint32_t> totalInverse;		  // Poids, Noeuds
	set<uint32_t> noeudsObserve;								// Les noeuds déjà observés
  uint32_t noeudCourant = premierNoeud;

	// On va ajouter 0 dans le total et le total inversé afin d'éviter de faire du
	// code custom juste pour la première boucle.
	total[premierNoeud] = 0;
	totalInverse.insert(pair<float, uint32_t>(0, premierNoeud));

	// Chrono
	chrono::time_point<chrono::system_clock> debut, fin;
	debut = chrono::system_clock::now();

	// Boucle afin de déterminer le chemin le plus optimal pour se rendre entre
	// le premier noeud et le deuxième.
	while(noeudCourant != secondNoeud) {

			// Aller chercher le noeud avec le poids le plus petit en partant
			while(noeudsObserve.find(noeudCourant) != noeudsObserve.end() && totalInverse.size() > 0) {
				noeudCourant = totalInverse.begin()->second;
				totalInverse.erase(totalInverse.begin());
			}

			// Si TotalInverse est vide et qu'on n'est plus sur le premier noeud,
			// alors on a fait le tour du graphe et on peut maintenant savoir le
			// chemin le plus efficace à l'aide du map des prédécesseurs.
			if(totalInverse.size() == 0 && noeudCourant != premierNoeud) {
				break;
			}

			// Puisqu'on a trouvé un noeud qu'on a pas encore parcouru, on l'ajoute a
			// la liste des noeuds parcourus et on le retire de TotalInverse.
			noeudsObserve.insert(noeudCourant);
			totalInverse.erase(totalInverse.begin());

			// Si on est rendu au noeud qu'on voulait trouver, on a trouvé le chemin
			// le plus optimal !
			if(noeudCourant != secondNoeud) {
				this->lire_noeud(noeudCourant);
				//cout << "Noeud Courant : " << noeudCourant << " | Prédécesseur: " << predecesseurs[noeudCourant] << endl;

				for(map<uint32_t, float>::iterator it = lesNoeuds[noeudCourant].liens.begin(); it != lesNoeuds[noeudCourant].liens.end(); ++it) {

					// On conserve seulement le chemin avec le plus petit poids
					float poidsTotal = it->second + total[noeudCourant];
					//cout << "Noeud: " << it->first << " | Poids: " << poidsTotal << endl;

					if(total[it->first] == 0 || total[it->first] > poidsTotal) {
						//cout << " -> Mise à jour prédécesseur # Noeud: " << it->first << " | Ancien: " << predecesseurs[noeudCourant] << " | Nouveau: " << noeudCourant << endl;
						total[it->first] = poidsTotal;
						totalInverse.insert(pair<float, uint32_t>(poidsTotal, it->first));
						predecesseurs[it->first] = noeudCourant;
					}
				}

				/*for(multimap<float, uint32_t>::iterator it = totalInverse.begin(); it != totalInverse.end(); ++it) {
					cout << "TotalInverse Noeud: " << it->second << " | Poids: " << it->first << endl;
				}
				cout << "# ------------------------------------ #" << endl;*/
			}

	}

	// On veut savoir le temps qu'a pris la méthode pour trouver le chemin le
	// plus optimal.
	fin = chrono::system_clock::now();
	chrono::duration<double> tempsEcoule = fin - debut;
	cout << "Temps pour trouvé le meilleur chemin = " << tempsEcoule.count() << "s." << endl;
}
<|endoftext|>


<commit_before>#include "BackBufferMaker.h"
#include "Director.h"

#include "EngineShaderFactory.hpp"
#include "ResourceManager.h"

using namespace Rendering::PostProcessing;
using namespace Rendering::Shader;
using namespace Rendering::Buffer;
using namespace Rendering::Texture;
using namespace Rendering::Mesh;
using namespace Device;
using namespace Math;
using namespace Core;
using namespace Resource;

BackBufferMaker::BackBufferMaker()
	:	_vertexShader(nullptr), _pixelShader(nullptr), _depthBuffer(nullptr),
		_meshFilter(nullptr)
{
}

BackBufferMaker::~BackBufferMaker()
{
	Destroy();
}

void BackBufferMaker::Initialize()
{
	ResourceManager* resourceManager = ResourceManager::GetInstance();
	Manager::ShaderManager* shaderMgr = resourceManager->GetShaderManager();

	Factory::EngineFactory shaderLoader(shaderMgr);
	shaderLoader.LoadShader("BackBufferMaker", "VS", "PS", nullptr, nullptr, &_vertexShader, &_pixelShader);
	ASSERT_COND_MSG(_vertexShader && _pixelShader, "Error, Cant load BackBufferMaker shader files");

	const Size<uint>& winSize = GlobalDeviceDirectorGetScreenSize;

	ConstBuffer* transformConstBuffer = new ConstBuffer;
	transformConstBuffer->Initialize(sizeof(Matrix));
	{
		Matrix world, view, proj;

		Matrix::Identity(world);
		world._43 = -10;

		Camera::CameraForm::ViewMatrix(view, world);
		Matrix::OrthoLH(proj, (float)winSize.w, (float)winSize.h, 0.01f, 1000.0f);

		Matrix viewProj = view * proj;
		Matrix::Transpose(viewProj, viewProj);

		ID3D11DeviceContext* context = Device::Director::GetInstance()->GetDirectX()->GetContext();
		transformConstBuffer->Update(context, &viewProj);

		BaseShader::BufferType bufferType;
		bufferType.first	= 0;
		bufferType.second	= transformConstBuffer;
		_constBuffers.push_back(bufferType);
	}
	{
		for(int i=0; i<2; ++i)
		{
			BaseShader::TextureType type;
			type.first = i;
			type.second = nullptr;

			_textures.push_back(type);
		}
	}

	_depthBuffer = new DepthBuffer;
	_depthBuffer->Initialize(winSize);

	//Initialize Mesh
	{
		Mesh::MeshFilter::CreateFuncArguments meshCreateArgs("BackBufferMaker", "BackBufferMaker");

		struct Vertex
		{
			Math::Vector3	position;
			Math::Vector2	uv;
		};

		float left		= -(winSize.w / 2.0f);
		float right		= -left;
		float bottom	= -(winSize.h / 2.0f);
		float top		= -bottom;

		Vertex vertices[4];
		memset(vertices, 0, sizeof(Vertex) * 4);
		{
			vertices[0].position.x	= left;
			vertices[0].position.y	= top;
			vertices[0].position.z	= 0.0f;

			vertices[0].uv.x		= 0.0f;
			vertices[0].uv.y		= 0.0f;

			vertices[1].position.x	= right;
			vertices[1].position.y	= top;
			vertices[1].position.z	= 0.0f;

			vertices[1].uv.x		= 1.0f;
			vertices[1].uv.y		= 0.0f;

			vertices[2].position.x	= left;
			vertices[2].position.y	= bottom;
			vertices[2].position.z	= 0.0f;

			vertices[2].uv.x		= 0.0f;
			vertices[2].uv.y		= 1.0f;

			vertices[3].position.x	= right;
			vertices[3].position.y	= bottom;
			vertices[3].position.z	= 0.0f;

			vertices[3].uv.x		=  1.0f;
			vertices[3].uv.y		=  1.0f;
		}

		uint indices[] =
		{
			0, 1, 2,
			1, 3, 2
		};

		meshCreateArgs.vertex.data		= vertices;
		meshCreateArgs.vertex.count		= 4;
		meshCreateArgs.vertex.byteWidth	= sizeof(Vertex);

		meshCreateArgs.index.data		= indices;
		meshCreateArgs.index.count		= ARRAYSIZE(indices);
		meshCreateArgs.index.byteWidth	= 0; //not use

		meshCreateArgs.isDynamic		= false;
		meshCreateArgs.bufferFlag		= (uint)Mesh::MeshFilter::BufferElement::UV;

		_meshFilter = new MeshFilter;
		_meshFilter->CreateBuffer(meshCreateArgs);
	}
}

void BackBufferMaker::Destroy()
{
	for(auto iter : _constBuffers)
		SAFE_DELETE(iter.second);

	SAFE_DELETE(_depthBuffer);
	SAFE_DELETE(_meshFilter);
}

void BackBufferMaker::Render(const Device::DirectX* dx, const Rendering::Camera::CameraForm* mainCamera, const Rendering::Camera::UICamera* uiCamera)
{
	ID3D11DeviceContext* context		= dx->GetContext();

	const RenderTexture* mainCamRT	= mainCamera ? mainCamera->GetRenderTarget() : nullptr;
	const RenderTexture* uiCamRT	= uiCamera ? uiCamera->GetRenderTarget() : nullptr;

	ID3D11RenderTargetView* deviceBackBuffer = dx->GetBackBuffer();
	context->OMSetRenderTargets(1, &deviceBackBuffer, _depthBuffer->GetDepthStencilView());
	_depthBuffer->Clear(context, 1.0f, 0);

	float color[] = {0, 0, 0, 1};
	context->ClearRenderTargetView(deviceBackBuffer, color);

	ID3D11SamplerState* sampler = dx->GetPointSamplerState();
	context->PSSetSamplers(0, 1, &sampler);
	{
		_meshFilter->IASetBuffer(dx);

		_vertexShader->UpdateShader(context);
		_vertexShader->UpdateInputLayout(context);
		_vertexShader->UpdateResources(context, &_constBuffers, nullptr);

		_pixelShader->UpdateShader(context);
		_textures[0].second = mainCamRT;
		_textures[1].second = uiCamRT;
		_pixelShader->UpdateResources(context, nullptr, &_textures);

		context->DrawIndexed(_meshFilter->GetIndexCount(), 0, 0);
	}
	ID3D11SamplerState* nullSampler = nullptr;
	context->PSSetSamplers(0, 1, &nullSampler);
}<commit_msg>BackBufferMaker - LoadShader 변경으로 인한 코드 수정 #68<commit_after>#include "BackBufferMaker.h"
#include "Director.h"

#include "EngineShaderFactory.hpp"
#include "ResourceManager.h"

using namespace Rendering::PostProcessing;
using namespace Rendering::Shader;
using namespace Rendering::Buffer;
using namespace Rendering::Texture;
using namespace Rendering::Mesh;
using namespace Device;
using namespace Math;
using namespace Core;
using namespace Resource;

BackBufferMaker::BackBufferMaker()
	:	_vertexShader(nullptr), _pixelShader(nullptr), _depthBuffer(nullptr),
		_meshFilter(nullptr)
{
}

BackBufferMaker::~BackBufferMaker()
{
	Destroy();
}

void BackBufferMaker::Initialize()
{
	ResourceManager* resourceManager = ResourceManager::GetInstance();
	Manager::ShaderManager* shaderMgr = resourceManager->GetShaderManager();

	Factory::EngineFactory shaderLoader(shaderMgr);
	shaderLoader.LoadShader("BackBufferMaker", "VS", "PS", nullptr, &_vertexShader, &_pixelShader);
	ASSERT_COND_MSG(_vertexShader && _pixelShader, "Error, Cant load BackBufferMaker shader files");

	const Size<uint>& winSize = GlobalDeviceDirectorGetScreenSize;

	ConstBuffer* transformConstBuffer = new ConstBuffer;
	transformConstBuffer->Initialize(sizeof(Matrix));
	{
		Matrix world, view, proj;

		Matrix::Identity(world);
		world._43 = -10;

		Camera::CameraForm::ViewMatrix(view, world);
		Matrix::OrthoLH(proj, (float)winSize.w, (float)winSize.h, 0.01f, 1000.0f);

		Matrix viewProj = view * proj;
		Matrix::Transpose(viewProj, viewProj);

		ID3D11DeviceContext* context = Device::Director::GetInstance()->GetDirectX()->GetContext();
		transformConstBuffer->Update(context, &viewProj);

		BaseShader::BufferType bufferType;
		bufferType.first	= 0;
		bufferType.second	= transformConstBuffer;
		_constBuffers.push_back(bufferType);
	}
	{
		for(int i=0; i<2; ++i)
		{
			BaseShader::TextureType type;
			type.first = i;
			type.second = nullptr;

			_textures.push_back(type);
		}
	}

	_depthBuffer = new DepthBuffer;
	_depthBuffer->Initialize(winSize);

	//Initialize Mesh
	{
		Mesh::MeshFilter::CreateFuncArguments meshCreateArgs("BackBufferMaker", "BackBufferMaker");

		struct Vertex
		{
			Math::Vector3	position;
			Math::Vector2	uv;
		};

		float left		= -(winSize.w / 2.0f);
		float right		= -left;
		float bottom	= -(winSize.h / 2.0f);
		float top		= -bottom;

		Vertex vertices[4];
		memset(vertices, 0, sizeof(Vertex) * 4);
		{
			vertices[0].position.x	= left;
			vertices[0].position.y	= top;
			vertices[0].position.z	= 0.0f;

			vertices[0].uv.x		= 0.0f;
			vertices[0].uv.y		= 0.0f;

			vertices[1].position.x	= right;
			vertices[1].position.y	= top;
			vertices[1].position.z	= 0.0f;

			vertices[1].uv.x		= 1.0f;
			vertices[1].uv.y		= 0.0f;

			vertices[2].position.x	= left;
			vertices[2].position.y	= bottom;
			vertices[2].position.z	= 0.0f;

			vertices[2].uv.x		= 0.0f;
			vertices[2].uv.y		= 1.0f;

			vertices[3].position.x	= right;
			vertices[3].position.y	= bottom;
			vertices[3].position.z	= 0.0f;

			vertices[3].uv.x		=  1.0f;
			vertices[3].uv.y		=  1.0f;
		}

		uint indices[] =
		{
			0, 1, 2,
			1, 3, 2
		};

		meshCreateArgs.vertex.data		= vertices;
		meshCreateArgs.vertex.count		= 4;
		meshCreateArgs.vertex.byteWidth	= sizeof(Vertex);

		meshCreateArgs.index.data		= indices;
		meshCreateArgs.index.count		= ARRAYSIZE(indices);
		meshCreateArgs.index.byteWidth	= 0; //not use

		meshCreateArgs.isDynamic		= false;

		_meshFilter = new MeshFilter;
		_meshFilter->CreateBuffer(meshCreateArgs);
	}
}

void BackBufferMaker::Destroy()
{
	for(auto iter : _constBuffers)
		SAFE_DELETE(iter.second);

	SAFE_DELETE(_depthBuffer);
	SAFE_DELETE(_meshFilter);
}

void BackBufferMaker::Render(const Device::DirectX* dx, const Rendering::Camera::CameraForm* mainCamera, const Rendering::Camera::UICamera* uiCamera)
{
	ID3D11DeviceContext* context		= dx->GetContext();

	const RenderTexture* mainCamRT	= mainCamera ? mainCamera->GetRenderTarget() : nullptr;
	const RenderTexture* uiCamRT	= uiCamera ? uiCamera->GetRenderTarget() : nullptr;

	ID3D11RenderTargetView* deviceBackBuffer = dx->GetBackBuffer();
	context->OMSetRenderTargets(1, &deviceBackBuffer, _depthBuffer->GetDepthStencilView());
	_depthBuffer->Clear(context, 1.0f, 0);

	float color[] = {0, 0, 0, 1};
	context->ClearRenderTargetView(deviceBackBuffer, color);

	ID3D11SamplerState* sampler = dx->GetPointSamplerState();
	context->PSSetSamplers(0, 1, &sampler);
	{
		_meshFilter->IASetBuffer(dx);

		_vertexShader->UpdateShader(context);
		_vertexShader->UpdateInputLayout(context);
		_vertexShader->UpdateResources(context, &_constBuffers, nullptr);

		_pixelShader->UpdateShader(context);
		_textures[0].second = mainCamRT;
		_textures[1].second = uiCamRT;
		_pixelShader->UpdateResources(context, nullptr, &_textures);

		context->DrawIndexed(_meshFilter->GetIndexCount(), 0, 0);
	}
	ID3D11SamplerState* nullSampler = nullptr;
	context->PSSetSamplers(0, 1, &nullSampler);
}<|endoftext|>


<commit_before>/*
    This file is part of Csound.

    The Csound Library is free software; you can redistribute it
    and/or modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    Csound 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 Csound; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
    02111-1307 USA
 */
#include "OpcodeBase.hpp"

#include <cmath>

/**
 * Musically map MIDI velocity to peak amplitude
 * within a specified dynamic range in decibels:
 * a = (m * v + b) ^ 2
 * where a = amplitude,
 * v = MIDI velocity,
 * r = 10 ^ (R / 20),
 * b = 127 / (126 * sqrt( r )) - 1 / 126,
 * m = (1 - b) / 127,
 * and R = specified dynamic range in decibels.
 * See Roger Dannenberg, "The Interpretation of MIDI Velocity,"
 * in Georg Essl and Ichiro Fujinaga (Eds.), Proceedings of the
 * 2006 International Computer Music Conference,
 * November 6-11, 2006 (San Francisco:
 * The International Computer Music Association), pp. 193-196.
 */
class KAMPMIDID : public OpcodeBase<KAMPMIDID>
{
public:
  // Outputs.
  MYFLT *kamplitude;
  // Inputs.
  MYFLT *kvelocity;
  MYFLT *irdb;
  // State.
  MYFLT ir;
  MYFLT im;
  MYFLT ib;
  MYFLT onedrms;
  KAMPMIDID() {}
  int init(CSOUND *csound)
  {
      // Convert RMS power to amplitude (assuming a sinusoidal signal).
      onedrms = MYFLT(1.0) / MYFLT(0.707);
      // Convert dynamic range in decibels to RMS dynamic range.
      ir = std::pow( MYFLT(10.0), *irdb / MYFLT(20.0) );
      // Solve for coefficients of the linear conversion function given
      // RMS dynamic range.
      ib = MYFLT(127.0) / ( MYFLT(126.0) * std::sqrt(ir) ) -
        MYFLT(1.0) / MYFLT(126.0);
      im = ( MYFLT(1.0) - ib ) / MYFLT(127.0);
      return OK;
  }
  int kontrol(CSOUND *csound)
  {
      *kamplitude = std::pow( (im * (*kvelocity + ib) ), MYFLT(2.0) ) * onedrms;
      return OK;
  }
};

class IAMPMIDID : public OpcodeBase<IAMPMIDID>
{
public:
  // Outputs.
  MYFLT *iamplitude;
  // Inputs.
  MYFLT *ivelocity;
  MYFLT *irdb;
  // State.
  MYFLT ir;
  MYFLT im;
  MYFLT ib;
  MYFLT onedrms;
  IAMPMIDID() {}
  int init(CSOUND *csound)
  {
      // Convert RMS power to amplitude (assuming a sinusoidal signal).
      onedrms = MYFLT(1.0) / MYFLT(0.707);
      // Convert dynamic range in decibels to RMS dynamic range.
      ir = std::pow( MYFLT(10.0), *irdb / MYFLT(20.0) );
      // Solve for coefficients of the linear conversion function given
      // RMS dynamic range.
      ib = MYFLT(127.0) / ( MYFLT(126.0) * std::sqrt(ir) ) -
        MYFLT(1.0) / MYFLT(126.0);
      im = ( MYFLT(1.0) - ib ) / MYFLT(127.0);
      *iamplitude = std::pow( (im * (*ivelocity + ib) ), MYFLT(2.0) ) * onedrms;
      return OK;
  }
  int noteoff(CSOUND *)
  {
    return OK;
  }
};

extern "C" {

  PUBLIC int csoundModuleCreate(CSOUND *csound)
  {
      return 0;
  }

  PUBLIC int csoundModuleInit(CSOUND *csound)
  {
      int status = csound->AppendOpcode(csound,
                                        (char*)"kampmidid",
                                        sizeof(KAMPMIDID),
                                        3,
                                        (char*)"k",
                                        (char*)"ki",
                                        (int(*)(CSOUND*,void*)) KAMPMIDID::init_,
                                        (int(*)(CSOUND*,void*)) KAMPMIDID::kontrol_,
                                        (int (*)(CSOUND*,void*)) 0);

      status |= csound->AppendOpcode(csound,
                                     (char*)"iampmidid",
                                     sizeof(IAMPMIDID),
                                     1,
                                     (char*)"i",
                                     (char*)"ii",
                                     (int (*)(CSOUND*,void*)) IAMPMIDID::init_,
                                     (int (*)(CSOUND*,void*)) 0,
                                     (int (*)(CSOUND*,void*)) 0);
      return status;
  }

  PUBLIC int csoundModuleDestroy(CSOUND *csound)
  {
      return 0;
  }
}

<commit_msg>Changed kampmidid and iampmidid to polymorphic ampmidid.i and ampmidid.k.<commit_after>/*
    This file is part of Csound.

    The Csound Library is free software; you can redistribute it
    and/or modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    Csound 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 Csound; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
    02111-1307 USA
 */
#include "OpcodeBase.hpp"

#include <cmath>

/**
 * Musically map MIDI velocity to peak amplitude
 * within a specified dynamic range in decibels:
 * a = (m * v + b) ^ 2
 * where a = amplitude,
 * v = MIDI velocity,
 * r = 10 ^ (R / 20),
 * b = 127 / (126 * sqrt( r )) - 1 / 126,
 * m = (1 - b) / 127,
 * and R = specified dynamic range in decibels.
 * See Roger Dannenberg, "The Interpretation of MIDI Velocity,"
 * in Georg Essl and Ichiro Fujinaga (Eds.), Proceedings of the
 * 2006 International Computer Music Conference,
 * November 6-11, 2006 (San Francisco:
 * The International Computer Music Association), pp. 193-196.
 */
class KAMPMIDID : public OpcodeBase<KAMPMIDID>
{
public:
  // Outputs.
  MYFLT *kamplitude;
  // Inputs.
  MYFLT *kvelocity;
  MYFLT *irdb;
  // State.
  MYFLT ir;
  MYFLT im;
  MYFLT ib;
  MYFLT onedrms;
  KAMPMIDID() {}
  int init(CSOUND *csound)
  {
      // Convert RMS power to amplitude (assuming a sinusoidal signal).
      onedrms = MYFLT(1.0) / MYFLT(0.707);
      // Convert dynamic range in decibels to RMS dynamic range.
      ir = std::pow( MYFLT(10.0), *irdb / MYFLT(20.0) );
      // Solve for coefficients of the linear conversion function given
      // RMS dynamic range.
      ib = MYFLT(127.0) / ( MYFLT(126.0) * std::sqrt(ir) ) -
        MYFLT(1.0) / MYFLT(126.0);
      im = ( MYFLT(1.0) - ib ) / MYFLT(127.0);
      return OK;
  }
  int kontrol(CSOUND *csound)
  {
      *kamplitude = std::pow( (im * (*kvelocity + ib) ), MYFLT(2.0) ) * onedrms;
      return OK;
  }
};

class IAMPMIDID : public OpcodeBase<IAMPMIDID>
{
public:
  // Outputs.
  MYFLT *iamplitude;
  // Inputs.
  MYFLT *ivelocity;
  MYFLT *irdb;
  // State.
  MYFLT ir;
  MYFLT im;
  MYFLT ib;
  MYFLT onedrms;
  IAMPMIDID() {}
  int init(CSOUND *csound)
  {
      // Convert RMS power to amplitude (assuming a sinusoidal signal).
      onedrms = MYFLT(1.0) / MYFLT(0.707);
      // Convert dynamic range in decibels to RMS dynamic range.
      ir = std::pow( MYFLT(10.0), *irdb / MYFLT(20.0) );
      // Solve for coefficients of the linear conversion function given
      // RMS dynamic range.
      ib = MYFLT(127.0) / ( MYFLT(126.0) * std::sqrt(ir) ) -
        MYFLT(1.0) / MYFLT(126.0);
      im = ( MYFLT(1.0) - ib ) / MYFLT(127.0);
      *iamplitude = std::pow( (im * (*ivelocity + ib) ), MYFLT(2.0) ) * onedrms;
      return OK;
  }
  int noteoff(CSOUND *)
  {
    return OK;
  }
};

extern "C" {

  PUBLIC int csoundModuleCreate(CSOUND *csound)
  {
      return 0;
  }

  PUBLIC int csoundModuleInit(CSOUND *csound)
  {
      int status = csound->AppendOpcode(csound,
                                        (char*)"ampmidid.k",
                                        sizeof(KAMPMIDID),
                                        3,
                                        (char*)"k",
                                        (char*)"ki",
                                        (int(*)(CSOUND*,void*)) KAMPMIDID::init_,
                                        (int(*)(CSOUND*,void*)) KAMPMIDID::kontrol_,
                                        (int (*)(CSOUND*,void*)) 0);
      status |= csound->AppendOpcode(csound,
                                     (char*)"ampmidid.i",
                                     sizeof(IAMPMIDID),
                                     1,
                                     (char*)"i",
                                     (char*)"ii",
                                     (int (*)(CSOUND*,void*)) IAMPMIDID::init_,
                                     (int (*)(CSOUND*,void*)) 0,
                                     (int (*)(CSOUND*,void*)) 0);
      status |= csound->AppendOpcode(csound,
                                        (char*)"ampmidid",
                                        0xffff,
                                        0,
                                        0,
                                        0,
                                        0,
                                        0,
                                        0);
      return status;
  }

  PUBLIC int csoundModuleDestroy(CSOUND *csound)
  {
      return 0;
  }
}

<|endoftext|>