<commit_before>#ifndef CAFFE_VISION_LAYERS_HPP_
#define CAFFE_VISION_LAYERS_HPP_

#include <string>
#include <utility>
#include <vector>

#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/common_layers.hpp"
#include "caffe/data_layers.hpp"
#include "caffe/layer.hpp"
#include "caffe/loss_layers.hpp"
#include "caffe/neuron_layers.hpp"
#include "caffe/proto/caffe.pb.h"

namespace caffe {

/**
 * @brief Convolves the input image with a bank of learned filters,
 *        and (optionally) adds biases.
 *
 * TODO(dox): thorough documentation for Forward, Backward, and proto params.
 */
template <typename Dtype>
class ConvolutionLayer : public Layer<Dtype> {
 public:
  explicit ConvolutionLayer(const LayerParameter& param)
      : Layer<Dtype>(param) {}
  virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);

  virtual inline LayerParameter_LayerType type() const {
    return LayerParameter_LayerType_CONVOLUTION;
  }
  virtual inline int MinBottomBlobs() const { return 1; }
  virtual inline int MinTopBlobs() const { return 1; }
  virtual inline bool EqualNumBottomTopBlobs() const { return true; }

 protected:
  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
  virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);

  int kernel_h_, kernel_w_;
  int stride_h_, stride_w_;
  int num_;
  int channels_;
  int pad_h_, pad_w_;
  int height_, width_;
  int group_;
  int num_output_;
  int height_out_, width_out_;
  bool bias_term_;
  // For the Caffe matrix multiplication convolution.
  int M_, K_, N_;
  Blob<Dtype> col_buffer_;
  Blob<Dtype> bias_multiplier_;
};

#ifdef USE_CUDNN
/*
 * @brief cuDNN implementation of ConvolutionLayer.
 *        Fallback to ConvolutionLayer for CPU mode.
*/
template <typename Dtype>
class CuDNNConvolutionLayer : public ConvolutionLayer<Dtype>
{
 public:
  explicit CuDNNConvolutionLayer(const LayerParameter& param)
      : ConvolutionLayer<Dtype>(param) {}
  virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual ~CuDNNConvolutionLayer();

 protected:
  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);

  cudnnHandle_t* handle_;
  cudaStream_t*  stream_;
  vector<cudnnTensor4dDescriptor_t> bottom_descs_, top_descs_;
  cudnnTensor4dDescriptor_t    bias_desc_;
  cudnnFilterDescriptor_t      filter_desc_;
  vector<cudnnConvolutionDescriptor_t> conv_descs_;
  int bottom_offset_, top_offset_, weight_offset_, bias_offset_;
};
#endif

/**
 * @brief A helper for image operations that rearranges image regions into
 *        column vectors.  Used by ConvolutionLayer to perform convolution
 *        by matrix multiplication.
 *
 * TODO(dox): thorough documentation for Forward, Backward, and proto params.
 */
template <typename Dtype>
class Im2colLayer : public Layer<Dtype> {
 public:
  explicit Im2colLayer(const LayerParameter& param)
      : Layer<Dtype>(param) {}
  virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);

  virtual inline LayerParameter_LayerType type() const {
    return LayerParameter_LayerType_IM2COL;
  }
  virtual inline int ExactNumBottomBlobs() const { return 1; }
  virtual inline int ExactNumTopBlobs() const { return 1; }

 protected:
  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
  virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);

  int kernel_h_, kernel_w_;
  int stride_h_, stride_w_;
  int channels_;
  int height_, width_;
  int pad_h_, pad_w_;
};

// Forward declare PoolingLayer and SplitLayer for use in LRNLayer.
template <typename Dtype> class PoolingLayer;
template <typename Dtype> class SplitLayer;

/**
 * @brief Normalize the input in a local region across or within feature maps.
 *
 * TODO(dox): thorough documentation for Forward, Backward, and proto params.
 */
template <typename Dtype>
class LRNLayer : public Layer<Dtype> {
 public:
  explicit LRNLayer(const LayerParameter& param)
      : Layer<Dtype>(param) {}
  virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);

  virtual inline LayerParameter_LayerType type() const {
    return LayerParameter_LayerType_LRN;
  }
  virtual inline int ExactNumBottomBlobs() const { return 1; }
  virtual inline int ExactNumTopBlobs() const { return 1; }

 protected:
  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
  virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);

  virtual void CrossChannelForward_cpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual void CrossChannelForward_gpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual void WithinChannelForward(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual void CrossChannelBackward_cpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
  virtual void CrossChannelBackward_gpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
  virtual void WithinChannelBackward(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);

  int size_;
  int pre_pad_;
  Dtype alpha_;
  Dtype beta_;
  int num_;
  int channels_;
  int height_;
  int width_;

  // Fields used for normalization ACROSS_CHANNELS
  // scale_ stores the intermediate summing results
  Blob<Dtype> scale_;

  // Fields used for normalization WITHIN_CHANNEL
  shared_ptr<SplitLayer<Dtype> > split_layer_;
  vector<Blob<Dtype>*> split_top_vec_;
  shared_ptr<PowerLayer<Dtype> > square_layer_;
  Blob<Dtype> square_input_;
  Blob<Dtype> square_output_;
  vector<Blob<Dtype>*> square_bottom_vec_;
  vector<Blob<Dtype>*> square_top_vec_;
  shared_ptr<PoolingLayer<Dtype> > pool_layer_;
  Blob<Dtype> pool_output_;
  vector<Blob<Dtype>*> pool_top_vec_;
  shared_ptr<PowerLayer<Dtype> > power_layer_;
  Blob<Dtype> power_output_;
  vector<Blob<Dtype>*> power_top_vec_;
  shared_ptr<EltwiseLayer<Dtype> > product_layer_;
  Blob<Dtype> product_input_;
  vector<Blob<Dtype>*> product_bottom_vec_;
};

/**
 * @brief Pools the input image by taking the max, average, etc. within regions.
 *
 * TODO(dox): thorough documentation for Forward, Backward, and proto params.
 */
template <typename Dtype>
class PoolingLayer : public Layer<Dtype> {
 public:
  explicit PoolingLayer(const LayerParameter& param)
      : Layer<Dtype>(param) {}
  virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);

  virtual inline LayerParameter_LayerType type() const {
    return LayerParameter_LayerType_POOLING;
  }
  virtual inline int ExactNumBottomBlobs() const { return 1; }
  virtual inline int MinTopBlobs() const { return 1; }
  // MAX POOL layers can output an extra top blob for the mask;
  // others can only output the pooled inputs.
  virtual inline int MaxTopBlobs() const {
    return (this->layer_param_.pooling_param().pool() ==
            PoolingParameter_PoolMethod_MAX) ? 2 : 1;
  }

 protected:
  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
  virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);

  int kernel_h_, kernel_w_;
  int stride_h_, stride_w_;
  int pad_h_, pad_w_;
  int channels_;
  int height_, width_;
  int pooled_height_, pooled_width_;
  Blob<Dtype> rand_idx_;
  Blob<int> max_idx_;
};

#ifdef USE_CUDNN
/*
 * @brief cuDNN implementation of PoolingLayer.
 *        Fallback to PoolingLayer for CPU mode.
*/
template <typename Dtype>
class CuDNNPoolingLayer : public PoolingLayer<Dtype> {
 public:
  explicit CuDNNPoolingLayer(const LayerParameter& param)
      : PoolingLayer<Dtype>(param) {}
  virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual ~CuDNNPoolingLayer();

 protected:
  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);

  cudnnHandle_t             handle_;
  cudnnTensor4dDescriptor_t bottom_desc_, top_desc_;
  cudnnPoolingDescriptor_t  pooling_desc_;
  cudnnPoolingMode_t        mode_;
};
#endif

}  // namespace caffe

#endif  // CAFFE_VISION_LAYERS_HPP_
<commit_msg>[lint] cuDNN conv declaration<commit_after>#ifndef CAFFE_VISION_LAYERS_HPP_
#define CAFFE_VISION_LAYERS_HPP_

#include <string>
#include <utility>
#include <vector>

#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/common_layers.hpp"
#include "caffe/data_layers.hpp"
#include "caffe/layer.hpp"
#include "caffe/loss_layers.hpp"
#include "caffe/neuron_layers.hpp"
#include "caffe/proto/caffe.pb.h"

namespace caffe {

/**
 * @brief Convolves the input image with a bank of learned filters,
 *        and (optionally) adds biases.
 *
 * TODO(dox): thorough documentation for Forward, Backward, and proto params.
 */
template <typename Dtype>
class ConvolutionLayer : public Layer<Dtype> {
 public:
  explicit ConvolutionLayer(const LayerParameter& param)
      : Layer<Dtype>(param) {}
  virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);

  virtual inline LayerParameter_LayerType type() const {
    return LayerParameter_LayerType_CONVOLUTION;
  }
  virtual inline int MinBottomBlobs() const { return 1; }
  virtual inline int MinTopBlobs() const { return 1; }
  virtual inline bool EqualNumBottomTopBlobs() const { return true; }

 protected:
  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
  virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);

  int kernel_h_, kernel_w_;
  int stride_h_, stride_w_;
  int num_;
  int channels_;
  int pad_h_, pad_w_;
  int height_, width_;
  int group_;
  int num_output_;
  int height_out_, width_out_;
  bool bias_term_;
  // For the Caffe matrix multiplication convolution.
  int M_, K_, N_;
  Blob<Dtype> col_buffer_;
  Blob<Dtype> bias_multiplier_;
};

#ifdef USE_CUDNN
/*
 * @brief cuDNN implementation of ConvolutionLayer.
 *        Fallback to ConvolutionLayer for CPU mode.
*/
template <typename Dtype>
class CuDNNConvolutionLayer : public ConvolutionLayer<Dtype> {
 public:
  explicit CuDNNConvolutionLayer(const LayerParameter& param)
      : ConvolutionLayer<Dtype>(param) {}
  virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual ~CuDNNConvolutionLayer();

 protected:
  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);

  cudnnHandle_t* handle_;
  cudaStream_t*  stream_;
  vector<cudnnTensor4dDescriptor_t> bottom_descs_, top_descs_;
  cudnnTensor4dDescriptor_t    bias_desc_;
  cudnnFilterDescriptor_t      filter_desc_;
  vector<cudnnConvolutionDescriptor_t> conv_descs_;
  int bottom_offset_, top_offset_, weight_offset_, bias_offset_;
};
#endif

/**
 * @brief A helper for image operations that rearranges image regions into
 *        column vectors.  Used by ConvolutionLayer to perform convolution
 *        by matrix multiplication.
 *
 * TODO(dox): thorough documentation for Forward, Backward, and proto params.
 */
template <typename Dtype>
class Im2colLayer : public Layer<Dtype> {
 public:
  explicit Im2colLayer(const LayerParameter& param)
      : Layer<Dtype>(param) {}
  virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);

  virtual inline LayerParameter_LayerType type() const {
    return LayerParameter_LayerType_IM2COL;
  }
  virtual inline int ExactNumBottomBlobs() const { return 1; }
  virtual inline int ExactNumTopBlobs() const { return 1; }

 protected:
  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
  virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);

  int kernel_h_, kernel_w_;
  int stride_h_, stride_w_;
  int channels_;
  int height_, width_;
  int pad_h_, pad_w_;
};

// Forward declare PoolingLayer and SplitLayer for use in LRNLayer.
template <typename Dtype> class PoolingLayer;
template <typename Dtype> class SplitLayer;

/**
 * @brief Normalize the input in a local region across or within feature maps.
 *
 * TODO(dox): thorough documentation for Forward, Backward, and proto params.
 */
template <typename Dtype>
class LRNLayer : public Layer<Dtype> {
 public:
  explicit LRNLayer(const LayerParameter& param)
      : Layer<Dtype>(param) {}
  virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);

  virtual inline LayerParameter_LayerType type() const {
    return LayerParameter_LayerType_LRN;
  }
  virtual inline int ExactNumBottomBlobs() const { return 1; }
  virtual inline int ExactNumTopBlobs() const { return 1; }

 protected:
  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
  virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);

  virtual void CrossChannelForward_cpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual void CrossChannelForward_gpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual void WithinChannelForward(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual void CrossChannelBackward_cpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
  virtual void CrossChannelBackward_gpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
  virtual void WithinChannelBackward(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);

  int size_;
  int pre_pad_;
  Dtype alpha_;
  Dtype beta_;
  int num_;
  int channels_;
  int height_;
  int width_;

  // Fields used for normalization ACROSS_CHANNELS
  // scale_ stores the intermediate summing results
  Blob<Dtype> scale_;

  // Fields used for normalization WITHIN_CHANNEL
  shared_ptr<SplitLayer<Dtype> > split_layer_;
  vector<Blob<Dtype>*> split_top_vec_;
  shared_ptr<PowerLayer<Dtype> > square_layer_;
  Blob<Dtype> square_input_;
  Blob<Dtype> square_output_;
  vector<Blob<Dtype>*> square_bottom_vec_;
  vector<Blob<Dtype>*> square_top_vec_;
  shared_ptr<PoolingLayer<Dtype> > pool_layer_;
  Blob<Dtype> pool_output_;
  vector<Blob<Dtype>*> pool_top_vec_;
  shared_ptr<PowerLayer<Dtype> > power_layer_;
  Blob<Dtype> power_output_;
  vector<Blob<Dtype>*> power_top_vec_;
  shared_ptr<EltwiseLayer<Dtype> > product_layer_;
  Blob<Dtype> product_input_;
  vector<Blob<Dtype>*> product_bottom_vec_;
};

/**
 * @brief Pools the input image by taking the max, average, etc. within regions.
 *
 * TODO(dox): thorough documentation for Forward, Backward, and proto params.
 */
template <typename Dtype>
class PoolingLayer : public Layer<Dtype> {
 public:
  explicit PoolingLayer(const LayerParameter& param)
      : Layer<Dtype>(param) {}
  virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);

  virtual inline LayerParameter_LayerType type() const {
    return LayerParameter_LayerType_POOLING;
  }
  virtual inline int ExactNumBottomBlobs() const { return 1; }
  virtual inline int MinTopBlobs() const { return 1; }
  // MAX POOL layers can output an extra top blob for the mask;
  // others can only output the pooled inputs.
  virtual inline int MaxTopBlobs() const {
    return (this->layer_param_.pooling_param().pool() ==
            PoolingParameter_PoolMethod_MAX) ? 2 : 1;
  }

 protected:
  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
  virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);

  int kernel_h_, kernel_w_;
  int stride_h_, stride_w_;
  int pad_h_, pad_w_;
  int channels_;
  int height_, width_;
  int pooled_height_, pooled_width_;
  Blob<Dtype> rand_idx_;
  Blob<int> max_idx_;
};

#ifdef USE_CUDNN
/*
 * @brief cuDNN implementation of PoolingLayer.
 *        Fallback to PoolingLayer for CPU mode.
*/
template <typename Dtype>
class CuDNNPoolingLayer : public PoolingLayer<Dtype> {
 public:
  explicit CuDNNPoolingLayer(const LayerParameter& param)
      : PoolingLayer<Dtype>(param) {}
  virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual ~CuDNNPoolingLayer();

 protected:
  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);

  cudnnHandle_t             handle_;
  cudnnTensor4dDescriptor_t bottom_desc_, top_desc_;
  cudnnPoolingDescriptor_t  pooling_desc_;
  cudnnPoolingMode_t        mode_;
};
#endif

}  // namespace caffe

#endif  // CAFFE_VISION_LAYERS_HPP_
<|endoftext|>


<commit_before>/* DLL export definitions for LASzip */

#ifndef LASZIPEXPORT_H
#define LASZIPEXPORT_H

#ifndef LASZIP_DLL
#if (defined(_MSC_VER) || defined __CYGWIN__) && !defined(LAS_DISABLE_DLL)
    #if defined(LASZIP_DLL_EXPORT)
    #   define LASZIP_DLL   __declspec(dllexport)
    #elif defined(LASZIP_DLL_IMPORT)
    #   define LASZIP_DLL   __declspec(dllimport)
    #else
    #   define LASZIP_DLL
    #endif
#else
    #  if defined(USE_GCC_VISIBILITY_FLAG)
    #    define LASZIP_DLL     __attribute__ ((visibility("default")))
    #  else
    #    define LASZIP_DLL
    #  endif
#endif
#endif

#endif
<commit_msg>rename copied symbol from liblas<commit_after>/* DLL export definitions for LASzip */

#ifndef LASZIPEXPORT_H
#define LASZIPEXPORT_H

#ifndef LASZIP_DLL
#if (defined(_MSC_VER) || defined __CYGWIN__) && !defined(LASZIP_DISABLE_DLL)
    #if defined(LASZIP_DLL_EXPORT)
    #   define LASZIP_DLL   __declspec(dllexport)
    #elif defined(LASZIP_DLL_IMPORT)
    #   define LASZIP_DLL   __declspec(dllimport)
    #else
    #   define LASZIP_DLL
    #endif
#else
    #  if defined(USE_GCC_VISIBILITY_FLAG)
    #    define LASZIP_DLL     __attribute__ ((visibility("default")))
    #  else
    #    define LASZIP_DLL
    #  endif
#endif
#endif

#endif
<|endoftext|>


<commit_before>/*

Copyright (c) 2008-2014, Arvid Norberg
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 the author 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.

*/

#ifndef TORRENT_BITFIELD_HPP_INCLUDED
#define TORRENT_BITFIELD_HPP_INCLUDED

#include "libtorrent/assert.hpp"
#include "libtorrent/config.hpp"
#include <cstring> // for memset and memcpy
#include <cstdlib> // for malloc, free and realloc
#include <boost/cstdint.hpp> // uint32_t

namespace libtorrent
{
	// The bitfiled type stores any number of bits as a bitfield
	// in a heap allocated or borrowed array.
	struct TORRENT_EXPORT bitfield
	{
		// constructs a new bitfield. The default constructor creates an empty
		// bitfield. ``bits`` is the size of the bitfield (specified in bits).
		// `` val`` is the value to initialize the bits to. If not specified
		// all bits are initialized to 0.
		//
		// The constructor taking a pointer ``b`` and ``bits`` copies a bitfield
		// from the specified buffer, and ``bits`` number of bits (rounded up to
		// the nearest byte boundry).
		bitfield(): m_bytes(0), m_size(0), m_own(false) {}
		bitfield(int bits): m_bytes(0), m_size(0), m_own(false)
		{ resize(bits); }
		bitfield(int bits, bool val): m_bytes(0), m_size(0), m_own(false)
		{ resize(bits, val); }
		bitfield(char const* b, int bits): m_bytes(0), m_size(0), m_own(false)
		{ assign(b, bits); }
		bitfield(bitfield const& rhs): m_bytes(0), m_size(0), m_own(false)
		{ assign(rhs.bytes(), rhs.size()); }
#if __cplusplus > 199711L
		bitfield(bitfield&& rhs): m_bytes(rhs.m_bytes), m_size(rhs.m_size), m_own(rhs.m_own)
		{ rhs.m_bytes = NULL; }
#endif

		// assigns a bitfield pointed to ``b`` of ``bits`` number of bits, without
		// taking ownership of the buffer. This is a way to avoid copying data and
		// yet provide a raw buffer to functions that may operate on the bitfield
		// type. It is the user's responsibility to make sure the passed-in buffer's
		// life time exceeds all uses of the bitfield.
		void borrow_bytes(char* b, int bits)
		{
			dealloc();
			m_bytes = (unsigned char*)b;
			m_size = bits;
			m_own = false;
		}

		// hidden
		~bitfield() { dealloc(); }

		// copy bitfield from buffer ``b`` of ``bits`` number of bits, rounded up to
		// the nearest byte boundary.
		void assign(char const* b, int bits)
		{ resize(bits); std::memcpy(m_bytes, b, (bits + 7) / 8); clear_trailing_bits(); }

		// query bit at ``index``. Returns true if bit is 1, otherwise false.
		bool operator[](int index) const
		{ return get_bit(index); }
		bool get_bit(int index) const
		{
			TORRENT_ASSERT(index >= 0);
			TORRENT_ASSERT(index < m_size);
			return (m_bytes[index / 8] & (0x80 >> (index & 7))) != 0;
		}

		// set bit at ``index`` to 0 (clear_bit) or 1 (set_bit).
		void clear_bit(int index)
		{
			TORRENT_ASSERT(index >= 0);
			TORRENT_ASSERT(index < m_size);
			m_bytes[index / 8] &= ~(0x80 >> (index & 7));
		}
		void set_bit(int index)
		{
			TORRENT_ASSERT(index >= 0);
			TORRENT_ASSERT(index < m_size);
			m_bytes[index / 8] |= (0x80 >> (index & 7));
		}

		// returns true if all bits in the bitfield are set
		bool all_set() const
		{
			const int num_words = m_size / 32;
			const int num_bytes = m_size / 8;
			boost::uint32_t* bits = (boost::uint32_t*)m_bytes;
			for (int i = 0; i < num_words; ++i)
			{
				if (bits[i] != 0xffffffff) return false;
			}

			for (int i = num_words * 4; i < num_bytes; ++i)
			{
				if (m_bytes[i] != 0xff) return false;
			}
			int rest = m_size - num_bytes * 8;
			boost::uint8_t mask = (0xff << (8-rest)) & 0xff;
			if (rest > 0 && (m_bytes[num_bytes] & mask) != mask)
				return false;
			return true;
		}

		// returns the size of the bitfield in bits.
		std::size_t size() const { return m_size; }

		// returns true if the bitfield has zero size.
		bool empty() const { return m_size == 0; }

		// returns a pointer to the internal buffer of the bitfield.
		char const* bytes() const { return (char*)m_bytes; }

		// copy operator
		bitfield& operator=(bitfield const& rhs)
		{
			assign(rhs.bytes(), rhs.size());
			return *this;
		}

		// count the number of bits in the bitfield that are set to 1.
		int count() const
		{
			// 0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111,
			// 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111
			const static char num_bits[] =
			{
				0, 1, 1, 2, 1, 2, 2, 3,
				1, 2, 2, 3, 2, 3, 3, 4
			};

			int ret = 0;
			const int num_bytes = m_size / 8;
			for (int i = 0; i < num_bytes; ++i)
			{
				ret += num_bits[m_bytes[i] & 0xf] + num_bits[m_bytes[i] >> 4];
			}

			int rest = m_size - num_bytes * 8;
			for (int i = 0; i < rest; ++i)
			{
				ret += (m_bytes[num_bytes] >> (7-i)) & 1;
			}
			TORRENT_ASSERT(ret <= m_size);
			TORRENT_ASSERT(ret >= 0);
			return ret;
		}

		struct const_iterator
		{
		friend struct bitfield;

			typedef bool value_type;
			typedef ptrdiff_t difference_type;
			typedef bool const* pointer;
			typedef bool& reference;
			typedef std::forward_iterator_tag iterator_category;

			bool operator*() { return (*byte & bit) != 0; }
			const_iterator& operator++() { inc(); return *this; }
			const_iterator operator++(int)
			{ const_iterator ret(*this); inc(); return ret; }
			const_iterator& operator--() { dec(); return *this; }
			const_iterator operator--(int)
			{ const_iterator ret(*this); dec(); return ret; }

			const_iterator(): byte(0), bit(0x80) {}
			bool operator==(const_iterator const& rhs) const
			{ return byte == rhs.byte && bit == rhs.bit; }

			bool operator!=(const_iterator const& rhs) const
			{ return byte != rhs.byte || bit != rhs.bit; }

		private:
			void inc()
			{
				TORRENT_ASSERT(byte);
				if (bit == 0x01)
				{
					bit = 0x80;
					++byte;
				}
				else
				{
					bit >>= 1;
				}
			}
			void dec()
			{
				TORRENT_ASSERT(byte);
				if (bit == 0x80)
				{
					bit = 0x01;
					--byte;
				}
				else
				{
					bit <<= 1;
				}
			}
			const_iterator(unsigned char const* ptr, int offset)
				: byte(ptr), bit(0x80 >> offset) {}
			unsigned char const* byte;
			int bit;
		};

		const_iterator begin() const { return const_iterator(m_bytes, 0); }
		const_iterator end() const { return const_iterator(m_bytes + m_size / 8, m_size & 7); }

		// set the size of the bitfield to ``bits`` length. If the bitfield is extended,
		// the new bits are initialized to ``val``.
		void resize(int bits, bool val)
		{
			int s = m_size;
			int b = m_size & 7;
			resize(bits);
			if (s >= m_size) return;
			int old_size_bytes = (s + 7) / 8;
			int new_size_bytes = (m_size + 7) / 8;
			if (val)
			{
				if (old_size_bytes && b) m_bytes[old_size_bytes - 1] |= (0xff >> b);
				if (old_size_bytes < new_size_bytes)
					std::memset(m_bytes + old_size_bytes, 0xff, new_size_bytes - old_size_bytes);
				clear_trailing_bits();
			}
			else
			{
				if (old_size_bytes < new_size_bytes)
					std::memset(m_bytes + old_size_bytes, 0x00, new_size_bytes - old_size_bytes);
			}
		}
		void resize(int bits)
		{
			TORRENT_ASSERT(bits >= 0);
			const int b = (bits + 7) / 8;
			if (m_bytes)
			{
				if (m_own)
				{
					m_bytes = (unsigned char*)std::realloc(m_bytes, b);
					m_own = true;
				}
				else if (bits > m_size)
				{
					unsigned char* tmp = (unsigned char*)std::malloc(b);
					std::memcpy(tmp, m_bytes, (std::min)(int(m_size + 7)/ 8, b));
					m_bytes = tmp;
					m_own = true;
				}
			}
			else if (bits > 0)
			{
				m_bytes = (unsigned char*)std::malloc(b);
				m_own = true;
			}
			m_size = bits;
			clear_trailing_bits();
		}

		// set all bits in the bitfield to 1 (set_all) or 0 (clear_all).
		void set_all()
		{
			std::memset(m_bytes, 0xff, (m_size + 7) / 8);
			clear_trailing_bits();
		}
		void clear_all()
		{
			std::memset(m_bytes, 0x00, (m_size + 7) / 8);
		}

		// make the bitfield empty, of zero size.
		void clear() { dealloc(); m_size = 0; }

	private:

		void clear_trailing_bits()
		{
			// clear the tail bits in the last byte
			if (m_size & 7) m_bytes[(m_size + 7) / 8 - 1] &= 0xff << (8 - (m_size & 7));
		}

		void dealloc() { if (m_own) std::free(m_bytes); m_bytes = 0; }
		unsigned char* m_bytes;
		int m_size:31; // in bits
		bool m_own:1;
	};

}

#endif // TORRENT_BITFIELD_HPP_INCLUDED

<commit_msg>add missing include<commit_after>/*

Copyright (c) 2008-2014, Arvid Norberg
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 the author 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.

*/

#ifndef TORRENT_BITFIELD_HPP_INCLUDED
#define TORRENT_BITFIELD_HPP_INCLUDED

#include "libtorrent/assert.hpp"
#include "libtorrent/config.hpp"
#include <cstring> // for memset and memcpy
#include <cstdlib> // for malloc, free and realloc
#include <boost/cstdint.hpp> // uint32_t
#include <algorithm> // for min()

namespace libtorrent
{
	// The bitfiled type stores any number of bits as a bitfield
	// in a heap allocated or borrowed array.
	struct TORRENT_EXPORT bitfield
	{
		// constructs a new bitfield. The default constructor creates an empty
		// bitfield. ``bits`` is the size of the bitfield (specified in bits).
		// `` val`` is the value to initialize the bits to. If not specified
		// all bits are initialized to 0.
		//
		// The constructor taking a pointer ``b`` and ``bits`` copies a bitfield
		// from the specified buffer, and ``bits`` number of bits (rounded up to
		// the nearest byte boundry).
		bitfield(): m_bytes(0), m_size(0), m_own(false) {}
		bitfield(int bits): m_bytes(0), m_size(0), m_own(false)
		{ resize(bits); }
		bitfield(int bits, bool val): m_bytes(0), m_size(0), m_own(false)
		{ resize(bits, val); }
		bitfield(char const* b, int bits): m_bytes(0), m_size(0), m_own(false)
		{ assign(b, bits); }
		bitfield(bitfield const& rhs): m_bytes(0), m_size(0), m_own(false)
		{ assign(rhs.bytes(), rhs.size()); }
#if __cplusplus > 199711L
		bitfield(bitfield&& rhs): m_bytes(rhs.m_bytes), m_size(rhs.m_size), m_own(rhs.m_own)
		{ rhs.m_bytes = NULL; }
#endif

		// assigns a bitfield pointed to ``b`` of ``bits`` number of bits, without
		// taking ownership of the buffer. This is a way to avoid copying data and
		// yet provide a raw buffer to functions that may operate on the bitfield
		// type. It is the user's responsibility to make sure the passed-in buffer's
		// life time exceeds all uses of the bitfield.
		void borrow_bytes(char* b, int bits)
		{
			dealloc();
			m_bytes = (unsigned char*)b;
			m_size = bits;
			m_own = false;
		}

		// hidden
		~bitfield() { dealloc(); }

		// copy bitfield from buffer ``b`` of ``bits`` number of bits, rounded up to
		// the nearest byte boundary.
		void assign(char const* b, int bits)
		{ resize(bits); std::memcpy(m_bytes, b, (bits + 7) / 8); clear_trailing_bits(); }

		// query bit at ``index``. Returns true if bit is 1, otherwise false.
		bool operator[](int index) const
		{ return get_bit(index); }
		bool get_bit(int index) const
		{
			TORRENT_ASSERT(index >= 0);
			TORRENT_ASSERT(index < m_size);
			return (m_bytes[index / 8] & (0x80 >> (index & 7))) != 0;
		}

		// set bit at ``index`` to 0 (clear_bit) or 1 (set_bit).
		void clear_bit(int index)
		{
			TORRENT_ASSERT(index >= 0);
			TORRENT_ASSERT(index < m_size);
			m_bytes[index / 8] &= ~(0x80 >> (index & 7));
		}
		void set_bit(int index)
		{
			TORRENT_ASSERT(index >= 0);
			TORRENT_ASSERT(index < m_size);
			m_bytes[index / 8] |= (0x80 >> (index & 7));
		}

		// returns true if all bits in the bitfield are set
		bool all_set() const
		{
			const int num_words = m_size / 32;
			const int num_bytes = m_size / 8;
			boost::uint32_t* bits = (boost::uint32_t*)m_bytes;
			for (int i = 0; i < num_words; ++i)
			{
				if (bits[i] != 0xffffffff) return false;
			}

			for (int i = num_words * 4; i < num_bytes; ++i)
			{
				if (m_bytes[i] != 0xff) return false;
			}
			int rest = m_size - num_bytes * 8;
			boost::uint8_t mask = (0xff << (8-rest)) & 0xff;
			if (rest > 0 && (m_bytes[num_bytes] & mask) != mask)
				return false;
			return true;
		}

		// returns the size of the bitfield in bits.
		std::size_t size() const { return m_size; }

		// returns true if the bitfield has zero size.
		bool empty() const { return m_size == 0; }

		// returns a pointer to the internal buffer of the bitfield.
		char const* bytes() const { return (char*)m_bytes; }

		// copy operator
		bitfield& operator=(bitfield const& rhs)
		{
			assign(rhs.bytes(), rhs.size());
			return *this;
		}

		// count the number of bits in the bitfield that are set to 1.
		int count() const
		{
			// 0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111,
			// 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111
			const static char num_bits[] =
			{
				0, 1, 1, 2, 1, 2, 2, 3,
				1, 2, 2, 3, 2, 3, 3, 4
			};

			int ret = 0;
			const int num_bytes = m_size / 8;
			for (int i = 0; i < num_bytes; ++i)
			{
				ret += num_bits[m_bytes[i] & 0xf] + num_bits[m_bytes[i] >> 4];
			}

			int rest = m_size - num_bytes * 8;
			for (int i = 0; i < rest; ++i)
			{
				ret += (m_bytes[num_bytes] >> (7-i)) & 1;
			}
			TORRENT_ASSERT(ret <= m_size);
			TORRENT_ASSERT(ret >= 0);
			return ret;
		}

		struct const_iterator
		{
		friend struct bitfield;

			typedef bool value_type;
			typedef ptrdiff_t difference_type;
			typedef bool const* pointer;
			typedef bool& reference;
			typedef std::forward_iterator_tag iterator_category;

			bool operator*() { return (*byte & bit) != 0; }
			const_iterator& operator++() { inc(); return *this; }
			const_iterator operator++(int)
			{ const_iterator ret(*this); inc(); return ret; }
			const_iterator& operator--() { dec(); return *this; }
			const_iterator operator--(int)
			{ const_iterator ret(*this); dec(); return ret; }

			const_iterator(): byte(0), bit(0x80) {}
			bool operator==(const_iterator const& rhs) const
			{ return byte == rhs.byte && bit == rhs.bit; }

			bool operator!=(const_iterator const& rhs) const
			{ return byte != rhs.byte || bit != rhs.bit; }

		private:
			void inc()
			{
				TORRENT_ASSERT(byte);
				if (bit == 0x01)
				{
					bit = 0x80;
					++byte;
				}
				else
				{
					bit >>= 1;
				}
			}
			void dec()
			{
				TORRENT_ASSERT(byte);
				if (bit == 0x80)
				{
					bit = 0x01;
					--byte;
				}
				else
				{
					bit <<= 1;
				}
			}
			const_iterator(unsigned char const* ptr, int offset)
				: byte(ptr), bit(0x80 >> offset) {}
			unsigned char const* byte;
			int bit;
		};

		const_iterator begin() const { return const_iterator(m_bytes, 0); }
		const_iterator end() const { return const_iterator(m_bytes + m_size / 8, m_size & 7); }

		// set the size of the bitfield to ``bits`` length. If the bitfield is extended,
		// the new bits are initialized to ``val``.
		void resize(int bits, bool val)
		{
			int s = m_size;
			int b = m_size & 7;
			resize(bits);
			if (s >= m_size) return;
			int old_size_bytes = (s + 7) / 8;
			int new_size_bytes = (m_size + 7) / 8;
			if (val)
			{
				if (old_size_bytes && b) m_bytes[old_size_bytes - 1] |= (0xff >> b);
				if (old_size_bytes < new_size_bytes)
					std::memset(m_bytes + old_size_bytes, 0xff, new_size_bytes - old_size_bytes);
				clear_trailing_bits();
			}
			else
			{
				if (old_size_bytes < new_size_bytes)
					std::memset(m_bytes + old_size_bytes, 0x00, new_size_bytes - old_size_bytes);
			}
		}
		void resize(int bits)
		{
			TORRENT_ASSERT(bits >= 0);
			const int b = (bits + 7) / 8;
			if (m_bytes)
			{
				if (m_own)
				{
					m_bytes = (unsigned char*)std::realloc(m_bytes, b);
					m_own = true;
				}
				else if (bits > m_size)
				{
					unsigned char* tmp = (unsigned char*)std::malloc(b);
					std::memcpy(tmp, m_bytes, (std::min)(int(m_size + 7)/ 8, b));
					m_bytes = tmp;
					m_own = true;
				}
			}
			else if (bits > 0)
			{
				m_bytes = (unsigned char*)std::malloc(b);
				m_own = true;
			}
			m_size = bits;
			clear_trailing_bits();
		}

		// set all bits in the bitfield to 1 (set_all) or 0 (clear_all).
		void set_all()
		{
			std::memset(m_bytes, 0xff, (m_size + 7) / 8);
			clear_trailing_bits();
		}
		void clear_all()
		{
			std::memset(m_bytes, 0x00, (m_size + 7) / 8);
		}

		// make the bitfield empty, of zero size.
		void clear() { dealloc(); m_size = 0; }

	private:

		void clear_trailing_bits()
		{
			// clear the tail bits in the last byte
			if (m_size & 7) m_bytes[(m_size + 7) / 8 - 1] &= 0xff << (8 - (m_size & 7));
		}

		void dealloc() { if (m_own) std::free(m_bytes); m_bytes = 0; }
		unsigned char* m_bytes;
		int m_size:31; // in bits
		bool m_own:1;
	};

}

#endif // TORRENT_BITFIELD_HPP_INCLUDED

<|endoftext|>


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

  nomlib - C++11 cross-platform game engine

Copyright (c) 2013, Jeffrey Carpenter <jeffrey.carp@gmail.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:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.

******************************************************************************/
#ifndef NOMLIB_MATH_HELPERS_HPP
#define NOMLIB_MATH_HELPERS_HPP

#include <chrono>
#include <random>
#include <cmath>

#include "nomlib/config.hpp"
#include "nomlib/math/Point2-inl.hpp"

namespace nom {

extern const double PI;

/// Returns a random number between the specified start and end numbers.
int32 rand ( int32 start, int32 end );

/// Rotates a given X & Y coordinate point along a given pivot axis
/// (rotation point) at the given angle (in degrees), clockwise.
const Point2f rotate_points ( float angle, float x, float y, float pivot_x, float pivot_y );

/// ...
double round ( double number );

int abs ( int value );

} // namespace nom

#endif // include guard defined
<commit_msg>Remove abs function (this should have been with previous git commit)<commit_after>/******************************************************************************

  nomlib - C++11 cross-platform game engine

Copyright (c) 2013, Jeffrey Carpenter <jeffrey.carp@gmail.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:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.

******************************************************************************/
#ifndef NOMLIB_MATH_HELPERS_HPP
#define NOMLIB_MATH_HELPERS_HPP

#include <chrono>
#include <random>
#include <cmath>

#include "nomlib/config.hpp"
#include "nomlib/math/Point2-inl.hpp"

namespace nom {

extern const double PI;

/// Returns a random number between the specified start and end numbers.
int32 rand ( int32 start, int32 end );

/// Rotates a given X & Y coordinate point along a given pivot axis
/// (rotation point) at the given angle (in degrees), clockwise.
const Point2f rotate_points ( float angle, float x, float y, float pivot_x, float pivot_y );

/// ...
double round ( double number );

} // namespace nom

#endif // include guard defined
<|endoftext|>


<commit_before>#include "SpaceDefiner.h"

#include <cstdlib>
#include <ctime>

SpaceDefiner::SpaceDefiner()
{
//yes
}

SpaceDefiner::~SpaceDefiner()
{

}

//equation must be in terms of X
std::vector<vector3d*>* SpaceDefiner::SpaceDefine(std::string str, float start, float end, float num){
	std::vector<vector3d*>* vec = new std::vector<vector3d*>();
	equation_factory eqrf;
	equation* eqr = eqrf.vector_equation(str);
//void SpaceDefiner::Define(char input[50], struct node nodes[NODE_MAX][NODE_MAX][NODE_MAX])
//{

	float* f = new float[3];

	for(float k = start; k<end; k += (end-start)/num){
		f = eqr->eval(k,0.0f,0.0f,f);
		vector3d* v = new vector3d(f[0],f[1],f[2]);
		vec->push_back(v);
	}

	delete f;
	delete eqr;
	return vec;
}

std::vector<vector3d*>* SpaceDefiner::uv_surface(std::string str, float u_start, float u_end, float v_start, float v_end, float u_num, float v_num){
	//what we are returning
	std::vector<vector3d*>* vec = new std::vector<vector3d*>();
	//make the equation dang namit
	equation_factor eqrf;
	equation* eqr = eqrf.vector_equation(str);

	//needed when we are making vectors
	float* f = new float[3];

	//this will fill the space with a series of points which collectively will cover the surface.
	for(float uk = u_start; uk<u_end; uk += (u_end-u_start)/u_num){
		for(float vk = v_start; vk<v_end; vk += (v_end-v_start)/v_num){
			f = eqr->eval(uk,uv,0.0f,f);
			vector3d* surface_point = new vector3d(f[0], f[1], f[2]);
			vec->push_back(surface_point); //add to the list
			float mag = surface_point->magnitude();
			//creating 5 points which are closer to the origin than this surface point
			for(int i=1; i<6; i++){
				float mod = (1.0f/6.0f * i) * mag; //(1/6) because then the 6 points in a line will be 0/6, 1/6, 2/6, 3/6, 4/6, 5/6, and line point
				vector3d* interior = new vector3d(f[0] * mod, f[1] * mod, f[2] * mod);
				vec->push_back(interior); //got dem sweet, sweet points
			}

		}
	}

	//cleanup
	delete eqr;
	delete f;

	//return
	return vec;
}

//makes a prism centered at (0,0,0) with the specified number of points.
std::vector<vector3d*>* SpaceDefiner::prism(float x_length, float x_num, float y_length, float y_num, float z_length, float z_num){
	//what we are returning
	std::vector<vector3d*>* vec = new std::vector<vector3d*>();

	for(float x = (0 - x_length/2.0f); x <= (0 + x_length/2.0f); x += (x_length/x_num)){
		for(float y = (0 - y_length/2.0f); y <= (0 + y_length/2.0f); y += (y_length/y_num)){
			for(float z = (0 - z_length/2.0f); z <= (0 + z_length/2.0f); z += (z_length/z_num)){
				vector3d* v = new vector3d(x,y,z);
				vec->push_back(v);
			}

		}

	}

	//return
	return vec;
}

std::vector<vector3d*>* SpaceDefiner::prism_rand(float x_length, float x_num, float y_length, float y_num, float z_length, float z_num){
	//what we are returning
	std::vector<vector3d*>* vec = new std::vector<vector3d*>();
	srand(time(NULL));

	float xleft = 0 - x_length/2.0f;
	float yleft = 0 - y_length/2.0f;
	float zleft = 0 - z_length/2.0f;

	for(int x=0; x<x_num; ++x){
		for(int y=0; y<y_num; ++y){
			for(int z=0; z<z_num; ++z){
				float rx = xleft + ((rand() % RAND_MAX)*x_length);
				float ry = yleft + ((rand() % RAND_MAX)*y_length);
				float rz = zleft + ((rand() % RAND_MAX)*z_length);

				vector3d* v = new vector3d(rx,ry,rz);
				vec->push_back(v);
			}

		}

	}

	//return
	return vec;
}

<commit_msg>fixing space definer<commit_after>#include "SpaceDefiner.h"

#include <cstdlib>
#include <ctime>

SpaceDefiner::SpaceDefiner()
{
//yes
}

SpaceDefiner::~SpaceDefiner()
{

}

//equation must be in terms of X
std::vector<vector3d*>* SpaceDefiner::SpaceDefine(std::string str, float start, float end, float num){
	std::vector<vector3d*>* vec = new std::vector<vector3d*>();
	equation_factory eqrf;
	equation* eqr = eqrf.vector_equation(str);
//void SpaceDefiner::Define(char input[50], struct node nodes[NODE_MAX][NODE_MAX][NODE_MAX])
//{

	float* f = new float[3];

	for(float k = start; k<end; k += (end-start)/num){
		f = eqr->eval(k,0.0f,0.0f,f);
		vector3d* v = new vector3d(f[0],f[1],f[2]);
		vec->push_back(v);
	}

	delete f;
	delete eqr;
	return vec;
}

std::vector<vector3d*>* SpaceDefiner::uv_surface(std::string str, float u_start, float u_end, float v_start, float v_end, float u_num, float v_num){
	//what we are returning
	std::vector<vector3d*>* vec = new std::vector<vector3d*>();
	//make the equation dang namit
	equation_factory eqrf;
	equation* eqr = eqrf.vector_equation(str);

	//needed when we are making vectors
	float* f = new float[3];

	//this will fill the space with a series of points which collectively will cover the surface.
	for(float uk = u_start; uk<u_end; uk += (u_end-u_start)/u_num){
		for(float vk = v_start; vk<v_end; vk += (v_end-v_start)/v_num){
			f = eqr->eval(uk,vk,0.0f,f);
			vector3d* surface_point = new vector3d(f[0], f[1], f[2]);
			vec->push_back(surface_point); //add to the list
			float mag = surface_point->magnitude();
			//creating 5 points which are closer to the origin than this surface point
			for(int i=1; i<6; i++){
				float mod = (1.0f/6.0f * i) * mag; //(1/6) because then the 6 points in a line will be 0/6, 1/6, 2/6, 3/6, 4/6, 5/6, and line point
				vector3d* interior = new vector3d(f[0] * mod, f[1] * mod, f[2] * mod);
				vec->push_back(interior); //got dem sweet, sweet points
			}

		}
	}

	//cleanup
	delete eqr;
	delete f;

	//return
	return vec;
}

//makes a prism centered at (0,0,0) with the specified number of points.
std::vector<vector3d*>* SpaceDefiner::prism(float x_length, float x_num, float y_length, float y_num, float z_length, float z_num){
	//what we are returning
	std::vector<vector3d*>* vec = new std::vector<vector3d*>();

	for(float x = (0 - x_length/2.0f); x <= (0 + x_length/2.0f); x += (x_length/x_num)){
		for(float y = (0 - y_length/2.0f); y <= (0 + y_length/2.0f); y += (y_length/y_num)){
			for(float z = (0 - z_length/2.0f); z <= (0 + z_length/2.0f); z += (z_length/z_num)){
				vector3d* v = new vector3d(x,y,z);
				vec->push_back(v);
			}

		}

	}

	//return
	return vec;
}

std::vector<vector3d*>* SpaceDefiner::prism_rand(float x_length, float x_num, float y_length, float y_num, float z_length, float z_num){
	//what we are returning
	std::vector<vector3d*>* vec = new std::vector<vector3d*>();
	srand(time(NULL));

	float xleft = 0 - x_length/2.0f;
	float yleft = 0 - y_length/2.0f;
	float zleft = 0 - z_length/2.0f;

	for(int x=0; x<x_num; ++x){
		for(int y=0; y<y_num; ++y){
			for(int z=0; z<z_num; ++z){
				float rx = xleft + ((rand() % RAND_MAX)*x_length);
				float ry = yleft + ((rand() % RAND_MAX)*y_length);
				float rz = zleft + ((rand() % RAND_MAX)*z_length);

				vector3d* v = new vector3d(rx,ry,rz);
				vec->push_back(v);
			}

		}

	}

	//return
	return vec;
}

<|endoftext|>


<commit_before><commit_msg>Crash fix<commit_after><|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/workarounds/adr32s_workarounds.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file workarounds/adr32s_workarounds.H
/// @brief Workarounds for the ADR32s logic blocks
/// Workarounds are very deivce specific, so there is no attempt to generalize
/// this code in any way.
///
// *HWP HWP Owner: Stephen Glancy <sglancy@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB

#ifndef _MSS_WORKAROUNDS_ADR32S_H_
#define _MSS_WORKAROUNDS_ADR32S_H_

#include <fapi2.H>
#include <p9_mc_scom_addresses.H>
#include <p9_mc_scom_addresses_fld.H>
#include <lib/mss_attribute_accessors_manual.H>

namespace mss
{

namespace workarounds
{

namespace adr32s
{

///
/// @brief Clears the FIRs mistakenly set by the DCD calibration
/// @param[in] i_target MCBIST target on which to operate
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
/// @note Always needs to be run for DD1.* parts.  unsure for DD2
///
fapi2::ReturnCode clear_dcd_firs( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target );

///
/// @brief Perform ADR DCD calibration - Nimbus Only
/// @param[in] i_target the MCBIST (controler) to perform calibration on
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode duty_cycle_distortion_calibration( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target );

///
/// @brief Retries to clear the cal update bit, as it has been seen that the bit can be "sticky" in hardware
/// @param[in] i_target MCA target on which to operate
/// @param[in] i_reg the register on which to operate
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
fapi2::ReturnCode setup_dll_control_regs( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target, const uint64_t i_reg );

} // close namespace adr32s
} // close namespace workarounds
} // close namespace mss

#endif
<commit_msg>Update HPW Level for MSS API library<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/workarounds/adr32s_workarounds.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file workarounds/adr32s_workarounds.H
/// @brief Workarounds for the ADR32s logic blocks
/// Workarounds are very deivce specific, so there is no attempt to generalize
/// this code in any way.
///
// *HWP HWP Owner: Stephen Glancy <sglancy@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB

#ifndef _MSS_WORKAROUNDS_ADR32S_H_
#define _MSS_WORKAROUNDS_ADR32S_H_

#include <fapi2.H>
#include <p9_mc_scom_addresses.H>
#include <p9_mc_scom_addresses_fld.H>
#include <lib/mss_attribute_accessors_manual.H>

namespace mss
{

namespace workarounds
{

namespace adr32s
{

///
/// @brief Clears the FIRs mistakenly set by the DCD calibration
/// @param[in] i_target MCBIST target on which to operate
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
/// @note Always needs to be run for DD1.* parts.  unsure for DD2
///
fapi2::ReturnCode clear_dcd_firs( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target );

///
/// @brief Perform ADR DCD calibration - Nimbus Only
/// @param[in] i_target the MCBIST (controler) to perform calibration on
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode duty_cycle_distortion_calibration( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target );

///
/// @brief Retries to clear the cal update bit, as it has been seen that the bit can be "sticky" in hardware
/// @param[in] i_target MCA target on which to operate
/// @param[in] i_reg the register on which to operate
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
fapi2::ReturnCode setup_dll_control_regs( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target, const uint64_t i_reg );

} // close namespace adr32s
} // close namespace workarounds
} // close namespace mss

#endif
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qwaylandglcontext.h"

#include "qwaylanddisplay.h"
#include "qwaylandwindow.h"

#include "../../../eglconvenience/qeglconvenience.h"

#include <QtGui/QPlatformGLContext>
#include <QtGui/QPlatformWindowFormat>
#include <QtCore/QMutex>

QWaylandGLContext::QWaylandGLContext(EGLDisplay eglDisplay, const QPlatformWindowFormat &format)
    : QPlatformGLContext()
    , mEglDisplay(eglDisplay)
    , mSurface(EGL_NO_SURFACE)
    , mConfig(q_configFromQPlatformWindowFormat(mEglDisplay,format,true))
    , mFormat(qt_qPlatformWindowFormatFromConfig(mEglDisplay,mConfig))
{
    QPlatformGLContext *sharePlatformContext = 0;
    sharePlatformContext = format.sharedGLContext();
    mFormat.setSharedContext(sharePlatformContext);
    EGLContext shareEGLContext = EGL_NO_CONTEXT;
    if (sharePlatformContext)
        shareEGLContext = static_cast<const QWaylandGLContext*>(sharePlatformContext)->mContext;

    eglBindAPI(EGL_OPENGL_ES_API);

    QVector<EGLint> eglContextAttrs;
    eglContextAttrs.append(EGL_CONTEXT_CLIENT_VERSION);
    eglContextAttrs.append(2);
    eglContextAttrs.append(EGL_NONE);

    mContext = eglCreateContext(mEglDisplay, mConfig,
                                shareEGLContext, eglContextAttrs.constData());
}

QWaylandGLContext::QWaylandGLContext()
    : QPlatformGLContext()
    , mEglDisplay(0)
    , mContext(EGL_NO_CONTEXT)
    , mSurface(EGL_NO_SURFACE)
    , mConfig(0)
{ }

QWaylandGLContext::~QWaylandGLContext()
{
    eglDestroyContext(mEglDisplay,mContext);
}

void QWaylandGLContext::makeCurrent()
{
    QPlatformGLContext::makeCurrent();
    if (mSurface == EGL_NO_SURFACE) {
        qWarning("makeCurrent with EGL_NO_SURFACE");
    }
    eglMakeCurrent(mEglDisplay, mSurface, mSurface, mContext);
}

void QWaylandGLContext::doneCurrent()
{
    QPlatformGLContext::doneCurrent();
    eglMakeCurrent(mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
}

void QWaylandGLContext::swapBuffers()
{
    eglSwapBuffers(mEglDisplay,mSurface);
}

void *QWaylandGLContext::getProcAddress(const QString &string)
{
    return (void *) eglGetProcAddress(string.toLatin1().data());
}

void QWaylandGLContext::setEglSurface(EGLSurface surface)
{
    doneCurrent();
    mSurface = surface;
}

EGLConfig QWaylandGLContext::eglConfig() const
{
    return mConfig;
}

<commit_msg>We need to let the currentContext be in the same state after<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qwaylandglcontext.h"

#include "qwaylanddisplay.h"
#include "qwaylandwindow.h"

#include "../../../eglconvenience/qeglconvenience.h"

#include <QtGui/QPlatformGLContext>
#include <QtGui/QPlatformWindowFormat>
#include <QtCore/QMutex>

QWaylandGLContext::QWaylandGLContext(EGLDisplay eglDisplay, const QPlatformWindowFormat &format)
    : QPlatformGLContext()
    , mEglDisplay(eglDisplay)
    , mSurface(EGL_NO_SURFACE)
    , mConfig(q_configFromQPlatformWindowFormat(mEglDisplay,format,true))
    , mFormat(qt_qPlatformWindowFormatFromConfig(mEglDisplay,mConfig))
{
    QPlatformGLContext *sharePlatformContext = 0;
    sharePlatformContext = format.sharedGLContext();
    mFormat.setSharedContext(sharePlatformContext);
    EGLContext shareEGLContext = EGL_NO_CONTEXT;
    if (sharePlatformContext)
        shareEGLContext = static_cast<const QWaylandGLContext*>(sharePlatformContext)->mContext;

    eglBindAPI(EGL_OPENGL_ES_API);

    QVector<EGLint> eglContextAttrs;
    eglContextAttrs.append(EGL_CONTEXT_CLIENT_VERSION);
    eglContextAttrs.append(2);
    eglContextAttrs.append(EGL_NONE);

    mContext = eglCreateContext(mEglDisplay, mConfig,
                                shareEGLContext, eglContextAttrs.constData());
}

QWaylandGLContext::QWaylandGLContext()
    : QPlatformGLContext()
    , mEglDisplay(0)
    , mContext(EGL_NO_CONTEXT)
    , mSurface(EGL_NO_SURFACE)
    , mConfig(0)
{ }

QWaylandGLContext::~QWaylandGLContext()
{
    eglDestroyContext(mEglDisplay,mContext);
}

void QWaylandGLContext::makeCurrent()
{
    QPlatformGLContext::makeCurrent();
    if (mSurface == EGL_NO_SURFACE) {
        qWarning("makeCurrent with EGL_NO_SURFACE");
    }
    eglMakeCurrent(mEglDisplay, mSurface, mSurface, mContext);
}

void QWaylandGLContext::doneCurrent()
{
    QPlatformGLContext::doneCurrent();
    eglMakeCurrent(mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
}

void QWaylandGLContext::swapBuffers()
{
    eglSwapBuffers(mEglDisplay,mSurface);
}

void *QWaylandGLContext::getProcAddress(const QString &string)
{
    return (void *) eglGetProcAddress(string.toLatin1().data());
}

void QWaylandGLContext::setEglSurface(EGLSurface surface)
{
    bool wasCurrent = false;
    if (QPlatformGLContext::currentContext() == this) {
        wasCurrent = true;
        doneCurrent();
    }
    mSurface = surface;
    if (wasCurrent) {
        makeCurrent();
    }
}

EGLConfig QWaylandGLContext::eglConfig() const
{
    return mConfig;
}

<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads

// <thread>

// class thread

// template <class F, class ...Args> thread(F&& f, Args&&... args);

#include <thread>
#include <new>
#include <cstdlib>
#include <cassert>

unsigned throw_one = 0xFFFF;

void* operator new(std::size_t s) throw(std::bad_alloc)
{
    if (throw_one == 0)
        throw std::bad_alloc();
    --throw_one;
    return std::malloc(s);
}

void  operator delete(void* p) throw()
{
    std::free(p);
}

bool f_run = false;

void f()
{
    f_run = true;
}

class G
{
    int alive_;
public:
    static int n_alive;
    static bool op_run;

    G() : alive_(1) {++n_alive;}
    G(const G& g) : alive_(g.alive_) {++n_alive;}
    ~G() {alive_ = 0; --n_alive;}

    void operator()()
    {
        assert(alive_ == 1);
        assert(n_alive >= 1);
        op_run = true;
    }

    void operator()(int i, double j)
    {
        assert(alive_ == 1);
        assert(n_alive >= 1);
        assert(i == 5);
        assert(j == 5.5);
        op_run = true;
    }
};

int G::n_alive = 0;
bool G::op_run = false;

#ifndef _LIBCPP_HAS_NO_VARIADICS

class MoveOnly
{
    MoveOnly(const MoveOnly&);
public:
    MoveOnly() {}
    MoveOnly(MoveOnly&&) {}

    void operator()(MoveOnly&&)
    {
    }
};

#endif

int main()
{
    {
        std::thread t(f);
        t.join();
        assert(f_run == true);
    }
    f_run = false;
    {
        try
        {
            throw_one = 0;
            std::thread t(f);
            assert(false);
        }
        catch (...)
        {
            throw_one = 0xFFFF;
            assert(!f_run);
        }
    }
    {
        assert(G::n_alive == 0);
        assert(!G::op_run);
        std::thread t((G()));
        t.join();
        assert(G::n_alive == 0);
        assert(G::op_run);
    }
    G::op_run = false;
    {
        try
        {
            throw_one = 0;
            assert(G::n_alive == 0);
            assert(!G::op_run);
            std::thread t((G()));
            assert(false);
        }
        catch (...)
        {
            throw_one = 0xFFFF;
            assert(G::n_alive == 0);
            assert(!G::op_run);
        }
    }
#ifndef _LIBCPP_HAS_NO_VARIADICS
    {
        assert(G::n_alive == 0);
        assert(!G::op_run);
        std::thread t(G(), 5, 5.5);
        t.join();
        assert(G::n_alive == 0);
        assert(G::op_run);
    }
    {
        std::thread t = std::thread(MoveOnly(), MoveOnly());
        t.join();
    }
#endif  // _LIBCPP_HAS_NO_VARIADICS
}
<commit_msg>Mark another test as UNSUPPORTED with ASAN and MSAN<commit_after>//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads

// <thread>

// class thread

// template <class F, class ...Args> thread(F&& f, Args&&... args);

// UNSUPPORTED: asan, msan

#include <thread>
#include <new>
#include <cstdlib>
#include <cassert>

unsigned throw_one = 0xFFFF;

void* operator new(std::size_t s) throw(std::bad_alloc)
{
    if (throw_one == 0)
        throw std::bad_alloc();
    --throw_one;
    return std::malloc(s);
}

void  operator delete(void* p) throw()
{
    std::free(p);
}

bool f_run = false;

void f()
{
    f_run = true;
}

class G
{
    int alive_;
public:
    static int n_alive;
    static bool op_run;

    G() : alive_(1) {++n_alive;}
    G(const G& g) : alive_(g.alive_) {++n_alive;}
    ~G() {alive_ = 0; --n_alive;}

    void operator()()
    {
        assert(alive_ == 1);
        assert(n_alive >= 1);
        op_run = true;
    }

    void operator()(int i, double j)
    {
        assert(alive_ == 1);
        assert(n_alive >= 1);
        assert(i == 5);
        assert(j == 5.5);
        op_run = true;
    }
};

int G::n_alive = 0;
bool G::op_run = false;

#ifndef _LIBCPP_HAS_NO_VARIADICS

class MoveOnly
{
    MoveOnly(const MoveOnly&);
public:
    MoveOnly() {}
    MoveOnly(MoveOnly&&) {}

    void operator()(MoveOnly&&)
    {
    }
};

#endif

int main()
{
    {
        std::thread t(f);
        t.join();
        assert(f_run == true);
    }
    f_run = false;
    {
        try
        {
            throw_one = 0;
            std::thread t(f);
            assert(false);
        }
        catch (...)
        {
            throw_one = 0xFFFF;
            assert(!f_run);
        }
    }
    {
        assert(G::n_alive == 0);
        assert(!G::op_run);
        std::thread t((G()));
        t.join();
        assert(G::n_alive == 0);
        assert(G::op_run);
    }
    G::op_run = false;
    {
        try
        {
            throw_one = 0;
            assert(G::n_alive == 0);
            assert(!G::op_run);
            std::thread t((G()));
            assert(false);
        }
        catch (...)
        {
            throw_one = 0xFFFF;
            assert(G::n_alive == 0);
            assert(!G::op_run);
        }
    }
#ifndef _LIBCPP_HAS_NO_VARIADICS
    {
        assert(G::n_alive == 0);
        assert(!G::op_run);
        std::thread t(G(), 5, 5.5);
        t.join();
        assert(G::n_alive == 0);
        assert(G::op_run);
    }
    {
        std::thread t = std::thread(MoveOnly(), MoveOnly());
        t.join();
    }
#endif  // _LIBCPP_HAS_NO_VARIADICS
}
<|endoftext|>


<commit_before>/*
T0 DA for online calibration

Contact: Alla.Maevskaya@cern.ch
Run Type: AMPLITUDE_CALIBRATION
DA Type: MON
Number of events needed: 5000
Input Files: inLaser.dat, external parameters
Output Files: daLaser.root, to be exported to the DAQ FXS
Trigger types used: CALIBRATION_EVENT

*/

#define FILE_OUT "daLaser.root"
#define FILE_IN "inLaser.dat"
#include <daqDA.h>
#include <event.h>
#include <monitor.h>

#include <Riostream.h>
#include <stdio.h>
#include <stdlib.h>

//AliRoot
#include <AliRawReaderDate.h>
#include <AliRawReader.h>
#include <AliT0RawReader.h>

//ROOT
#include "TROOT.h"
#include "TPluginManager.h"
#include "TFile.h"
#include "TKey.h"
#include "TH2S.h"
#include "TObject.h"
#include "TBenchmark.h"
#include "TRandom.h"
#include "TMath.h"
#include "TCanvas.h"
#include "TString.h"
#include "TH1.h"
#include "TF1.h"
#include "TSpectrum.h"
#include "TVirtualFitter.h"
//AMORE
//
#ifdef ALI_AMORE
#include <AmoreDA.h>
#endif

float lcfd, hcfd;
/* Main routine
      Arguments:
      1- monitoring data source
*/
int main(int argc, char **argv) {
  int status;

  /* magic line */
  gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo",
					"*",
					"TStreamerInfo",
					"RIO",
					"TStreamerInfo()");

  Int_t nEntries = daqDA_ECS_getTotalIteration(); // usually = 11 = Nb of calibration runs
 cout<<" nEntries "<<nEntries<<endl;
 Int_t nInit=1;  // = 0 all DAC values ; = 1 DAC=0 excluded (default=1)
  // Reading current iteration
  Int_t nIndex = daqDA_ECS_getCurrentIteration();
  if(nIndex<0 || nIndex>nEntries) {printf("\n Failed: nIndex = %d\n",nIndex); return -1 ;}

// decode the input line
  if (argc!=2) {
    printf("Wrong number of arguments\n");
    return -1;
  }

  Float_t mipsin[20];
   if(daqDA_DB_getFile(FILE_IN, FILE_IN)){
     printf("Couldn't get input file >>inLaser.dat<< from DAQ_DB !!!\n");
     return -1;
  }

  ifstream filein(FILE_IN,ios::in);
  Int_t k=0;
  while (k<nEntries ) {
    filein >>mipsin[k] ;
    cout<<" "<<mipsin[k]<<endl;
    k++; }
  filein>>lcfd;
  filein>>hcfd;
  filein.close();

  /*
  if (argc!=2) {
    printf("Wrong number of arguments\n");
    return -1;
  }
  */

  // Char_t inputFile[256]="";

  /* define data source : this is argument 1 */
  status=monitorSetDataSource( argv[1] );
  if (status!=0) {
    printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
    return -1;
  }

  /* declare monitoring program */
  status=monitorDeclareMp( __FILE__ );
  if (status!=0) {
    printf("monitorDeclareMp() failed : %s\n",monitorDecodeError(status));
    return -1;
  }

  /* define wait event timeout - 1s max */
  monitorSetNowait();
  monitorSetNoWaitNetworkTimeout(1000);

  /* log start of process */
  printf("T0 monitoring program started\n");

  // Allocation of histograms - start

  TH1F *hQTC[24];  TH1F *hLED[24]; TH1F *hCFD[24];
  printf(" CFD low limit %f high %f",lcfd, hcfd);

  for(Int_t ic=0; ic<24; ic++)
    {
      hQTC[ic] = new TH1F(Form("hQTC%d_%d",ic+1,nIndex),"QTC",1000, 500, 4500);
      hLED[ic] = new TH1F(Form("hLED%d_%d",ic+1,nIndex),"LED",300,300,600);
      hCFD[ic] = new TH1F(Form("hCFD%d_%d",ic+1,nIndex),"CFD", Int_t ((hcfd-lcfd)/2), lcfd, hcfd);
    }

  // Allocation of histograms - end

  // Reading current iteration

  Int_t iev=0;

  /* main loop (infinite) */
  for(;;) {
    struct eventHeaderStruct *event;
    eventTypeType eventT;

    /* check shutdown condition */
    if (daqDA_checkShutdown()) {break;}

    /* get next event (blocking call until timeout) */
    status=monitorGetEventDynamic((void **)&event);
    if (status==(int)MON_ERR_EOF) {
      printf ("End of File detected\n");
      break; /* end of monitoring file has been reached */
    }

    if (status!=0) {
      printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
      break;
    }

    /* retry if got no event */
    if (event==NULL) {
      continue;
    }

    /* use event - here, just write event id to result file */
    eventT=event->eventType;

    switch (event->eventType){

    case START_OF_RUN:
      break;

    case END_OF_RUN:
      break;

    case CALIBRATION_EVENT:
      //      case PHYSICS_EVENT:
      iev++;

      if(iev==1) printf("First event  %i\n",iev);

      // Initalize raw-data reading and decoding
      AliRawReader *reader = new AliRawReaderDate((void*)event);

      // Enable the following two lines in case of real-data
      reader->RequireHeader(kTRUE);
      AliT0RawReader *start = new AliT0RawReader(reader, kTRUE);

      // Read raw data
      Int_t allData[106][5];
      for(Int_t i0=0;i0<106;i0++)
      	for(Int_t j0=0;j0<5;j0++)
		allData[i0][j0] = 0;

      if(start->Next()){
        for (Int_t i=0; i<106; i++) {
	  for(Int_t iHit=0;iHit<5;iHit++){
	    allData[i][iHit]= start->GetData(i,iHit);
	  }
        }
      }
      else
	printf("No data for T0 found!!!\n");

      // Fill the histograms

      for (Int_t ik = 0; ik<24; ik+=2)
	{
	  Int_t cc = ik/2;
	  if(allData[ik+25][0]>0 && allData[ik+26][0]>0)
	    hQTC[cc]->Fill((allData[ik+25][0]-allData[ik+26][0]));
	  if(allData[cc+13][0]>0 && allData[cc+1][0]>0)
	    hLED[cc]->Fill(allData[cc+13][0]-allData[cc+1][0]);
	  if(allData[cc+1][0] > 0) hCFD[cc]->Fill(allData[cc+1][0]);
	  //	  printf("%i %i CFD %i LED_CFD %i\n",
	  //	  ik,cc,allData[cc+1][0],allData[cc+1][0]);

	}

      for (Int_t ik = 24; ik<48; ik+=2)
	{
	  Int_t cc = ik/2;
	   if(allData[ik+57][0]>0 && allData[ik+58][0]>0 && allData[cc+45][0]>0)
	     hQTC[cc]->Fill(allData[ik+57][0]-allData[ik+58][0]);

	   if(allData[cc+57][0]>0 && allData[cc+45][0]>0)
	     hLED[cc]->Fill(allData[cc+57][0]-allData[cc+45][0]);
	   if(allData[cc+45][0] > 0) hCFD[cc]->Fill(allData[cc+45][0]);
	   //  printf("%i %i CFD %i LED_CFD %i\n",
	   //  ik,cc,allData[cc+45][0],allData[cc+45][0]);

	}

      delete start;
      start = 0x0;
      delete reader;
      reader= 0x0;
      // End of fill histograms

    }

    /* free resources */
    free(event);

    /* exit when last event received, no need to wait for TERM signal */
    if (eventT==END_OF_RUN) {
      printf("EOR event detected\n");
      printf("Number of events processed - %i\n ",iev);
      break;
    }
  }

  printf("After loop, before writing histos\n");
  TH1F* hAmp = new TH1F("hAmpLaser"," Laser amplitude ", 1000, 0.5, 10.5);
  for(Int_t k=0; k<nEntries; k++)   hAmp->Fill(mipsin[k]);
  // write a file with the histograms
  TFile *hist=0;
  if(nIndex == 1 )
    hist = new TFile(FILE_OUT,"RECREATE");
  else
    hist = new TFile(FILE_OUT,"UPDATE");
  hist->cd();

  for(Int_t j=0;j<24;j++)
    {
      if(hQTC[j]->GetEntries()>0) hQTC[j]->Write();
      if(hLED[j]->GetEntries()>0) hLED[j]->Write();
      if(hCFD[j]->GetEntries()>0) hCFD[j]->Write();
    }
  hAmp->Write();

  hist->Close();
  delete hist;

  status=0;

  /* export file to FXS */
  if (daqDA_FES_storeFile(FILE_OUT, "AMPLITUDE_CALIBRATION")) {
    status=-2;
  }

  return status;
}

<commit_msg>amplitude calibration up to 20MIPs<commit_after>/*
T0 DA for online calibration

Contact: Alla.Maevskaya@cern.ch
Run Type: AMPLITUDE_CALIBRATION
DA Type: MON
Number of events needed: 5000
Input Files: inLaser.dat, external parameters
Output Files: daLaser.root, to be exported to the DAQ FXS
Trigger types used: CALIBRATION_EVENT

*/

#define FILE_OUT "daLaser.root"
#define FILE_IN "inLaser.dat"
#include <daqDA.h>
#include <event.h>
#include <monitor.h>

#include <Riostream.h>
#include <stdio.h>
#include <stdlib.h>

//AliRoot
#include <AliRawReaderDate.h>
#include <AliRawReader.h>
#include <AliT0RawReader.h>

//ROOT
#include "TROOT.h"
#include "TPluginManager.h"
#include "TFile.h"
#include "TKey.h"
#include "TH2S.h"
#include "TObject.h"
#include "TBenchmark.h"
#include "TRandom.h"
#include "TMath.h"
#include "TCanvas.h"
#include "TString.h"
#include "TH1.h"
#include "TF1.h"
#include "TSpectrum.h"
#include "TVirtualFitter.h"
//AMORE
//
#ifdef ALI_AMORE
#include <AmoreDA.h>
#endif

float lcfd, hcfd;
/* Main routine
      Arguments:
      1- monitoring data source
*/
int main(int argc, char **argv) {
  int status;

  /* magic line */
  gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo",
					"*",
					"TStreamerInfo",
					"RIO",
					"TStreamerInfo()");

  Int_t nEntries = daqDA_ECS_getTotalIteration(); // usually = 11 = Nb of calibration runs
 cout<<" nEntries "<<nEntries<<endl;
 Int_t nInit=1;  // = 0 all DAC values ; = 1 DAC=0 excluded (default=1)
  // Reading current iteration
  Int_t nIndex = daqDA_ECS_getCurrentIteration();
  if(nIndex<0 || nIndex>nEntries) {printf("\n Failed: nIndex = %d\n",nIndex); return -1 ;}

// decode the input line
  if (argc!=2) {
    printf("Wrong number of arguments\n");
    return -1;
  }

  Float_t mipsin[20];
   if(daqDA_DB_getFile(FILE_IN, FILE_IN)){
     printf("Couldn't get input file >>inLaser.dat<< from DAQ_DB !!!\n");
     return -1;
  }

  ifstream filein(FILE_IN,ios::in);
  Int_t k=0;
  while (k<nEntries ) {
    filein >>mipsin[k] ;
    cout<<" "<<mipsin[k]<<endl;
    k++; }
  filein>>lcfd;
  filein>>hcfd;
  filein.close();

  /*
  if (argc!=2) {
    printf("Wrong number of arguments\n");
    return -1;
  }
  */

  // Char_t inputFile[256]="";

  /* define data source : this is argument 1 */
  status=monitorSetDataSource( argv[1] );
  if (status!=0) {
    printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
    return -1;
  }

  /* declare monitoring program */
  status=monitorDeclareMp( __FILE__ );
  if (status!=0) {
    printf("monitorDeclareMp() failed : %s\n",monitorDecodeError(status));
    return -1;
  }

  /* define wait event timeout - 1s max */
  monitorSetNowait();
  monitorSetNoWaitNetworkTimeout(1000);

  /* log start of process */
  printf("T0 monitoring program started\n");

  // Allocation of histograms - start

  TH1F *hQTC[24];  TH1F *hLED[24]; TH1F *hCFD[24];
  printf(" CFD low limit %f high %f",lcfd, hcfd);

  for(Int_t ic=0; ic<24; ic++)
    {
      hQTC[ic] = new TH1F(Form("hQTC%d_%d",ic+1,nIndex),"QTC",1000, 500, 4500);
      hLED[ic] = new TH1F(Form("hLED%d_%d",ic+1,nIndex),"LED",300,300,600);
      hCFD[ic] = new TH1F(Form("hCFD%d_%d",ic+1,nIndex),"CFD", Int_t ((hcfd-lcfd)/2), lcfd, hcfd);
    }

  // Allocation of histograms - end

  // Reading current iteration

  Int_t iev=0;

  /* main loop (infinite) */
  for(;;) {
    struct eventHeaderStruct *event;
    eventTypeType eventT;

    /* check shutdown condition */
    if (daqDA_checkShutdown()) {break;}

    /* get next event (blocking call until timeout) */
    status=monitorGetEventDynamic((void **)&event);
    if (status==(int)MON_ERR_EOF) {
      printf ("End of File detected\n");
      break; /* end of monitoring file has been reached */
    }

    if (status!=0) {
      printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
      break;
    }

    /* retry if got no event */
    if (event==NULL) {
      continue;
    }

    /* use event - here, just write event id to result file */
    eventT=event->eventType;

    switch (event->eventType){

    case START_OF_RUN:
      break;

    case END_OF_RUN:
      break;

    case CALIBRATION_EVENT:
      //      case PHYSICS_EVENT:
      iev++;

      if(iev==1) printf("First event  %i\n",iev);

      // Initalize raw-data reading and decoding
      AliRawReader *reader = new AliRawReaderDate((void*)event);

      // Enable the following two lines in case of real-data
      reader->RequireHeader(kTRUE);
      AliT0RawReader *start = new AliT0RawReader(reader, kTRUE);

      // Read raw data
      Int_t allData[106][5];
      for(Int_t i0=0;i0<106;i0++)
      	for(Int_t j0=0;j0<5;j0++)
		allData[i0][j0] = 0;

      if(start->Next()){
        for (Int_t i=0; i<106; i++) {
	  for(Int_t iHit=0;iHit<5;iHit++){
	    allData[i][iHit]= start->GetData(i,iHit);
	  }
        }
      }
      else
	printf("No data for T0 found!!!\n");

      // Fill the histograms

      for (Int_t ik = 0; ik<24; ik+=2)
	{
	  Int_t cc = ik/2;
	  if(allData[ik+25][0]>0 && allData[ik+26][0]>0)
	    hQTC[cc]->Fill((allData[ik+25][0]-allData[ik+26][0]));
	  if(allData[cc+13][0]>0 && allData[cc+1][0]>0)
	    hLED[cc]->Fill(allData[cc+13][0]-allData[cc+1][0]);
	  if(allData[cc+1][0] > 0) hCFD[cc]->Fill(allData[cc+1][0]);
	  //	  printf("%i %i CFD %i LED_CFD %i\n",
	  //	  ik,cc,allData[cc+1][0],allData[cc+1][0]);

	}

      for (Int_t ik = 24; ik<48; ik+=2)
	{
	  Int_t cc = ik/2;
	   if(allData[ik+57][0]>0 && allData[ik+58][0]>0 && allData[cc+45][0]>0)
	     hQTC[cc]->Fill(allData[ik+57][0]-allData[ik+58][0]);

	   if(allData[cc+57][0]>0 && allData[cc+45][0]>0)
	     hLED[cc]->Fill(allData[cc+57][0]-allData[cc+45][0]);
	   if(allData[cc+45][0] > 0) hCFD[cc]->Fill(allData[cc+45][0]);
	   //  printf("%i %i CFD %i LED_CFD %i\n",
	   //  ik,cc,allData[cc+45][0],allData[cc+45][0]);

	}

      delete start;
      start = 0x0;
      delete reader;
      reader= 0x0;
      // End of fill histograms

    }

    /* free resources */
    free(event);

    /* exit when last event received, no need to wait for TERM signal */
    if (eventT==END_OF_RUN) {
      printf("EOR event detected\n");
      printf("Number of events processed - %i\n ",iev);
      break;
    }
  }

  printf("After loop, before writing histos\n");
  TH1F* hAmp = new TH1F("hAmpLaser"," Laser amplitude ", 1000, 0.5, 20.5);
  for(Int_t k=0; k<nEntries; k++)   hAmp->Fill(mipsin[k]);
  // write a file with the histograms
  TFile *hist=0;
  if(nIndex == 1 )
    hist = new TFile(FILE_OUT,"RECREATE");
  else
    hist = new TFile(FILE_OUT,"UPDATE");
  hist->cd();

  for(Int_t j=0;j<24;j++)
    {
      if(hQTC[j]->GetEntries()>0) hQTC[j]->Write();
      if(hLED[j]->GetEntries()>0) hLED[j]->Write();
      if(hCFD[j]->GetEntries()>0) hCFD[j]->Write();
    }
  hAmp->Write();

  hist->Close();
  delete hist;

  status=0;

  /* export file to FXS */
  if (daqDA_FES_storeFile(FILE_OUT, "AMPLITUDE_CALIBRATION")) {
    status=-2;
  }

  return status;
}

<|endoftext|>


<commit_before>/*-----------------------------------------------------------------------------
 This source file is part of Hopsan NG

 Copyright (c) 2011
    Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson,
    Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack

 This file is provided "as is", with no guarantee or warranty for the
 functionality or reliability of the contents. All contents in this file is
 the original work of the copyright holders at the Division of Fluid and
 Mechatronic Systems (Flumes) at Linköping University. Modifying, using or
 redistributing any part of this file is prohibited without explicit
 permission from the copyright holders.
-----------------------------------------------------------------------------*/

//!
//! @file   MechanicRotationalInterfaceQ.hpp
//! @author Robert Braun <robert.braun@liu.se>
//! @date   2011-05-30
//!
//! @brief Contains a rotational mechanic interface component of Q-type
//!
//$Id$

#ifndef MECHANICROTATIONALINTERFACEQ_HPP_INCLUDED
#define MECHANICROTATIONALINTERFACEQ_HPP_INCLUDED

#include "../../ComponentEssentials.h"
#include "../../ComponentUtilities.h"

namespace hopsan {

    //!
    //! @brief
    //! @ingroup MechanicalComponents
    //!
    class MechanicRotationalInterfaceQ : public ComponentQ
    {

    private:
        Port *mpP1;

    public:
        static Component *Creator()
        {
            return new MechanicRotationalInterfaceQ("RotationalInterfaceQ");
        }

        MechanicRotationalInterfaceQ(const std::string name) : ComponentQ(name)
        {
            mpP1 = addPowerPort("P1", "NodeMechanicRotational");
        }

        void initialize()
        {
            //Interfacing is handled through readnode/writenode from the RT wrapper file
        }

        void simulateOneTimestep()
        {
            //Interfacing is handled through readnode/writenode from the RT wrapper file
        }
    };
}

#endif // MECHANICROTATIONALINTERFACEQ_HPP_INCLUDED

<commit_msg>Added torque calculation in q-type rotational interface component<commit_after>/*-----------------------------------------------------------------------------
 This source file is part of Hopsan NG

 Copyright (c) 2011
    Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson,
    Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack

 This file is provided "as is", with no guarantee or warranty for the
 functionality or reliability of the contents. All contents in this file is
 the original work of the copyright holders at the Division of Fluid and
 Mechatronic Systems (Flumes) at Linköping University. Modifying, using or
 redistributing any part of this file is prohibited without explicit
 permission from the copyright holders.
-----------------------------------------------------------------------------*/

//!
//! @file   MechanicRotationalInterfaceQ.hpp
//! @author Robert Braun <robert.braun@liu.se>
//! @date   2011-05-30
//!
//! @brief Contains a rotational mechanic interface component of Q-type
//!
//$Id$

#ifndef MECHANICROTATIONALINTERFACEQ_HPP_INCLUDED
#define MECHANICROTATIONALINTERFACEQ_HPP_INCLUDED

#include "../../ComponentEssentials.h"
#include "../../ComponentUtilities.h"

namespace hopsan {

    //!
    //! @brief
    //! @ingroup MechanicalComponents
    //!
    class MechanicRotationalInterfaceQ : public ComponentQ
    {

    private:
        Port *mpP1;
        double *mpND_t, *mpND_w, *mpND_c, *mpND_Zx;

    public:
        static Component *Creator()
        {
            return new MechanicRotationalInterfaceQ("RotationalInterfaceQ");
        }

        MechanicRotationalInterfaceQ(const std::string name) : ComponentQ(name)
        {
            mpP1 = addPowerPort("P1", "NodeMechanicRotational");
        }

        void initialize()
        {
            mpND_t = getSafeNodeDataPtr(mpP1, NodeMechanicRotational::TORQUE);
            mpND_w = getSafeNodeDataPtr(mpP1, NodeMechanicRotational::ANGULARVELOCITY);
            mpND_c = getSafeNodeDataPtr(mpP1, NodeMechanicRotational::WAVEVARIABLE);
            mpND_Zx = getSafeNodeDataPtr(mpP1, NodeMechanicRotational::CHARIMP);
        }

        void simulateOneTimestep()
        {
            //! @todo If this works, do same in other Q-type interface components

            //Calculate torque from c and Zx
            double w = (*mpND_w);
            double c = (*mpND_c);
            double Zx = (*mpND_Zx);

            (*mpND_t) = c + Zx*w;
        }
    };
}

#endif // MECHANICROTATIONALINTERFACEQ_HPP_INCLUDED

<|endoftext|>