<commit_before>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor_types.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/kernels/bounds_check.h"
#include "tensorflow/contrib/repeat/kernels/repeat_op.h"

namespace tensorflow{

typedef Eigen::ThreadPoolDevice CPUDevice;
#if GOOGLE_CUDA
typedef Eigen::GpuDevice GPUDevice;
#endif // GOOGLE_CUDA

template <typename Device, typename T>
class RepeatOp : public OpKernel {
 public:
  explicit RepeatOp(OpKernelConstruction* context) : OpKernel(context) {
    OP_REQUIRES_OK(context, context->GetAttr("axis", &axis_));
  }

  void Compute(OpKernelContext* context) override {
    const Tensor& input = context->input(0);
    const Tensor& repeats = context->input(1);

    OP_REQUIRES(context, TensorShapeUtils::IsVector(repeats.shape()) ||
                         TensorShapeUtils::IsScalar(repeats.shape()),
                errors::InvalidArgument("`repeats` expects a scalar or a 1-D vector."));
    OP_REQUIRES(context, repeats.NumElements() == input.dim_size(axis_) ||
                         repeats.NumElements() == 1,
                errors::InvalidArgument(
                    "Expected `repeats` argument to be a vector of length ",
                    input.dim_size(axis_), " or 1, but got length ",
                    repeats.NumElements()));
    OP_REQUIRES(context, FastBoundsCheck(axis_, input.dims()),
                errors::InvalidArgument("Expected 0 <= `axis` < ", input.dims()));

    TensorShape output_shape = input.shape();
    auto repeats_flat = repeats.flat<int32>();
    const int old_dim = input.shape().dim_size(axis_);
    int new_dim = 0;
    if (repeats.NumElements() == 1) {
      new_dim = repeats_flat(0) * old_dim;
    } else {
      const int N = repeats_flat.size();
      for (int i = 0; i < N; ++i) {
        new_dim += repeats_flat(i);
      }
    }
    output_shape.set_dim(axis_, new_dim);

    Tensor* output = NULL;
    OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output));

#if GOOGLE_CUDA
    if (std::is_same<Device, GPUDevice>::value) {
      RepeatGPUImpl<T>(context->eigen_gpu_device(), input, repeats_flat, axis_, output);
      return ;
    }
#endif // GOOGLE_CUDA

    RepeatCPUImplV2<T>(context->device(), input, repeats_flat,
                       axis_, 10000, output);
  }

 private:
  int32 axis_;

};

#define REGISTER_KERNEL(type)                    \
  REGISTER_KERNEL_BUILDER(                       \
      Name("Repeat")                             \
      .Device(DEVICE_CPU)                        \
      .TypeConstraint<type>("T"),                \
      RepeatOp<CPUDevice, type>)

TF_CALL_ALL_TYPES(REGISTER_KERNEL);

#undef REGISTER_KERNEL

#if GOOGLE_CUDA

#define REGISTER_KERNEL_GPU(type)                \
  REGISTER_KERNEL_BUILDER(                       \
      Name("Repeat")                             \
      .Device(DEVICE_GPU)                        \
      .TypeConstraint<type>("T")                 \
      .HostMemory("repeats"),                    \
      RepeatOp<GPUDevice, type>)

TF_CALL_GPU_NUMBER_TYPES(REGISTER_KERNEL_GPU);

#undef REGISTER_KERNEL_GPU

#endif // GOOGLE_CUDA

} //end namespace tensorflow
<commit_msg>Add support for scalar input and negative axis<commit_after>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor_types.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/kernels/bounds_check.h"
#include "tensorflow/contrib/repeat/kernels/repeat_op.h"

namespace tensorflow{

typedef Eigen::ThreadPoolDevice CPUDevice;
#if GOOGLE_CUDA
typedef Eigen::GpuDevice GPUDevice;
#endif // GOOGLE_CUDA

template <typename Device, typename T>
class RepeatOp : public OpKernel {
 public:
  explicit RepeatOp(OpKernelConstruction* context) : OpKernel(context) {
    OP_REQUIRES_OK(context, context->GetAttr("axis", &axis_));
  }

  void Compute(OpKernelContext* context) override {
    const Tensor& input = context->input(0);
    const Tensor& repeats = context->input(1);
    const int input_rank = input.dims()==0 ? 1 : input.dims();
    const int32 axis = axis_>=0 ? axis_ : axis_+input_rank;

    OP_REQUIRES(context, TensorShapeUtils::IsVector(repeats.shape()) ||
                         TensorShapeUtils::IsScalar(repeats.shape()),
                errors::InvalidArgument("`repeats` expects a scalar or a 1-D vector."));
    OP_REQUIRES(context, FastBoundsCheck(axis, input_rank),
                errors::InvalidArgument(
                    "Expected -", input_rank, " <= `axis` < ", input_rank));
    OP_REQUIRES(context, repeats.NumElements() == input.dim_size(axis) ||
                         repeats.NumElements() == 1,
                errors::InvalidArgument(
                    "Expected `repeats` argument to be a vector of length ",
                    input.dim_size(axis_), " or 1, but got length ",
                    repeats.NumElements()));

    auto repeats_flat = repeats.flat<int32>();
    TensorShape output_shape({1});
    int old_dim;
    if (input.dims() != 0) {
      output_shape = input.shape();
      old_dim = input.shape().dim_size(axis);
    } else {
      old_dim = 1;
    }
    int new_dim = 0;
    if (repeats.NumElements() == 1) {
      new_dim = repeats_flat(0) * old_dim;
    } else {
      const int N = repeats_flat.size();
      for (int i = 0; i < N; ++i) {
        new_dim += repeats_flat(i);
      }
    }
    output_shape.set_dim(axis, new_dim);

    Tensor* output = NULL;
    OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output));

#if GOOGLE_CUDA
    if (std::is_same<Device, GPUDevice>::value) {
      RepeatGPUImpl<T>(context->eigen_gpu_device(), input, repeats_flat, axis, output);
      return ;
    }
#endif // GOOGLE_CUDA

    RepeatCPUImplV2<T>(context->device(), input, repeats_flat,
                       axis, 10000, output);
  }

 private:
  int32 axis_;

};

#define REGISTER_KERNEL(type)                    \
  REGISTER_KERNEL_BUILDER(                       \
      Name("Repeat")                             \
      .Device(DEVICE_CPU)                        \
      .TypeConstraint<type>("T"),                \
      RepeatOp<CPUDevice, type>)

TF_CALL_ALL_TYPES(REGISTER_KERNEL);

#undef REGISTER_KERNEL

#if GOOGLE_CUDA

#define REGISTER_KERNEL_GPU(type)                \
  REGISTER_KERNEL_BUILDER(                       \
      Name("Repeat")                             \
      .Device(DEVICE_GPU)                        \
      .TypeConstraint<type>("T")                 \
      .HostMemory("repeats"),                    \
      RepeatOp<GPUDevice, type>)

TF_CALL_GPU_NUMBER_TYPES(REGISTER_KERNEL_GPU);

#undef REGISTER_KERNEL_GPU

#endif // GOOGLE_CUDA

} //end namespace tensorflow
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

//#define MAIN

#include "otbImage.h"
#include "itkVectorImage.h"
#include "itkExceptionObject.h"
#include <iostream>
#include "itkComplexToModulusImageFilter.h"
#include "itkStreamingImageFilter.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbMultiChannelExtractROI.h"

int otbImageFileReaderERS(int argc, char* argv[])
{
  try
  {
        // Verify the number of parameters in the command line
        const char * inputFilename  = argv[1];
        const char * outputFilename = argv[2];

        typedef float  	                        InputPixelType;
        typedef unsigned short                           OutputPixelType;
        const   unsigned int        	        Dimension = 2;

        typedef otb::VectorImage< InputPixelType,  Dimension >        InputImageType;
        typedef otb::VectorImage< OutputPixelType, Dimension >        OutputImageType;

        typedef otb::ImageFileReader< InputImageType  >         ReaderType;
        typedef otb::ImageFileWriter< OutputImageType >         WriterType;

        typedef itk::StreamingImageFilter< InputImageType, OutputImageType >         StreamingType;

        StreamingType::Pointer streaming = StreamingType::New();
        ReaderType::Pointer complexReader = ReaderType::New();

	complexReader->SetFileName( inputFilename  );
	streaming->SetNumberOfStreamDivisions(100);
	streaming->SetInput(complexReader->GetOutput());

        typedef otb::MultiChannelExtractROI< OutputPixelType,
                                             OutputPixelType >  ExtractROIFilterType;

        ExtractROIFilterType::Pointer extractROIFilter = ExtractROIFilterType::New();

	extractROIFilter->SetStartX( 10 );
	extractROIFilter->SetStartY( 10 );
	extractROIFilter->SetSizeX( 100 );
	extractROIFilter->SetSizeY( 100 );
	extractROIFilter->SetSizeY( 100 );
        extractROIFilter->SetInput( streaming->GetOutput() );

        WriterType::Pointer writer = WriterType::New();

        writer->SetFileName( outputFilename );
        writer->SetInput( extractROIFilter->GetOutput() );
        writer->Update();

  }
  catch( itk::ExceptionObject & err )
  {
    std::cerr << "Exception OTB attrappee dans exception ITK !" << std::endl;
    std::cerr << err << std::endl;
    return EXIT_FAILURE;
  }
  catch( std::bad_alloc & err )
  {
    std::cout << "Exception bad_alloc : "<<(char*)err.what()<< std::endl;
    return EXIT_FAILURE;
  }
  catch( ... )
  {
    std::cerr << "Exception OTB non attrappee !" << std::endl;
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}

<commit_msg>correction test.<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

//#define MAIN

#include "otbImage.h"
#include "itkVectorImage.h"
#include "itkExceptionObject.h"
#include <iostream>
#include "itkComplexToModulusImageFilter.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbMultiChannelExtractROI.h"

int otbImageFileReaderERS(int argc, char* argv[])
{
  try
  {
        // Verify the number of parameters in the command line
        const char * inputFilename  = argv[1];
        const char * outputFilename = argv[2];

        typedef float  	                        InputPixelType;
        typedef unsigned short                           OutputPixelType;
        const   unsigned int        	        Dimension = 2;

        typedef otb::VectorImage< InputPixelType,  Dimension >        InputImageType;
        typedef otb::VectorImage< OutputPixelType, Dimension >        OutputImageType;

        typedef otb::ImageFileReader< InputImageType  >         ReaderType;
        typedef otb::ImageFileWriter< OutputImageType >         WriterType;

        ReaderType::Pointer complexReader = ReaderType::New();

	complexReader->SetFileName( inputFilename  );

        typedef otb::MultiChannelExtractROI< InputPixelType,
                                             OutputPixelType >  ExtractROIFilterType;

        ExtractROIFilterType::Pointer extractROIFilter = ExtractROIFilterType::New();

	extractROIFilter->SetStartX( 10 );
	extractROIFilter->SetStartY( 10 );
	extractROIFilter->SetSizeX( 100 );
	extractROIFilter->SetSizeY( 100 );
	extractROIFilter->SetSizeY( 100 );
        extractROIFilter->SetInput( complexReader->GetOutput() );

        WriterType::Pointer writer = WriterType::New();

        writer->SetFileName( outputFilename );
        writer->SetInput( extractROIFilter->GetOutput() );
        writer->Update();

  }
  catch( itk::ExceptionObject & err )
  {
    std::cerr << "Exception OTB attrappee dans exception ITK !" << std::endl;
    std::cerr << err << std::endl;
    return EXIT_FAILURE;
  }
  catch( std::bad_alloc & err )
  {
    std::cout << "Exception bad_alloc : "<<(char*)err.what()<< std::endl;
    return EXIT_FAILURE;
  }
  catch( ... )
  {
    std::cerr << "Exception OTB non attrappee !" << std::endl;
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>#pragma once

#include "toast/environment.hpp"
#include "toast/filesystem.hpp"

#include <string>

// The Toast Shared Memory Internals

#define TOAST_PRIVATE_MEMPOOL_SIZE 256

// Private Memory Pool Init/Error Flags
#define PMP_VERIFY  0x7A
#define PMP_VALID   0x7B
#define PMP_LOAD_COMPLETE 0x7C
#define PMP_INVALID 0x80

#define PMP_LOAD_ERR 0x8A
#define PMP_INFO_ERR 0x8B
#define PMP_INIT_ERR 0x8C

#ifdef OS_WIN
    #include <windows.h>
    #include <conio.h>
    #include <tchar.h>

    #define SHM_HANDLE HANDLE
#else
    #include <stdlib.h>
    #include <string.h>
    #include <sys/types.h>
    #include <sys/ipc.h>
    #include <sys/shm.h>
    #include <sys/mman.h>
    #include <fcntl.h>

    #define SHM_HANDLE int
#endif

namespace Toast {
    namespace Internal {
        namespace SHM {
            API SHM_HANDLE create_shm_file(std::string name, int size);
            API SHM_HANDLE open_shm_file(std::string name);
            API char *map_shm_file(SHM_HANDLE handle, int size);
            API void unmap_shm_file(void *addr, int size);
            API void close_shm_file(std::string name, SHM_HANDLE handle);
        }
    }
}<commit_msg>Make the private pool a little bit smaller<commit_after>#pragma once

#include "toast/environment.hpp"
#include "toast/filesystem.hpp"

#include <string>

// The Toast Shared Memory Internals

#define TOAST_PRIVATE_MEMPOOL_SIZE 128

// Private Memory Pool Init/Error Flags
#define PMP_VERIFY  0x7A
#define PMP_VALID   0x7B
#define PMP_LOAD_COMPLETE 0x7C
#define PMP_INVALID 0x80

#define PMP_LOAD_ERR 0x8A
#define PMP_INFO_ERR 0x8B
#define PMP_INIT_ERR 0x8C

#ifdef OS_WIN
    #include <windows.h>
    #include <conio.h>
    #include <tchar.h>

    #define SHM_HANDLE HANDLE
#else
    #include <stdlib.h>
    #include <string.h>
    #include <sys/types.h>
    #include <sys/ipc.h>
    #include <sys/shm.h>
    #include <sys/mman.h>
    #include <fcntl.h>

    #define SHM_HANDLE int
#endif

namespace Toast {
    namespace Internal {
        namespace SHM {
            API SHM_HANDLE create_shm_file(std::string name, int size);
            API SHM_HANDLE open_shm_file(std::string name);
            API char *map_shm_file(SHM_HANDLE handle, int size);
            API void unmap_shm_file(void *addr, int size);
            API void close_shm_file(std::string name, SHM_HANDLE handle);
        }
    }
}<|endoftext|>


<commit_before>/**
 *  For conditions of distribution and use, see copyright notice in license.txt
 *
 *  @file   VoiceToolWidget.cpp
 *  @brief  Widget for voice communication control
 *
 */

#include "StableHeaders.h"
#include "DebugOperatorNew.h"

#include "VoiceToolWidget.h"
#include "CommunicationsService.h"
#include "VoiceStateWidget.h"
#include "UiServiceInterface.h"
#include "Input.h"
#include "UiProxyWidget.h"
#include "VoiceControllerWidget.h"
#include "VoiceUsersInfoWidget.h"
#include "VoiceTransmissionModeWidget.h"
#include "VoiceController.h"
#include <QSettings>
#include <QComboBox>

#include "DebugOperatorNew.h"

namespace CommUI
{
    VoiceToolWidget::VoiceToolWidget(Foundation::Framework* framework) :
        framework_(framework),
        voice_users_info_widget_(0),
        in_world_voice_session_(0),
        voice_state_widget_(0),
        voice_controller_widget_(0),
        voice_controller_proxy_widget_(0),
        channel_selection_(0),
        transmission_mode_widget_(0),
        voice_controller_(0)
    {
        setupUi(this);
        InitializeInWorldVoice();
    }

    VoiceToolWidget::~VoiceToolWidget()
    {
        UninitializeInWorldVoice();
    }

    void VoiceToolWidget::InitializeInWorldVoice()
    {
        if (framework_ &&  framework_->GetServiceManager())
        {
            Communications::ServiceInterface *communication_service = framework_->GetService<Communications::ServiceInterface>();
            if (communication_service)
                ConnectInWorldVoiceSession( communication_service->InWorldVoiceSession() );
        }
    }

    void VoiceToolWidget::ConnectInWorldVoiceSession(Communications::InWorldVoice::SessionInterface* session)
    {
        in_world_voice_session_ = session;
        if (!session)
            return;

        QObject::connect(in_world_voice_session_, SIGNAL(StartSendingAudio()), this, SLOT(UpdateInWorldVoiceIndicator()) );
        QObject::connect(in_world_voice_session_, SIGNAL(StopSendingAudio()), this, SLOT(UpdateInWorldVoiceIndicator()) );
        QObject::connect(in_world_voice_session_, SIGNAL(StateChanged(Communications::InWorldVoice::SessionInterface::State)), this, SLOT(UpdateInWorldVoiceIndicator()));
        QObject::connect(in_world_voice_session_, SIGNAL(ParticipantJoined(Communications::InWorldVoice::ParticipantInterface*)), this, SLOT(UpdateInWorldVoiceIndicator()) );
        QObject::connect(in_world_voice_session_, SIGNAL(ParticipantJoined(Communications::InWorldVoice::ParticipantInterface*)), this, SLOT(ConnectParticipantVoiceAvticitySignals(Communications::InWorldVoice::ParticipantInterface*)) );
        QObject::connect(in_world_voice_session_, SIGNAL(ParticipantLeft(Communications::InWorldVoice::ParticipantInterface*)), this, SLOT(UpdateInWorldVoiceIndicator()) );
        QObject::connect(in_world_voice_session_, SIGNAL(destroyed()), this, SLOT(UninitializeInWorldVoice()));
        QObject::connect(in_world_voice_session_, SIGNAL(SpeakerVoiceActivityChanged(double)), this, SLOT(UpdateInWorldVoiceIndicator()));
        QObject::connect(in_world_voice_session_, SIGNAL(ActiceChannelChanged(QString)), this, SLOT(UpdateUI()));
        QObject::connect(in_world_voice_session_, SIGNAL(ChannelListChanged(QStringList)), this, SLOT(UpdateUI()));
    }

    void VoiceToolWidget::Minimize()
    {

    }

    void VoiceToolWidget::Maximize()
    {

    }

    void VoiceToolWidget::UpdateInWorldVoiceIndicator()
    {
        if (!in_world_voice_session_)
            return;

        if (in_world_voice_session_->GetState() != Communications::InWorldVoice::SessionInterface::STATE_OPEN)
        {
            voice_users_info_widget_->hide();
            voice_state_widget_->hide();
            if (voice_controller_proxy_widget_)
                voice_controller_proxy_widget_->hide();
            return;
        }
        else
        {
            voice_users_info_widget_->show();
            voice_state_widget_->show();
        }

        if (in_world_voice_session_->IsAudioSendingEnabled())
        {
            if (voice_state_widget_)
            {
                voice_state_widget_->setState(CommUI::VoiceStateWidget::STATE_ONLINE);
                voice_state_widget_->SetVoiceActivity(in_world_voice_session_->SpeakerVoiceActivity());
            }
        }
        else
        {
            if (voice_state_widget_)
                voice_state_widget_->setState(CommUI::VoiceStateWidget::STATE_OFFLINE);
        }

        if (voice_users_info_widget_)
        {
            double channel_voice_activity = 0;
            QList<Communications::InWorldVoice::ParticipantInterface*> list = in_world_voice_session_->Participants();
            foreach(Communications::InWorldVoice::ParticipantInterface* p, list)
            {
                if (p->IsSpeaking())
                {
                    channel_voice_activity = 1;
                    break;
                }
            }
            voice_users_info_widget_->SetVoiceActivity(channel_voice_activity);
            voice_users_info_widget_->SetUsersCount(in_world_voice_session_->Participants().count());
        }
    }

    void VoiceToolWidget::ConnectParticipantVoiceAvticitySignals(Communications::InWorldVoice::ParticipantInterface* p)
    {
        connect(p, SIGNAL(StartSpeaking()), this, SLOT(UpdateInWorldVoiceIndicator()));
        connect(p, SIGNAL(StopSpeaking()), this, SLOT(UpdateInWorldVoiceIndicator()));
    }

    void VoiceToolWidget::UninitializeInWorldVoice()
    {
        if (voice_controller_proxy_widget_)
            framework_->UiService()->RemoveWidgetFromScene(voice_controller_proxy_widget_);
        if (voice_controller_widget_)
            SAFE_DELETE(voice_controller_widget_);

        if (voice_controller_)
            SAFE_DELETE(voice_controller_);
        in_world_voice_session_ = 0;
    }

    void VoiceToolWidget::ToggleVoiceControlWidget()
    {
        if (!in_world_voice_session_ || !voice_controller_proxy_widget_)
            return;

        if (voice_controller_proxy_widget_->isVisible())
            voice_controller_proxy_widget_->AnimatedHide();
        else
        {
            voice_controller_proxy_widget_->show();
            /// @todo fixme HACK BEGIN
            voice_controller_proxy_widget_->moveBy(1,1);
            voice_controller_proxy_widget_->moveBy(-1,-1);
            /// HACK END
        }
    }

    void VoiceToolWidget::UpdateUI()
    {
        QString channel = in_world_voice_session_->GetActiveChannel();

        if (!voice_controller_)
        {
            voice_controller_ = new VoiceController(in_world_voice_session_);
            /// @todo Use Settings class from MumbeVoipModule
            QSettings settings(QSettings::IniFormat, QSettings::UserScope, APPLICATION_NAME, "configuration/MumbleVoip");
            switch(settings.value("MumbleVoice/default_voice_mode").toInt())
            {
            case 0:
                voice_controller_->SetTransmissionMode(VoiceController::Mute);
                break;
            case 1:
                voice_controller_->SetTransmissionMode(VoiceController::ContinuousTransmission);
                break;
            case 2:
                voice_controller_->SetTransmissionMode(VoiceController::PushToTalk);
                break;
            case 3:
                voice_controller_->SetTransmissionMode(VoiceController::ToggleMode);
                break;
            }
        }

        if (!voice_state_widget_)
        {
            voice_state_widget_ = new VoiceStateWidget();
            connect(voice_state_widget_, SIGNAL( clicked() ), SLOT(ToggleTransmissionModeWidget() ) );
            this->layout()->addWidget(voice_state_widget_);
            voice_state_widget_->show();
        }

        if (!voice_users_info_widget_)
        {
            voice_users_info_widget_ = new CommUI::VoiceUsersInfoWidget(0);
            connect(voice_users_info_widget_, SIGNAL( clicked() ), SLOT(ToggleVoiceControlWidget() ) );
            this->layout()->addWidget(voice_users_info_widget_);
        }
        voice_users_info_widget_->show();
        voice_users_info_widget_->updateGeometry();

        if (!channel_selection_)
        {
            channel_selection_ = new QComboBox();
            this->layout()->addWidget(channel_selection_);
        }

        disconnect(channel_selection_, SIGNAL(currentIndexChanged(const QString&)), in_world_voice_session_, SLOT(SetActiveChannel(QString)));
        channel_selection_->clear();
        channel_selection_->addItems(in_world_voice_session_->GetChannels());
        channel_selection_->addItems( QStringList() << ""); // no active channel
        channel_selection_->setCurrentIndex(channel_selection_->findText(in_world_voice_session_->GetActiveChannel()));
        channel_selection_->updateGeometry();
        connect(channel_selection_, SIGNAL(currentIndexChanged(const QString&)), in_world_voice_session_, SLOT(SetActiveChannel(QString)));
        this->update();

        if (voice_controller_widget_)
        {
            SAFE_DELETE(voice_controller_widget_);
            voice_controller_proxy_widget_ = 0; // automatically deleted by framework
        }
        if (in_world_voice_session_->GetState() == Communications::InWorldVoice::SessionInterface::STATE_OPEN)
        {
            voice_controller_widget_ = new VoiceControllerWidget(in_world_voice_session_);
            voice_controller_proxy_widget_ = framework_->UiService()->AddWidgetToScene(voice_controller_widget_);
            voice_controller_proxy_widget_->setWindowTitle("In-world voice");
            voice_controller_proxy_widget_->hide();
            /// @todo fixme HACK BEGIN
            voice_controller_proxy_widget_->moveBy(1,1);
            voice_controller_proxy_widget_->moveBy(-1,-1);
            /// HACK END

            /// @todo Make these configurable
            input_context_ = framework_->GetInput()->RegisterInputContext("CommunicationWidget", 90);
            connect(input_context_.get(), SIGNAL(MouseMiddlePressed(MouseEvent*)), voice_controller_, SLOT(SetPushToTalkOn()));
            connect(input_context_.get(), SIGNAL(MouseMiddleReleased(MouseEvent*)),voice_controller_, SLOT(SetPushToTalkOff()));
            connect(input_context_.get(), SIGNAL(MouseMiddlePressed(MouseEvent*)), voice_controller_, SLOT(Toggle()));
        }
        UpdateInWorldVoiceIndicator();
    }

    void VoiceToolWidget::ToggleTransmissionModeWidget()
    {
        if (!transmission_mode_widget_)
        {
            /// @todo Use Settings class from MumbeVoipModule
            QSettings settings(QSettings::IniFormat, QSettings::UserScope, APPLICATION_NAME, "configuration/MumbleVoip");
            int default_voice_mode = settings.value("MumbleVoice/default_voice_mode").toInt();

            transmission_mode_widget_ = new VoiceTransmissionModeWidget(default_voice_mode);
            connect(transmission_mode_widget_, SIGNAL(TransmissionModeSelected(int)), this, SLOT(ChangeTransmissionMode(int)));

            UiProxyWidget* proxy = framework_->UiService()->AddWidgetToScene(transmission_mode_widget_, Qt::Widget);
            connect(proxy->scene(), SIGNAL(sceneRectChanged(const QRectF)), this, SLOT(UpdateTransmissionModeWidgetPosition()));
            UpdateTransmissionModeWidgetPosition();
            transmission_mode_widget_->show();
        }
        else
        {
            if (transmission_mode_widget_->isVisible())
                transmission_mode_widget_->hide();
            else
            {
                transmission_mode_widget_->show();
            }
        }
    }

    void VoiceToolWidget::UpdateTransmissionModeWidgetPosition()
    {
        QPoint absolute_pos;
        QWidget* p = parentWidget();
        while (p)
        {
            absolute_pos += p->pos();
            p = p->parentWidget();
        }
        absolute_pos.setY(absolute_pos.y() - transmission_mode_widget_->height());
        transmission_mode_widget_->move(absolute_pos);
    }

    void VoiceToolWidget::ChangeTransmissionMode(int mode)
    {
        voice_controller_->SetTransmissionMode(static_cast<VoiceController::TransmissionMode>(mode));
    }

} // CommUI
<commit_msg>Trying to fix rest of the linux build problems.<commit_after>/**
 *  For conditions of distribution and use, see copyright notice in license.txt
 *
 *  @file   VoiceToolWidget.cpp
 *  @brief  Widget for voice communication control
 *
 */

#include "StableHeaders.h"
#include "DebugOperatorNew.h"

#include "VoiceToolWidget.h"
#include "CommunicationsService.h"
#include "VoiceStateWidget.h"
#include "UiServiceInterface.h"
#include "Input.h"
#include "UiProxyWidget.h"
#include "VoiceControllerWidget.h"
#include "VoiceUsersInfoWidget.h"
#include "VoiceTransmissionModeWidget.h"
#include "VoiceController.h"
#include <QSettings>
#include <QComboBox>
#include <QGraphicsScene>

#include "DebugOperatorNew.h"

namespace CommUI
{
    VoiceToolWidget::VoiceToolWidget(Foundation::Framework* framework) :
        framework_(framework),
        voice_users_info_widget_(0),
        in_world_voice_session_(0),
        voice_state_widget_(0),
        voice_controller_widget_(0),
        voice_controller_proxy_widget_(0),
        channel_selection_(0),
        transmission_mode_widget_(0),
        voice_controller_(0)
    {
        setupUi(this);
        InitializeInWorldVoice();
    }

    VoiceToolWidget::~VoiceToolWidget()
    {
        UninitializeInWorldVoice();
    }

    void VoiceToolWidget::InitializeInWorldVoice()
    {
        if (framework_ &&  framework_->GetServiceManager())
        {
            Communications::ServiceInterface *communication_service = framework_->GetService<Communications::ServiceInterface>();
            if (communication_service)
                ConnectInWorldVoiceSession( communication_service->InWorldVoiceSession() );
        }
    }

    void VoiceToolWidget::ConnectInWorldVoiceSession(Communications::InWorldVoice::SessionInterface* session)
    {
        in_world_voice_session_ = session;
        if (!session)
            return;

        QObject::connect(in_world_voice_session_, SIGNAL(StartSendingAudio()), this, SLOT(UpdateInWorldVoiceIndicator()) );
        QObject::connect(in_world_voice_session_, SIGNAL(StopSendingAudio()), this, SLOT(UpdateInWorldVoiceIndicator()) );
        QObject::connect(in_world_voice_session_, SIGNAL(StateChanged(Communications::InWorldVoice::SessionInterface::State)), this, SLOT(UpdateInWorldVoiceIndicator()));
        QObject::connect(in_world_voice_session_, SIGNAL(ParticipantJoined(Communications::InWorldVoice::ParticipantInterface*)), this, SLOT(UpdateInWorldVoiceIndicator()) );
        QObject::connect(in_world_voice_session_, SIGNAL(ParticipantJoined(Communications::InWorldVoice::ParticipantInterface*)), this, SLOT(ConnectParticipantVoiceAvticitySignals(Communications::InWorldVoice::ParticipantInterface*)) );
        QObject::connect(in_world_voice_session_, SIGNAL(ParticipantLeft(Communications::InWorldVoice::ParticipantInterface*)), this, SLOT(UpdateInWorldVoiceIndicator()) );
        QObject::connect(in_world_voice_session_, SIGNAL(destroyed()), this, SLOT(UninitializeInWorldVoice()));
        QObject::connect(in_world_voice_session_, SIGNAL(SpeakerVoiceActivityChanged(double)), this, SLOT(UpdateInWorldVoiceIndicator()));
        QObject::connect(in_world_voice_session_, SIGNAL(ActiceChannelChanged(QString)), this, SLOT(UpdateUI()));
        QObject::connect(in_world_voice_session_, SIGNAL(ChannelListChanged(QStringList)), this, SLOT(UpdateUI()));
    }

    void VoiceToolWidget::Minimize()
    {

    }

    void VoiceToolWidget::Maximize()
    {

    }

    void VoiceToolWidget::UpdateInWorldVoiceIndicator()
    {
        if (!in_world_voice_session_)
            return;

        if (in_world_voice_session_->GetState() != Communications::InWorldVoice::SessionInterface::STATE_OPEN)
        {
            voice_users_info_widget_->hide();
            voice_state_widget_->hide();
            if (voice_controller_proxy_widget_)
                voice_controller_proxy_widget_->hide();
            return;
        }
        else
        {
            voice_users_info_widget_->show();
            voice_state_widget_->show();
        }

        if (in_world_voice_session_->IsAudioSendingEnabled())
        {
            if (voice_state_widget_)
            {
                voice_state_widget_->setState(CommUI::VoiceStateWidget::STATE_ONLINE);
                voice_state_widget_->SetVoiceActivity(in_world_voice_session_->SpeakerVoiceActivity());
            }
        }
        else
        {
            if (voice_state_widget_)
                voice_state_widget_->setState(CommUI::VoiceStateWidget::STATE_OFFLINE);
        }

        if (voice_users_info_widget_)
        {
            double channel_voice_activity = 0;
            QList<Communications::InWorldVoice::ParticipantInterface*> list = in_world_voice_session_->Participants();
            foreach(Communications::InWorldVoice::ParticipantInterface* p, list)
            {
                if (p->IsSpeaking())
                {
                    channel_voice_activity = 1;
                    break;
                }
            }
            voice_users_info_widget_->SetVoiceActivity(channel_voice_activity);
            voice_users_info_widget_->SetUsersCount(in_world_voice_session_->Participants().count());
        }
    }

    void VoiceToolWidget::ConnectParticipantVoiceAvticitySignals(Communications::InWorldVoice::ParticipantInterface* p)
    {
        connect(p, SIGNAL(StartSpeaking()), this, SLOT(UpdateInWorldVoiceIndicator()));
        connect(p, SIGNAL(StopSpeaking()), this, SLOT(UpdateInWorldVoiceIndicator()));
    }

    void VoiceToolWidget::UninitializeInWorldVoice()
    {
        if (voice_controller_proxy_widget_)
            framework_->UiService()->RemoveWidgetFromScene(voice_controller_proxy_widget_);
        if (voice_controller_widget_)
            SAFE_DELETE(voice_controller_widget_);

        if (voice_controller_)
            SAFE_DELETE(voice_controller_);
        in_world_voice_session_ = 0;
    }

    void VoiceToolWidget::ToggleVoiceControlWidget()
    {
        if (!in_world_voice_session_ || !voice_controller_proxy_widget_)
            return;

        if (voice_controller_proxy_widget_->isVisible())
            voice_controller_proxy_widget_->AnimatedHide();
        else
        {
            voice_controller_proxy_widget_->show();
            /// @todo fixme HACK BEGIN
            voice_controller_proxy_widget_->moveBy(1,1);
            voice_controller_proxy_widget_->moveBy(-1,-1);
            /// HACK END
        }
    }

    void VoiceToolWidget::UpdateUI()
    {
        QString channel = in_world_voice_session_->GetActiveChannel();

        if (!voice_controller_)
        {
            voice_controller_ = new VoiceController(in_world_voice_session_);
            /// @todo Use Settings class from MumbeVoipModule
            QSettings settings(QSettings::IniFormat, QSettings::UserScope, APPLICATION_NAME, "configuration/MumbleVoip");
            switch(settings.value("MumbleVoice/default_voice_mode").toInt())
            {
            case 0:
                voice_controller_->SetTransmissionMode(VoiceController::Mute);
                break;
            case 1:
                voice_controller_->SetTransmissionMode(VoiceController::ContinuousTransmission);
                break;
            case 2:
                voice_controller_->SetTransmissionMode(VoiceController::PushToTalk);
                break;
            case 3:
                voice_controller_->SetTransmissionMode(VoiceController::ToggleMode);
                break;
            }
        }

        if (!voice_state_widget_)
        {
            voice_state_widget_ = new VoiceStateWidget();
            connect(voice_state_widget_, SIGNAL( clicked() ), SLOT(ToggleTransmissionModeWidget() ) );
            this->layout()->addWidget(voice_state_widget_);
            voice_state_widget_->show();
        }

        if (!voice_users_info_widget_)
        {
            voice_users_info_widget_ = new CommUI::VoiceUsersInfoWidget(0);
            connect(voice_users_info_widget_, SIGNAL( clicked() ), SLOT(ToggleVoiceControlWidget() ) );
            this->layout()->addWidget(voice_users_info_widget_);
        }
        voice_users_info_widget_->show();
        voice_users_info_widget_->updateGeometry();

        if (!channel_selection_)
        {
            channel_selection_ = new QComboBox();
            this->layout()->addWidget(channel_selection_);
        }

        disconnect(channel_selection_, SIGNAL(currentIndexChanged(const QString&)), in_world_voice_session_, SLOT(SetActiveChannel(QString)));
        channel_selection_->clear();
        channel_selection_->addItems(in_world_voice_session_->GetChannels());
        channel_selection_->addItems( QStringList() << ""); // no active channel
        channel_selection_->setCurrentIndex(channel_selection_->findText(in_world_voice_session_->GetActiveChannel()));
        channel_selection_->updateGeometry();
        connect(channel_selection_, SIGNAL(currentIndexChanged(const QString&)), in_world_voice_session_, SLOT(SetActiveChannel(QString)));
        this->update();

        if (voice_controller_widget_)
        {
            SAFE_DELETE(voice_controller_widget_);
            voice_controller_proxy_widget_ = 0; // automatically deleted by framework
        }
        if (in_world_voice_session_->GetState() == Communications::InWorldVoice::SessionInterface::STATE_OPEN)
        {
            voice_controller_widget_ = new VoiceControllerWidget(in_world_voice_session_);
            voice_controller_proxy_widget_ = framework_->UiService()->AddWidgetToScene(voice_controller_widget_);
            voice_controller_proxy_widget_->setWindowTitle("In-world voice");
            voice_controller_proxy_widget_->hide();
            /// @todo fixme HACK BEGIN
            voice_controller_proxy_widget_->moveBy(1,1);
            voice_controller_proxy_widget_->moveBy(-1,-1);
            /// HACK END

            /// @todo Make these configurable
            input_context_ = framework_->GetInput()->RegisterInputContext("CommunicationWidget", 90);
            connect(input_context_.get(), SIGNAL(MouseMiddlePressed(MouseEvent*)), voice_controller_, SLOT(SetPushToTalkOn()));
            connect(input_context_.get(), SIGNAL(MouseMiddleReleased(MouseEvent*)),voice_controller_, SLOT(SetPushToTalkOff()));
            connect(input_context_.get(), SIGNAL(MouseMiddlePressed(MouseEvent*)), voice_controller_, SLOT(Toggle()));
        }
        UpdateInWorldVoiceIndicator();
    }

    void VoiceToolWidget::ToggleTransmissionModeWidget()
    {
        if (!transmission_mode_widget_)
        {
            /// @todo Use Settings class from MumbeVoipModule
            QSettings settings(QSettings::IniFormat, QSettings::UserScope, APPLICATION_NAME, "configuration/MumbleVoip");
            int default_voice_mode = settings.value("MumbleVoice/default_voice_mode").toInt();

            transmission_mode_widget_ = new VoiceTransmissionModeWidget(default_voice_mode);
            connect(transmission_mode_widget_, SIGNAL(TransmissionModeSelected(int)), this, SLOT(ChangeTransmissionMode(int)));

            UiProxyWidget* proxy = framework_->UiService()->AddWidgetToScene(transmission_mode_widget_, Qt::Widget);
            QObject::connect(proxy->scene(), SIGNAL(sceneRectChanged(const QRectF)), this, SLOT(UpdateTransmissionModeWidgetPosition()));
            UpdateTransmissionModeWidgetPosition();
            transmission_mode_widget_->show();
        }
        else
        {
            if (transmission_mode_widget_->isVisible())
                transmission_mode_widget_->hide();
            else
            {
                transmission_mode_widget_->show();
            }
        }
    }

    void VoiceToolWidget::UpdateTransmissionModeWidgetPosition()
    {
        QPoint absolute_pos;
        QWidget* p = parentWidget();
        while (p)
        {
            absolute_pos += p->pos();
            p = p->parentWidget();
        }
        absolute_pos.setY(absolute_pos.y() - transmission_mode_widget_->height());
        transmission_mode_widget_->move(absolute_pos);
    }

    void VoiceToolWidget::ChangeTransmissionMode(int mode)
    {
        voice_controller_->SetTransmissionMode(static_cast<VoiceController::TransmissionMode>(mode));
    }

} // CommUI
<|endoftext|>


<commit_before>#include "Arduino.h"
#include <EBot.h>

#ifdef WOKE
IRrecv irrecv(receiverpin);
decode_results results;
#endif

EBot::EBot() {
}

EBot::~EBot() {
}

void EBot::begin() {
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);
  pinMode(ENA, OUTPUT);
  pinMode(ENB, OUTPUT);
  pinMode(Echo, INPUT);
  pinMode(Trig, OUTPUT);
  servo.attach(ServoPin);
  servo.write(90);
  this->setDirection();
  this->setSpeed();
  #ifdef WOKE
  irrecv.enableIRIn();
  #endif
}

void EBot::setDirection(EBot::direction move) {
  switch(move) {
    case STOP:
    this->stop();
    break;
    case FORWARD:
    this->forward(this->speed);
    break;
    case BACKWARD:
    this->backward(this->speed);
    break;
    case TURNLEFT:
    this->turnLeft(this->speed);
    break;
    case TURNRIGHT:
    this->turnRight(this->speed);
    break;
    case ROTATELEFT:
    this->rotateLeft(this->speed);
    break;
    case ROTATERIGHT:
    this->rotateRight(this->speed);
    break;
    case LEFTWHEELSTOP:
    this->leftWheelStop();
    break;
    case RIGHTWHEELSTOP:
    this->rightWheelStop();
    break;
    case LEFTWHEELFORWARD:
    this->leftWheelForward(this->speed);
    break;
    case RIGHTWHEELFORWARD:
    this->rightWheelForward(this->speed);
    break;
    case LEFTWHEELBACKWARD:
    this->leftWheelBackward(this->speed);
    break;
    case RIGHTWHEELBACKWARD:
    this->rightWheelBackward(this->speed);
    break;
  }
}

void EBot::setSpeed(int speed) {
  this->speed = speed;
}

void EBot::stop() {
  leftWheelStop();
  rightWheelStop();
}

void EBot::forward(int speed) {
  leftWheelForward(speed);
  rightWheelForward(speed);
}

void EBot::backward(int speed) {
  leftWheelBackward(speed);
  rightWheelBackward(speed);
}

void EBot::turnLeft(int speed) {
  leftWheelStop();
  rightWheelForward(speed);
}

void EBot::turnRight(int speed) {
  leftWheelForward(speed);
  rightWheelStop();
}

void EBot::rotateLeft(int speed) {
  leftWheelBackward(speed);
  rightWheelForward(speed);
}

void EBot::rotateRight(int speed) {
  leftWheelForward(speed);
  rightWheelBackward(speed);
}

void EBot::leftWheelStop() {
  digitalWrite(ENB, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, LOW);
}

void EBot::rightWheelStop() {
  digitalWrite(ENA, LOW);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, LOW);
}

void EBot::leftWheelForward(int speed) {
  speed = boundaries(speed, 0, 255);

  analogWrite(ENB, speed);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
}

void EBot::rightWheelForward(int speed) {
  speed = boundaries(speed, 0, 255);

  analogWrite(ENA, speed);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
}

void EBot::leftWheelBackward(int speed) {
  speed = boundaries(speed, 0, 255);

  analogWrite(ENB, speed);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
}

void EBot::rightWheelBackward(int speed) {
  speed = boundaries(speed, 0, 255);

  analogWrite(ENA, speed);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
}

void EBot::setAngle(int angle) {
  angle = boundaries(angle, 0, 179);

  this->servo.write(angle);
}

unsigned long EBot::getDistance() {
  unsigned long duration;

  digitalWrite(Trig, LOW);
  delayMicroseconds(2);
  digitalWrite(Trig, HIGH);
  delayMicroseconds(5);
  digitalWrite(Trig, LOW);
  duration = pulseIn(Echo, HIGH);

  return duration / 29 / 2;
}

unsigned long EBot::getIR() {
  unsigned long value = 0;
  #ifdef WOKE
  if (irrecv.decode(&results)) {
    value = results.value;
    irrecv.resume(); // Receive the next value
  }
  #endif
  return value;
}

bool EBot::readLS1() {
  return digitalRead(LS1);
}

bool EBot::readLS2() {
  return digitalRead(LS2);
}

bool EBot::readLS3() {
  return digitalRead(LS3);
}

int EBot::boundaries(int value, int min, int max) {
  value = value < min ? min : value;
  value = value > max ? max : value;

  return value;
}
<commit_msg>replace variable<commit_after>#include "Arduino.h"
#include <EBot.h>

#ifdef IRREMOTE
IRrecv irrecv(receiverpin);
decode_results results;
#endif

EBot::EBot() {
}

EBot::~EBot() {
}

void EBot::begin() {
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);
  pinMode(ENA, OUTPUT);
  pinMode(ENB, OUTPUT);
  pinMode(Echo, INPUT);
  pinMode(Trig, OUTPUT);
  servo.attach(ServoPin);
  servo.write(90);
  this->setDirection();
  this->setSpeed();
  #ifdef IRREMOTE
  irrecv.enableIRIn();
  #endif
}

void EBot::setDirection(EBot::direction move) {
  switch(move) {
    case STOP:
    this->stop();
    break;
    case FORWARD:
    this->forward(this->speed);
    break;
    case BACKWARD:
    this->backward(this->speed);
    break;
    case TURNLEFT:
    this->turnLeft(this->speed);
    break;
    case TURNRIGHT:
    this->turnRight(this->speed);
    break;
    case ROTATELEFT:
    this->rotateLeft(this->speed);
    break;
    case ROTATERIGHT:
    this->rotateRight(this->speed);
    break;
    case LEFTWHEELSTOP:
    this->leftWheelStop();
    break;
    case RIGHTWHEELSTOP:
    this->rightWheelStop();
    break;
    case LEFTWHEELFORWARD:
    this->leftWheelForward(this->speed);
    break;
    case RIGHTWHEELFORWARD:
    this->rightWheelForward(this->speed);
    break;
    case LEFTWHEELBACKWARD:
    this->leftWheelBackward(this->speed);
    break;
    case RIGHTWHEELBACKWARD:
    this->rightWheelBackward(this->speed);
    break;
  }
}

void EBot::setSpeed(int speed) {
  this->speed = speed;
}

void EBot::stop() {
  leftWheelStop();
  rightWheelStop();
}

void EBot::forward(int speed) {
  leftWheelForward(speed);
  rightWheelForward(speed);
}

void EBot::backward(int speed) {
  leftWheelBackward(speed);
  rightWheelBackward(speed);
}

void EBot::turnLeft(int speed) {
  leftWheelStop();
  rightWheelForward(speed);
}

void EBot::turnRight(int speed) {
  leftWheelForward(speed);
  rightWheelStop();
}

void EBot::rotateLeft(int speed) {
  leftWheelBackward(speed);
  rightWheelForward(speed);
}

void EBot::rotateRight(int speed) {
  leftWheelForward(speed);
  rightWheelBackward(speed);
}

void EBot::leftWheelStop() {
  digitalWrite(ENB, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, LOW);
}

void EBot::rightWheelStop() {
  digitalWrite(ENA, LOW);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, LOW);
}

void EBot::leftWheelForward(int speed) {
  speed = boundaries(speed, 0, 255);

  analogWrite(ENB, speed);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
}

void EBot::rightWheelForward(int speed) {
  speed = boundaries(speed, 0, 255);

  analogWrite(ENA, speed);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
}

void EBot::leftWheelBackward(int speed) {
  speed = boundaries(speed, 0, 255);

  analogWrite(ENB, speed);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
}

void EBot::rightWheelBackward(int speed) {
  speed = boundaries(speed, 0, 255);

  analogWrite(ENA, speed);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
}

void EBot::setAngle(int angle) {
  angle = boundaries(angle, 0, 179);

  this->servo.write(angle);
}

unsigned long EBot::getDistance() {
  unsigned long duration;

  digitalWrite(Trig, LOW);
  delayMicroseconds(2);
  digitalWrite(Trig, HIGH);
  delayMicroseconds(5);
  digitalWrite(Trig, LOW);
  duration = pulseIn(Echo, HIGH);

  return duration / 29 / 2;
}

unsigned long EBot::getIR() {
  unsigned long value = 0;
  #ifdef IRREMOTE
  if (irrecv.decode(&results)) {
    value = results.value;
    irrecv.resume(); // Receive the next value
  }
  #endif
  return value;
}

bool EBot::readLS1() {
  return digitalRead(LS1);
}

bool EBot::readLS2() {
  return digitalRead(LS2);
}

bool EBot::readLS3() {
  return digitalRead(LS3);
}

int EBot::boundaries(int value, int min, int max) {
  value = value < min ? min : value;
  value = value > max ? max : value;

  return value;
}
<|endoftext|>


<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.

#include <visionaray/math/forward.h>
#include <visionaray/array.h>
#include <visionaray/material.h>
#include <visionaray/get_surface.h>

using namespace visionaray;

// Material type to check
template <typename T>
using mat_type = matte<T>;

#if defined WITHOUT_TEX_COLOR
    template <typename N, typename M, int SIZE>
    using param_type = array<surface<N, M>, SIZE>;
    template <typename N, typename M>
    using result_type = surface<N, M>;
#elif defined WITH_TEX_COLOR
    template <typename N, typename M, int SIZE>
    using param_type = array<surface<N, M, vec3f>, SIZE>;
    template <typename N, typename M>
    using result_type = surface<N, M, N>;
#endif

int main()
{

#if defined SURFACE_PACK_FLOAT4

    param_type<vec3f, mat_type<float>, 4> surf_array;
    result_type<vector<3, simd::float4>, mat_type<simd::float4>> surf = simd::pack(surf_array);

#elif defined SURFACE_PACK_FLOAT8

#if VSNRAY_SIMD_ISA_GE(VSNRAY_SIMD_ISA_AVX)
    param_type<vec3f, mat_type<float>, 8> surf_array;
    result_type<vector<3, simd::float8>, mat_type<simd::float8>> surf = simd::pack(surf_array);
#endif

#elif defined SURFACE_PACK_ILLEGAL_LENGTH_1

    param_type<vec3f, mat_type<float>, 1> surf_array;
    auto surf = simd::pack(surf_array);

#elif defined SURFACE_PACK_ILLEGAL_LENGTH_3

    param_type<vec3f, mat_type<float>, 3> surf_array;
    auto surf = simd::pack(surf_array);

#elif defined SURFACE_PACK_ILLEGAL_INTEGRAL_1

    param_type<vec3f, mat_type<int>, 4> surf_array;
    auto surf = simd::pack(surf_array);

#elif defined SURFACE_PACK_ILLEGAL_INTEGRAL_2

    param_type<vec3i, mat_type<float>, 4> surf_array;
    auto surf = simd::pack(surf_array);

#endif

    return 0;
}
<commit_msg>Adapt to changed surface interface<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.

#include <visionaray/math/forward.h>
#include <visionaray/array.h>
#include <visionaray/material.h>
#include <visionaray/get_surface.h>

using namespace visionaray;

// Material type to check
template <typename T>
using mat_type = matte<T>;

#if defined WITHOUT_TEX_COLOR
    template <typename N, typename M, int SIZE>
    using param_type = array<surface<N, M>, SIZE>;
    template <typename N, typename M>
    using result_type = surface<N, M>;
#elif defined WITH_TEX_COLOR
    template <typename N, typename M, int SIZE>
    using param_type = array<surface<N, vec3f, M>, SIZE>;
    template <typename N, typename M>
    using result_type = surface<N, N/*TODO: in general TexCol != N*/, M>;
#endif

int main()
{

#if defined SURFACE_PACK_FLOAT4

    param_type<vec3f, mat_type<float>, 4> surf_array;
    result_type<vector<3, simd::float4>, mat_type<simd::float4>> surf = simd::pack(surf_array);

#elif defined SURFACE_PACK_FLOAT8

#if VSNRAY_SIMD_ISA_GE(VSNRAY_SIMD_ISA_AVX)
    param_type<vec3f, mat_type<float>, 8> surf_array;
    result_type<vector<3, simd::float8>, mat_type<simd::float8>> surf = simd::pack(surf_array);
#endif

#elif defined SURFACE_PACK_ILLEGAL_LENGTH_1

    param_type<vec3f, mat_type<float>, 1> surf_array;
    auto surf = simd::pack(surf_array);

#elif defined SURFACE_PACK_ILLEGAL_LENGTH_3

    param_type<vec3f, mat_type<float>, 3> surf_array;
    auto surf = simd::pack(surf_array);

#elif defined SURFACE_PACK_ILLEGAL_INTEGRAL_1

    param_type<vec3f, mat_type<int>, 4> surf_array;
    auto surf = simd::pack(surf_array);

#elif defined SURFACE_PACK_ILLEGAL_INTEGRAL_2

    param_type<vec3i, mat_type<float>, 4> surf_array;
    auto surf = simd::pack(surf_array);

#endif

    return 0;
}
<|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2011, Alexandru-Eugen Ichim
 *                      Willow Garage, Inc
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of 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.
 *
 * $Id$
 */

#ifndef PCL_KEYPOINTS_IMPL_SMOOTHEDSURFACESKEYPOINT_H_
#define PCL_KEYPOINTS_IMPL_SMOOTHEDSURFACESKEYPOINT_H_

#include "pcl/keypoints/smoothed_surfaces_keypoint.h"
#include <pcl/kdtree/kdtree_flann.h>

//#include <pcl/io/pcd_io.h>

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> void
pcl::SmoothedSurfacesKeypoint<PointT, PointNT>::addSmoothedPointCloud (const PointCloudTConstPtr &cloud,
                                                                       const PointCloudNTConstPtr &normals,
                                                                       KdTreePtr &kdtree,
                                                                       float &scale)
{
  clouds_.push_back (cloud);
  cloud_normals_.push_back (normals);
  cloud_trees_.push_back (kdtree);
  scales_.push_back (std::pair<float, size_t> (scale, scales_.size ()));
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> void
pcl::SmoothedSurfacesKeypoint<PointT, PointNT>::resetClouds ()
{
  clouds_.clear ();
  cloud_normals_.clear ();
  scales_.clear ();
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> void
pcl::SmoothedSurfacesKeypoint<PointT, PointNT>::detectKeypoints (PointCloudT &output)
{
  // Calculate differences for each cloud
  std::vector<std::vector<float> > diffs (scales_.size ());

  // The cloud with the smallest scale has no differences
  std::vector<float> aux_diffs (input_->points.size (), 0.0f);
  diffs[scales_[0].second] = aux_diffs;

  cloud_trees_[scales_[0].second]->setInputCloud (clouds_[scales_[0].second]);
  for (size_t scale_i = 1; scale_i < clouds_.size (); ++scale_i)
  {
    size_t cloud_i = scales_[scale_i].second,
        cloud_i_minus_one = scales_[scale_i - 1].second;
    diffs[cloud_i].resize (input_->points.size ());
    PCL_INFO ("cloud_i %u cloud_i_minus_one %u\n", cloud_i, cloud_i_minus_one);
    for (size_t point_i = 0; point_i < input_->points.size (); ++point_i)
      diffs[cloud_i][point_i] = cloud_normals_[cloud_i]->points[point_i].getNormalVector3fMap ().dot (
          clouds_[cloud_i]->points[point_i].getVector3fMap () - clouds_[cloud_i_minus_one]->points[point_i].getVector3fMap ());

    // Setup kdtree for this cloud
    cloud_trees_[cloud_i]->setInputCloud (clouds_[cloud_i]);
  }

  // Find minima and maxima in differences inside the input cloud
  typename KdTree<PointT>::Ptr input_tree = cloud_trees_.back ();
  for (int point_i = 0; point_i < (int)input_->points.size (); ++point_i)
  {
    std::vector<int> nn_indices;
    std::vector<float> nn_distances;
    input_tree->radiusSearch (point_i, input_scale_ * neighborhood_constant_, nn_indices, nn_distances);

    bool is_min = true, is_max = true;
    for (std::vector<int>::iterator nn_it = nn_indices.begin (); nn_it != nn_indices.end (); ++nn_it)
      if (*nn_it != point_i)
      {
        if (diffs[input_index_][point_i] < diffs[input_index_][*nn_it])
          is_max = false;
        else if (diffs[input_index_][point_i] > diffs[input_index_][*nn_it])
          is_min = false;
      }

    // If the point is a local minimum/maximum, check if it is the same over all the scales
    if (is_min || is_max)
    {
      bool passed_min = true, passed_max = true;
      for (size_t scale_i = 0; scale_i < scales_.size (); ++scale_i)
      {
        size_t cloud_i = scales_[scale_i].second;
        // skip input cloud
        if (cloud_i == clouds_.size () - 1)
          continue;

        nn_indices.clear (); nn_distances.clear ();
        cloud_trees_[cloud_i]->radiusSearch (point_i, scales_[scale_i].first * neighborhood_constant_, nn_indices, nn_distances);

        bool is_min_other_scale = true, is_max_other_scale = true;
        for (std::vector<int>::iterator nn_it = nn_indices.begin (); nn_it != nn_indices.end (); ++nn_it)
          if (*nn_it != point_i)
          {
            if (diffs[input_index_][point_i] < diffs[cloud_i][*nn_it])
              is_max_other_scale = false;
            else if (diffs[input_index_][point_i] > diffs[cloud_i][*nn_it])
              is_min_other_scale = false;
          }

        if (is_min == true && is_min_other_scale == false)
          passed_min = false;
        if (is_max == true && is_max_other_scale == false)
          passed_max = false;

        if (!passed_min && !passed_max)
          break;
      }

      // check if point was minimum/maximum over all the scales
      if (passed_min || passed_max)
        output.points.push_back (input_->points[point_i]);
    }
  }

  output.header = input_->header;
  output.width = output.points.size ();
  output.height = 1;

  // debug stuff
//  for (size_t scale_i = 0; scale_i < scales_.size (); ++scale_i)
//  {
//    PointCloud<PointXYZI>::Ptr debug_cloud (new PointCloud<PointXYZI> ());
//    debug_cloud->points.resize (input_->points.size ());
//    debug_cloud->width = input_->width;
//    debug_cloud->height = input_->height;
//    for (size_t point_i = 0; point_i < input_->points.size (); ++point_i)
//    {
//      debug_cloud->points[point_i].intensity = diffs[scales_[scale_i].second][point_i];
//      debug_cloud->points[point_i].x = input_->points[point_i].x;
//      debug_cloud->points[point_i].y = input_->points[point_i].y;
//      debug_cloud->points[point_i].z = input_->points[point_i].z;
//    }

//    char str[512]; sprintf (str, "diffs_%2d.pcd", scale_i);
//    io::savePCDFile (str, *debug_cloud);
  }
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> bool
pcl::SmoothedSurfacesKeypoint<PointT, PointNT>::initCompute ()
{
  PCL_INFO ("SmoothedSurfacesKeypoint initCompute () called\n");
  if ( !Keypoint<PointT, PointT>::initCompute ())
  {
    PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] Keypoint::initCompute failed\n");
    return false;
  }

  if (!normals_)
  {
    PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] Input normals were not set\n");
    return false;
  }
  if (clouds_.size () == 0)
  {
    PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] No other clouds were set apart from the input\n");
    return false;
  }

  if (input_->points.size () != normals_->points.size ())
  {
    PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] The input cloud and the input normals differ in size\n");
    return false;
  }

  for (size_t cloud_i = 0; cloud_i < clouds_.size (); ++cloud_i)
  {
    if (clouds_[cloud_i]->points.size () != input_->points.size ())
    {
      PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] Cloud %d does not have the same number of points as the input cloud\n", cloud_i);
      return false;
    }

    if (cloud_normals_[cloud_i]->points.size () != input_->points.size ())
    {
      PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] Normals for cloud %d do not have the same number of points as the input cloud\n", cloud_i);
      return false;
    }
  }

  // Add the input cloud as the last index
  scales_.push_back (std::pair<float, size_t> (input_scale_, scales_.size ()));
  clouds_.push_back (input_);
  cloud_normals_.push_back (normals_);
  cloud_trees_.push_back (tree_);
  // Sort the clouds by their scales
  sort (scales_.begin (), scales_.end (), compareScalesFunction);

  // Find the index of the input after sorting
  for (size_t i = 0; i < scales_.size (); ++i)
    if (scales_[i].second == scales_.size () - 1)
    {
      input_index_ = i;
      break;
    }

  PCL_INFO ("Scales: ");
  for (size_t i = 0; i < scales_.size (); ++i) PCL_INFO ("(%d %f), ", scales_[i].second, scales_[i].first);
  PCL_INFO ("\n");

  return true;
}

#define PCL_INSTANTIATE_SmoothedSurfacesKeypoint(T,NT) template class PCL_EXPORTS pcl::SmoothedSurfacesKeypoint<T,NT>;

#endif /* PCL_KEYPOINTS_IMPL_SMOOTHEDSURFACESKEYPOINT_H_ */
<commit_msg>just because I have to break the build once in a while :-), sorry folks<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2011, Alexandru-Eugen Ichim
 *                      Willow Garage, Inc
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of 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.
 *
 * $Id$
 */

#ifndef PCL_KEYPOINTS_IMPL_SMOOTHEDSURFACESKEYPOINT_H_
#define PCL_KEYPOINTS_IMPL_SMOOTHEDSURFACESKEYPOINT_H_

#include "pcl/keypoints/smoothed_surfaces_keypoint.h"
#include <pcl/kdtree/kdtree_flann.h>

//#include <pcl/io/pcd_io.h>

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> void
pcl::SmoothedSurfacesKeypoint<PointT, PointNT>::addSmoothedPointCloud (const PointCloudTConstPtr &cloud,
                                                                       const PointCloudNTConstPtr &normals,
                                                                       KdTreePtr &kdtree,
                                                                       float &scale)
{
  clouds_.push_back (cloud);
  cloud_normals_.push_back (normals);
  cloud_trees_.push_back (kdtree);
  scales_.push_back (std::pair<float, size_t> (scale, scales_.size ()));
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> void
pcl::SmoothedSurfacesKeypoint<PointT, PointNT>::resetClouds ()
{
  clouds_.clear ();
  cloud_normals_.clear ();
  scales_.clear ();
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> void
pcl::SmoothedSurfacesKeypoint<PointT, PointNT>::detectKeypoints (PointCloudT &output)
{
  // Calculate differences for each cloud
  std::vector<std::vector<float> > diffs (scales_.size ());

  // The cloud with the smallest scale has no differences
  std::vector<float> aux_diffs (input_->points.size (), 0.0f);
  diffs[scales_[0].second] = aux_diffs;

  cloud_trees_[scales_[0].second]->setInputCloud (clouds_[scales_[0].second]);
  for (size_t scale_i = 1; scale_i < clouds_.size (); ++scale_i)
  {
    size_t cloud_i = scales_[scale_i].second,
        cloud_i_minus_one = scales_[scale_i - 1].second;
    diffs[cloud_i].resize (input_->points.size ());
    PCL_INFO ("cloud_i %u cloud_i_minus_one %u\n", cloud_i, cloud_i_minus_one);
    for (size_t point_i = 0; point_i < input_->points.size (); ++point_i)
      diffs[cloud_i][point_i] = cloud_normals_[cloud_i]->points[point_i].getNormalVector3fMap ().dot (
          clouds_[cloud_i]->points[point_i].getVector3fMap () - clouds_[cloud_i_minus_one]->points[point_i].getVector3fMap ());

    // Setup kdtree for this cloud
    cloud_trees_[cloud_i]->setInputCloud (clouds_[cloud_i]);
  }

  // Find minima and maxima in differences inside the input cloud
  typename KdTree<PointT>::Ptr input_tree = cloud_trees_.back ();
  for (int point_i = 0; point_i < (int)input_->points.size (); ++point_i)
  {
    std::vector<int> nn_indices;
    std::vector<float> nn_distances;
    input_tree->radiusSearch (point_i, input_scale_ * neighborhood_constant_, nn_indices, nn_distances);

    bool is_min = true, is_max = true;
    for (std::vector<int>::iterator nn_it = nn_indices.begin (); nn_it != nn_indices.end (); ++nn_it)
      if (*nn_it != point_i)
      {
        if (diffs[input_index_][point_i] < diffs[input_index_][*nn_it])
          is_max = false;
        else if (diffs[input_index_][point_i] > diffs[input_index_][*nn_it])
          is_min = false;
      }

    // If the point is a local minimum/maximum, check if it is the same over all the scales
    if (is_min || is_max)
    {
      bool passed_min = true, passed_max = true;
      for (size_t scale_i = 0; scale_i < scales_.size (); ++scale_i)
      {
        size_t cloud_i = scales_[scale_i].second;
        // skip input cloud
        if (cloud_i == clouds_.size () - 1)
          continue;

        nn_indices.clear (); nn_distances.clear ();
        cloud_trees_[cloud_i]->radiusSearch (point_i, scales_[scale_i].first * neighborhood_constant_, nn_indices, nn_distances);

        bool is_min_other_scale = true, is_max_other_scale = true;
        for (std::vector<int>::iterator nn_it = nn_indices.begin (); nn_it != nn_indices.end (); ++nn_it)
          if (*nn_it != point_i)
          {
            if (diffs[input_index_][point_i] < diffs[cloud_i][*nn_it])
              is_max_other_scale = false;
            else if (diffs[input_index_][point_i] > diffs[cloud_i][*nn_it])
              is_min_other_scale = false;
          }

        if (is_min == true && is_min_other_scale == false)
          passed_min = false;
        if (is_max == true && is_max_other_scale == false)
          passed_max = false;

        if (!passed_min && !passed_max)
          break;
      }

      // check if point was minimum/maximum over all the scales
      if (passed_min || passed_max)
        output.points.push_back (input_->points[point_i]);
    }
  }

  output.header = input_->header;
  output.width = output.points.size ();
  output.height = 1;

  // debug stuff
//  for (size_t scale_i = 0; scale_i < scales_.size (); ++scale_i)
//  {
//    PointCloud<PointXYZI>::Ptr debug_cloud (new PointCloud<PointXYZI> ());
//    debug_cloud->points.resize (input_->points.size ());
//    debug_cloud->width = input_->width;
//    debug_cloud->height = input_->height;
//    for (size_t point_i = 0; point_i < input_->points.size (); ++point_i)
//    {
//      debug_cloud->points[point_i].intensity = diffs[scales_[scale_i].second][point_i];
//      debug_cloud->points[point_i].x = input_->points[point_i].x;
//      debug_cloud->points[point_i].y = input_->points[point_i].y;
//      debug_cloud->points[point_i].z = input_->points[point_i].z;
//    }

//    char str[512]; sprintf (str, "diffs_%2d.pcd", scale_i);
//    io::savePCDFile (str, *debug_cloud);
//  }
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> bool
pcl::SmoothedSurfacesKeypoint<PointT, PointNT>::initCompute ()
{
  PCL_INFO ("SmoothedSurfacesKeypoint initCompute () called\n");
  if ( !Keypoint<PointT, PointT>::initCompute ())
  {
    PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] Keypoint::initCompute failed\n");
    return false;
  }

  if (!normals_)
  {
    PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] Input normals were not set\n");
    return false;
  }
  if (clouds_.size () == 0)
  {
    PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] No other clouds were set apart from the input\n");
    return false;
  }

  if (input_->points.size () != normals_->points.size ())
  {
    PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] The input cloud and the input normals differ in size\n");
    return false;
  }

  for (size_t cloud_i = 0; cloud_i < clouds_.size (); ++cloud_i)
  {
    if (clouds_[cloud_i]->points.size () != input_->points.size ())
    {
      PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] Cloud %d does not have the same number of points as the input cloud\n", cloud_i);
      return false;
    }

    if (cloud_normals_[cloud_i]->points.size () != input_->points.size ())
    {
      PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] Normals for cloud %d do not have the same number of points as the input cloud\n", cloud_i);
      return false;
    }
  }

  // Add the input cloud as the last index
  scales_.push_back (std::pair<float, size_t> (input_scale_, scales_.size ()));
  clouds_.push_back (input_);
  cloud_normals_.push_back (normals_);
  cloud_trees_.push_back (tree_);
  // Sort the clouds by their scales
  sort (scales_.begin (), scales_.end (), compareScalesFunction);

  // Find the index of the input after sorting
  for (size_t i = 0; i < scales_.size (); ++i)
    if (scales_[i].second == scales_.size () - 1)
    {
      input_index_ = i;
      break;
    }

  PCL_INFO ("Scales: ");
  for (size_t i = 0; i < scales_.size (); ++i) PCL_INFO ("(%d %f), ", scales_[i].second, scales_[i].first);
  PCL_INFO ("\n");

  return true;
}

#define PCL_INSTANTIATE_SmoothedSurfacesKeypoint(T,NT) template class PCL_EXPORTS pcl::SmoothedSurfacesKeypoint<T,NT>;

#endif /* PCL_KEYPOINTS_IMPL_SMOOTHEDSURFACESKEYPOINT_H_ */
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2017  Bastien Penavayre
 *                     Filip Roséen <filip.roseen@gmail.com>
 *                              http://b.atch.se/posts/constexpr-meta-container
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#pragma once

#include "uniq_value.hpp"

namespace unconstexpr
{
    namespace detail
    {
        template <class Tag = void, class Type = int, Type Start = 0, Type Step = 1>
        class meta_counter
        {
            template<Type N>
            struct Flag
            {
                friend constexpr bool adl_flag (Flag<N>);
            };

            template<Type N>
            struct Writer
            {
                friend constexpr bool adl_flag (Flag<N>) { return true; }
                static constexpr Type value = N;
            };

            template<Type N, bool = adl_flag(Flag<N>{})>
            static constexpr Type reader (int, Flag<N>, Type r = reader(0, Flag<N + Step>{}))
            {
                return r;
            }

            template <Type N>
            static constexpr Type reader(float, Flag<N>)
            {
                return N - Step;
            }

        public:
            template <Type = Writer<Start>::value>
            static constexpr Type value(Type r = reader(0, Flag<Start>{}))
            {
                return r;
            }

            template <Type Value = value()>
            static constexpr Type next(Type r = Writer<Value + Step>::value)
            {
                return r;
            }
        };

        template <unsigned> struct unique_type {};
    }

    template <class Type = int, Type Start = 0, Type It = 1, unsigned I = uniq_value::value<> >
    using meta_counter = detail::meta_counter<detail::unique_type<I>, Type, Start, It>;
}
<commit_msg>streamline meta_counter<commit_after>/*
 * Copyright (C) 2017  Bastien Penavayre
 *                     Filip Roséen <filip.roseen@gmail.com>
 *                              http://b.atch.se/posts/constexpr-meta-container
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#pragma once

#include "uniq_value.hpp"

namespace unconstexpr
{
    namespace detail
    {
        template <class Tag = void, class Type = int, Type Start = 0, Type Step = 1>
        class meta_counter
        {
            template<Type N>
            struct Flag
            {
                friend constexpr bool adl_flag (Flag<N>);
            };

            template<Type N>
            struct Writer
            {
                friend constexpr bool adl_flag (Flag<N>) { return true; }
                static constexpr Type value = N;
            };

            template<Type N, bool = adl_flag(Flag<N>{})>
            static constexpr Type reader (int, Flag<N>, Type r = reader(0, Flag<N + Step>{}))
            {
                return r;
            }

            template <Type N>
            static constexpr Type reader(float, Flag<N>)
            {
                return N;
            }

        public:
            static constexpr Type value(Type r = reader(0, Flag<Start>{}))
            {
                return r;
            }

            template <Type Value = value()>
            static constexpr Type next(Type r = Writer<Value>::value)
            {
                return r + Step;
            }
        };

        template <unsigned> struct unique_type {};
    }

    template <class Type = int, Type Start = 0, Type It = 1, unsigned I = uniq_value::value<> >
    using meta_counter = detail::meta_counter<detail::unique_type<I>, Type, Start, It>;
}
<|endoftext|>


<commit_before>#ifndef PYTHONIC_INCLUDE_BUILTIN_PYTHRAN_IS_NONE_HPP
#define PYTHONIC_INCLUDE_BUILTIN_PYTHRAN_IS_NONE_HPP

#include "pythonic/include/utils/functor.hpp"
#include "pythonic/include/types/NoneType.hpp"

PYTHONIC_NS_BEGIN

namespace types
{

  struct false_type;

  struct true_type {
    operator bool() const
    {
      return true;
    }
    false_type operator!() const;
    true_type operator&(true_type) const;
    false_type operator&(false_type) const;
    true_type operator|(true_type) const;
    true_type operator|(false_type) const;
    true_type operator==(true_type) const;
    false_type operator==(false_type) const;
  };

  struct false_type {
    operator bool() const
    {
      return false;
    }
    true_type operator!() const
    {
      return {};
    }
    false_type operator&(true_type)
    {
      return {};
    }
    false_type operator&(false_type)
    {
      return {};
    }
    true_type operator|(true_type)
    {
      return {};
    }
    false_type operator|(false_type)
    {
      return {};
    }
    false_type operator==(true_type)
    {
      return {};
    }
    true_type operator==(false_type)
    {
      return {};
    }
  };

  false_type true_type::operator!() const
  {
    return {};
  }
  true_type true_type::operator&(true_type) const
  {
    return {};
  }
  false_type true_type::operator&(false_type) const
  {
    return {};
  }
  true_type true_type::operator|(true_type) const
  {
    return {};
  }
  true_type true_type::operator|(false_type) const
  {
    return {};
  }
  true_type true_type::operator==(true_type) const
  {
    return {};
  }
  false_type true_type::operator==(false_type) const
  {
    return {};
  }
}

namespace __builtin__
{

  namespace pythran
  {
    template <class T>
    types::false_type is_none(T const &)
    {
      return {};
    };

    template <class T>
    bool is_none(types::none<T> const &n)
    {
      return n.is_none;
    };

    types::true_type is_none(types::none_type const &)
    {
      return {};
    };

    DEFINE_FUNCTOR(pythonic::__builtin__::pythran, is_none);
  }
}
template <>
struct to_python<types::true_type> : to_python<bool> {
};
template <>
struct to_python<types::false_type> : to_python<bool> {
};
PYTHONIC_NS_END

#endif
<commit_msg>fix compile without ENABLE_PYTHON_MODULE<commit_after>#ifndef PYTHONIC_INCLUDE_BUILTIN_PYTHRAN_IS_NONE_HPP
#define PYTHONIC_INCLUDE_BUILTIN_PYTHRAN_IS_NONE_HPP

#include "pythonic/include/utils/functor.hpp"
#include "pythonic/include/types/NoneType.hpp"

PYTHONIC_NS_BEGIN

namespace types
{

  struct false_type;

  struct true_type {
    operator bool() const
    {
      return true;
    }
    false_type operator!() const;
    true_type operator&(true_type) const;
    false_type operator&(false_type) const;
    true_type operator|(true_type) const;
    true_type operator|(false_type) const;
    true_type operator==(true_type) const;
    false_type operator==(false_type) const;
  };

  struct false_type {
    operator bool() const
    {
      return false;
    }
    true_type operator!() const
    {
      return {};
    }
    false_type operator&(true_type)
    {
      return {};
    }
    false_type operator&(false_type)
    {
      return {};
    }
    true_type operator|(true_type)
    {
      return {};
    }
    false_type operator|(false_type)
    {
      return {};
    }
    false_type operator==(true_type)
    {
      return {};
    }
    true_type operator==(false_type)
    {
      return {};
    }
  };

  false_type true_type::operator!() const
  {
    return {};
  }
  true_type true_type::operator&(true_type) const
  {
    return {};
  }
  false_type true_type::operator&(false_type) const
  {
    return {};
  }
  true_type true_type::operator|(true_type) const
  {
    return {};
  }
  true_type true_type::operator|(false_type) const
  {
    return {};
  }
  true_type true_type::operator==(true_type) const
  {
    return {};
  }
  false_type true_type::operator==(false_type) const
  {
    return {};
  }
}

namespace __builtin__
{

  namespace pythran
  {
    template <class T>
    types::false_type is_none(T const &)
    {
      return {};
    };

    template <class T>
    bool is_none(types::none<T> const &n)
    {
      return n.is_none;
    };

    types::true_type is_none(types::none_type const &)
    {
      return {};
    };

    DEFINE_FUNCTOR(pythonic::__builtin__::pythran, is_none);
  }
}

#ifdef ENABLE_PYTHON_MODULE

template <>
struct to_python<types::true_type> : to_python<bool> {
};
template <>
struct to_python<types::false_type> : to_python<bool> {
};

#endif

PYTHONIC_NS_END

#endif
<|endoftext|>