<commit_before>/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2009-2014 Klaus Post
    Copyright (C) 2017 Axel Waggershauser

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

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/

#include "common/DngOpcodes.h"
#include "common/Common.h"                // for uint32, ushort16, make_unique
#include "common/Point.h"                 // for iPoint2D, iRectangle2D
#include "common/RawImage.h"              // for RawImage, RawImageData
#include "decoders/RawDecoderException.h" // for RawDecoderException (ptr o...
#include "io/ByteStream.h"                // for ByteStream
#include "io/Endianness.h"                // for getHostEndianness, Endiann...
#include "tiff/TiffEntry.h"               // for TiffEntry
#include <algorithm>                      // for fill_n
#include <cmath>                          // for pow

using std::vector;
using std::fill_n;

namespace rawspeed {

class DngOpcodes::DngOpcode {
public:
  virtual ~DngOpcode() = default;

  // Will be called once before processing.
  // Can be used for preparing pre-calculated values, etc.
  virtual void setup(const RawImage& ri) {
    // NOP by default. child class shall override this if needed.
  }

  // Will be called for actual processing.
  virtual void apply(RawImage& ri) = 0;
};

// ****************************************************************************

class DngOpcodes::FixBadPixelsConstant final : public DngOpcodes::DngOpcode {
  uint32 value;

public:
  explicit FixBadPixelsConstant(ByteStream& bs) {
    value = bs.getU32();
    bs.getU32(); // Bayer Phase not used
  }

  void setup(const RawImage& ri) override {
    // These limitations are present within the DNG SDK as well.
    if (ri->getDataType() != TYPE_USHORT16)
      ThrowRDE("Only 16 bit images supported");

    if (ri->getCpp() > 1)
      ThrowRDE("Only 1 component images supported");
  }

  void apply(RawImage& ri) override {
    iPoint2D crop = ri->getCropOffset();
    uint32 offset = crop.x | (crop.y << 16);
    for (auto y = 0; y < ri->dim.y; ++y) {
      auto* src = reinterpret_cast<ushort16*>(ri->getData(0, y));
      for (auto x = 0; x < ri->dim.x; ++x) {
        if (src[x] == value)
          ri->mBadPixelPositions.push_back(offset + (y << 16 | x));
      }
    }
  }
};

// ****************************************************************************

class DngOpcodes::FixBadPixelsList final : public DngOpcodes::DngOpcode {
  std::vector<uint32> badPixels;

public:
  explicit FixBadPixelsList(ByteStream& bs) {
    bs.getU32(); // Skip phase - we don't care
    auto badPointCount = bs.getU32();
    auto badRectCount = bs.getU32();

    // Read points
    for (auto i = 0U; i < badPointCount; ++i) {
      auto y = bs.getU32();
      auto x = bs.getU32();
      badPixels.push_back(y << 16 | x);
    }

    // Read rects
    for (auto i = 0U; i < badRectCount; ++i) {
      auto top = bs.getU32();
      auto left = bs.getU32();
      auto bottom = bs.getU32();
      auto right = bs.getU32();
      for (auto y = top; y <= bottom; ++y) {
        for (auto x = left; x <= right; ++x) {
          badPixels.push_back(y << 16 | x);
        }
      }
    }
  }

  void apply(RawImage& ri) override {
    ri->mBadPixelPositions.insert(ri->mBadPixelPositions.begin(),
                                  badPixels.begin(), badPixels.end());
  }
};

// ****************************************************************************

class DngOpcodes::ROIOpcode : public DngOpcodes::DngOpcode {
protected:
  uint32 top, left, bottom, right;

  explicit ROIOpcode(ByteStream& bs) {
    top = bs.getU32();
    left = bs.getU32();
    bottom = bs.getU32();
    right = bs.getU32();
  }

  void setup(const RawImage& ri) override {
    iRectangle2D roi(left, top, right - left, bottom - top);
    iRectangle2D fullImage(0, 0, ri->dim.x, ri->dim.y);

    if (!roi.isThisInside(fullImage))
      ThrowRDE("Area of interest not inside image.");
  }
};

// ****************************************************************************

class DngOpcodes::TrimBounds final : public ROIOpcode {
public:
  explicit TrimBounds(ByteStream& bs) : ROIOpcode(bs) {}

  void apply(RawImage& ri) override {
    ri->subFrame(iRectangle2D(left, top, right - left, bottom - top));
  }
};

// ****************************************************************************

class DngOpcodes::PixelOpcode : public ROIOpcode {
protected:
  uint32 firstPlane, planes, rowPitch, colPitch;

  explicit PixelOpcode(ByteStream& bs) : ROIOpcode(bs) {
    firstPlane = bs.getU32();
    planes = bs.getU32();
    rowPitch = bs.getU32();
    colPitch = bs.getU32();

    if (planes == 0)
      ThrowRDE("Zero planes");
    if (rowPitch == 0 || colPitch == 0)
      ThrowRDE("Invalid pitch");
  }

  void setup(const RawImage& ri) override {
    ROIOpcode::setup(ri);
    if (firstPlane + planes > ri->getCpp())
      ThrowRDE("Not that many planes in actual image");
  }

  // traverses the current ROI and applies the operation OP to each pixel,
  // i.e. each pixel value v is replaced by op(x, y, v), where x/y are the
  // coordinates of the pixel value v.
  template <typename T, typename OP> void applyOP(RawImage& ri, OP op) {
    int cpp = ri->getCpp();
    for (auto y = top; y < bottom; y += rowPitch) {
      auto* src = reinterpret_cast<T*>(ri->getData(0, y));
      // Add offset, so this is always first plane
      src += firstPlane;
      for (auto x = left; x < right; x += colPitch) {
        for (auto p = 0U; p < planes; ++p)
          src[x * cpp + p] = op(x, y, src[x * cpp + p]);
      }
    }
  }
};

// ****************************************************************************

class DngOpcodes::LookupOpcode : public PixelOpcode {
protected:
  vector<ushort16> lookup;

  explicit LookupOpcode(ByteStream& bs) : PixelOpcode(bs), lookup(65536) {}

  void setup(const RawImage& ri) override {
    PixelOpcode::setup(ri);
    if (ri->getDataType() != TYPE_USHORT16)
      ThrowRDE("Only 16 bit images supported");
  }

  void apply(RawImage& ri) override {
    applyOP<ushort16>(
        ri, [this](uint32 x, uint32 y, ushort16 v) { return lookup[v]; });
  }
};

// ****************************************************************************

class DngOpcodes::TableMap final : public LookupOpcode {
public:
  explicit TableMap(ByteStream& bs) : LookupOpcode(bs) {
    auto count = bs.getU32();

    if (count == 0 || count > 65536)
      ThrowRDE("Invalid size of lookup table");

    for (auto i = 0U; i < count; ++i)
      lookup[i] = bs.getU16();

    if (count < lookup.size())
      fill_n(&lookup[count], lookup.size() - count, lookup[count - 1]);
  }
};

// ****************************************************************************

class DngOpcodes::PolynomialMap final : public LookupOpcode {
public:
  explicit PolynomialMap(ByteStream& bs) : LookupOpcode(bs) {
    vector<double> polynomial;

    polynomial.resize(bs.getU32() + 1UL);

    if (polynomial.size() > 9)
      ThrowRDE("A polynomial with more than 8 degrees not allowed");

    for (auto& coeff : polynomial)
      coeff = bs.get<double>();

    // Create lookup
    lookup.resize(65536);
    for (auto i = 0U; i < lookup.size(); ++i) {
      double val = polynomial[0];
      for (auto j = 1U; j < polynomial.size(); ++j)
        val += polynomial[j] * pow(i / 65536.0, j);
      lookup[i] = (clampBits(static_cast<int>(val * 65535.5), 16));
    }
  }
};

// ****************************************************************************

class DngOpcodes::DeltaRowOrColBase : public PixelOpcode {
public:
  struct SelectX {
    static inline uint32 select(uint32 x, uint32 y) { return x; }
  };

  struct SelectY {
    static inline uint32 select(uint32 x, uint32 y) { return y; }
  };

protected:
  vector<float> deltaF;
  vector<int> deltaI;

  DeltaRowOrColBase(ByteStream& bs, float f2iScale) : PixelOpcode(bs) {
    deltaF.resize(bs.getU32());

    for (auto& f : deltaF)
      f = bs.get<float>();

    deltaI.reserve(deltaF.size());
    for (auto f : deltaF)
      deltaI.emplace_back(static_cast<int>(f2iScale * f));
  }
};

// ****************************************************************************

template <typename S>
class DngOpcodes::OffsetPerRowOrCol final : public DeltaRowOrColBase {
public:
  explicit OffsetPerRowOrCol(ByteStream& bs)
      : DeltaRowOrColBase(bs, 65535.0F) {}

  void apply(RawImage& ri) override {
    if (ri->getDataType() == TYPE_USHORT16) {
      applyOP<ushort16>(ri, [this](uint32 x, uint32 y, ushort16 v) {
        return clampBits(deltaI[S::select(x, y)] + v, 16);
      });
    } else {
      applyOP<float>(ri, [this](uint32 x, uint32 y, float v) {
        return deltaF[S::select(x, y)] + v;
      });
    }
  }
};

template <typename S>
class DngOpcodes::ScalePerRowOrCol final : public DeltaRowOrColBase {
public:
  explicit ScalePerRowOrCol(ByteStream& bs) : DeltaRowOrColBase(bs, 1024.0F) {}

  void apply(RawImage& ri) override {
    if (ri->getDataType() == TYPE_USHORT16) {
      applyOP<ushort16>(ri, [this](uint32 x, uint32 y, ushort16 v) {
        return clampBits((deltaI[S::select(x, y)] * v + 512) >> 10, 16);
      });
    } else {
      applyOP<float>(ri, [this](uint32 x, uint32 y, float v) {
        return deltaF[S::select(x, y)] * v;
      });
    }
  }
};

// ****************************************************************************

DngOpcodes::DngOpcodes(TiffEntry* entry) {
  ByteStream bs = entry->getData();
  // DNG opcodes seem to be always stored in big endian
  bs.setInNativeByteOrder(getHostEndianness() == big);

  using OffsetPerRow = OffsetPerRowOrCol<DeltaRowOrColBase::SelectY>;
  using OffsetPerCol = OffsetPerRowOrCol<DeltaRowOrColBase::SelectX>;

  using ScalePerRow = ScalePerRowOrCol<DeltaRowOrColBase::SelectY>;
  using ScalePerCol = ScalePerRowOrCol<DeltaRowOrColBase::SelectX>;

  auto opcode_count = bs.getU32();
  for (auto i = 0U; i < opcode_count; i++) {
    auto code = bs.getU32();
    bs.getU32(); // ignore version
    auto flags = bs.getU32();
    auto expected_pos = bs.getU32() + bs.getPosition();

    switch (code) {
    case 4:
      opcodes.push_back(make_unique<FixBadPixelsConstant>(bs));
      break;
    case 5:
      opcodes.push_back(make_unique<FixBadPixelsList>(bs));
      break;
    case 6:
      opcodes.push_back(make_unique<TrimBounds>(bs));
      break;
    case 7:
      opcodes.push_back(make_unique<TableMap>(bs));
      break;
    case 8:
      opcodes.push_back(make_unique<PolynomialMap>(bs));
      break;
    case 10:
      opcodes.push_back(make_unique<OffsetPerRow>(bs));
      break;
    case 11:
      opcodes.push_back(make_unique<OffsetPerCol>(bs));
      break;
    case 12:
      opcodes.push_back(make_unique<ScalePerRow>(bs));
      break;
    case 13:
      opcodes.push_back(make_unique<ScalePerCol>(bs));
      break;
    default:
      // Throw Error if not marked as optional
      if (!(flags & 1))
        ThrowRDE("Unsupported Opcode: %d", code);
    }
    if (bs.getPosition() != expected_pos)
      ThrowRDE("Inconsistent length of opcode");
  }
}

// defined here as empty destrutor, otherwise we'd need a complete definition
// of the the DngOpcode type in DngOpcodes.h
DngOpcodes::~DngOpcodes() = default;

void DngOpcodes::applyOpCodes(RawImage& ri) {
  for (const auto& code : opcodes) {
    code->setup(ri);
    code->apply(ri);
  }
}

} // namespace rawspeed
<commit_msg>DngOpcodes::DeltaRowOrColBase(): remove unused function parameter<commit_after>/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2009-2014 Klaus Post
    Copyright (C) 2017 Axel Waggershauser

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

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/

#include "common/DngOpcodes.h"
#include "common/Common.h"                // for uint32, ushort16, make_unique
#include "common/Point.h"                 // for iPoint2D, iRectangle2D
#include "common/RawImage.h"              // for RawImage, RawImageData
#include "decoders/RawDecoderException.h" // for RawDecoderException (ptr o...
#include "io/ByteStream.h"                // for ByteStream
#include "io/Endianness.h"                // for getHostEndianness, Endiann...
#include "tiff/TiffEntry.h"               // for TiffEntry
#include <algorithm>                      // for fill_n
#include <cmath>                          // for pow

using std::vector;
using std::fill_n;

namespace rawspeed {

class DngOpcodes::DngOpcode {
public:
  virtual ~DngOpcode() = default;

  // Will be called once before processing.
  // Can be used for preparing pre-calculated values, etc.
  virtual void setup(const RawImage& ri) {
    // NOP by default. child class shall override this if needed.
  }

  // Will be called for actual processing.
  virtual void apply(RawImage& ri) = 0;
};

// ****************************************************************************

class DngOpcodes::FixBadPixelsConstant final : public DngOpcodes::DngOpcode {
  uint32 value;

public:
  explicit FixBadPixelsConstant(ByteStream& bs) {
    value = bs.getU32();
    bs.getU32(); // Bayer Phase not used
  }

  void setup(const RawImage& ri) override {
    // These limitations are present within the DNG SDK as well.
    if (ri->getDataType() != TYPE_USHORT16)
      ThrowRDE("Only 16 bit images supported");

    if (ri->getCpp() > 1)
      ThrowRDE("Only 1 component images supported");
  }

  void apply(RawImage& ri) override {
    iPoint2D crop = ri->getCropOffset();
    uint32 offset = crop.x | (crop.y << 16);
    for (auto y = 0; y < ri->dim.y; ++y) {
      auto* src = reinterpret_cast<ushort16*>(ri->getData(0, y));
      for (auto x = 0; x < ri->dim.x; ++x) {
        if (src[x] == value)
          ri->mBadPixelPositions.push_back(offset + (y << 16 | x));
      }
    }
  }
};

// ****************************************************************************

class DngOpcodes::FixBadPixelsList final : public DngOpcodes::DngOpcode {
  std::vector<uint32> badPixels;

public:
  explicit FixBadPixelsList(ByteStream& bs) {
    bs.getU32(); // Skip phase - we don't care
    auto badPointCount = bs.getU32();
    auto badRectCount = bs.getU32();

    // Read points
    for (auto i = 0U; i < badPointCount; ++i) {
      auto y = bs.getU32();
      auto x = bs.getU32();
      badPixels.push_back(y << 16 | x);
    }

    // Read rects
    for (auto i = 0U; i < badRectCount; ++i) {
      auto top = bs.getU32();
      auto left = bs.getU32();
      auto bottom = bs.getU32();
      auto right = bs.getU32();
      for (auto y = top; y <= bottom; ++y) {
        for (auto x = left; x <= right; ++x) {
          badPixels.push_back(y << 16 | x);
        }
      }
    }
  }

  void apply(RawImage& ri) override {
    ri->mBadPixelPositions.insert(ri->mBadPixelPositions.begin(),
                                  badPixels.begin(), badPixels.end());
  }
};

// ****************************************************************************

class DngOpcodes::ROIOpcode : public DngOpcodes::DngOpcode {
protected:
  uint32 top, left, bottom, right;

  explicit ROIOpcode(ByteStream& bs) {
    top = bs.getU32();
    left = bs.getU32();
    bottom = bs.getU32();
    right = bs.getU32();
  }

  void setup(const RawImage& ri) override {
    iRectangle2D roi(left, top, right - left, bottom - top);
    iRectangle2D fullImage(0, 0, ri->dim.x, ri->dim.y);

    if (!roi.isThisInside(fullImage))
      ThrowRDE("Area of interest not inside image.");
  }
};

// ****************************************************************************

class DngOpcodes::TrimBounds final : public ROIOpcode {
public:
  explicit TrimBounds(ByteStream& bs) : ROIOpcode(bs) {}

  void apply(RawImage& ri) override {
    ri->subFrame(iRectangle2D(left, top, right - left, bottom - top));
  }
};

// ****************************************************************************

class DngOpcodes::PixelOpcode : public ROIOpcode {
protected:
  uint32 firstPlane, planes, rowPitch, colPitch;

  explicit PixelOpcode(ByteStream& bs) : ROIOpcode(bs) {
    firstPlane = bs.getU32();
    planes = bs.getU32();
    rowPitch = bs.getU32();
    colPitch = bs.getU32();

    if (planes == 0)
      ThrowRDE("Zero planes");
    if (rowPitch == 0 || colPitch == 0)
      ThrowRDE("Invalid pitch");
  }

  void setup(const RawImage& ri) override {
    ROIOpcode::setup(ri);
    if (firstPlane + planes > ri->getCpp())
      ThrowRDE("Not that many planes in actual image");
  }

  // traverses the current ROI and applies the operation OP to each pixel,
  // i.e. each pixel value v is replaced by op(x, y, v), where x/y are the
  // coordinates of the pixel value v.
  template <typename T, typename OP> void applyOP(RawImage& ri, OP op) {
    int cpp = ri->getCpp();
    for (auto y = top; y < bottom; y += rowPitch) {
      auto* src = reinterpret_cast<T*>(ri->getData(0, y));
      // Add offset, so this is always first plane
      src += firstPlane;
      for (auto x = left; x < right; x += colPitch) {
        for (auto p = 0U; p < planes; ++p)
          src[x * cpp + p] = op(x, y, src[x * cpp + p]);
      }
    }
  }
};

// ****************************************************************************

class DngOpcodes::LookupOpcode : public PixelOpcode {
protected:
  vector<ushort16> lookup;

  explicit LookupOpcode(ByteStream& bs) : PixelOpcode(bs), lookup(65536) {}

  void setup(const RawImage& ri) override {
    PixelOpcode::setup(ri);
    if (ri->getDataType() != TYPE_USHORT16)
      ThrowRDE("Only 16 bit images supported");
  }

  void apply(RawImage& ri) override {
    applyOP<ushort16>(
        ri, [this](uint32 x, uint32 y, ushort16 v) { return lookup[v]; });
  }
};

// ****************************************************************************

class DngOpcodes::TableMap final : public LookupOpcode {
public:
  explicit TableMap(ByteStream& bs) : LookupOpcode(bs) {
    auto count = bs.getU32();

    if (count == 0 || count > 65536)
      ThrowRDE("Invalid size of lookup table");

    for (auto i = 0U; i < count; ++i)
      lookup[i] = bs.getU16();

    if (count < lookup.size())
      fill_n(&lookup[count], lookup.size() - count, lookup[count - 1]);
  }
};

// ****************************************************************************

class DngOpcodes::PolynomialMap final : public LookupOpcode {
public:
  explicit PolynomialMap(ByteStream& bs) : LookupOpcode(bs) {
    vector<double> polynomial;

    polynomial.resize(bs.getU32() + 1UL);

    if (polynomial.size() > 9)
      ThrowRDE("A polynomial with more than 8 degrees not allowed");

    for (auto& coeff : polynomial)
      coeff = bs.get<double>();

    // Create lookup
    lookup.resize(65536);
    for (auto i = 0U; i < lookup.size(); ++i) {
      double val = polynomial[0];
      for (auto j = 1U; j < polynomial.size(); ++j)
        val += polynomial[j] * pow(i / 65536.0, j);
      lookup[i] = (clampBits(static_cast<int>(val * 65535.5), 16));
    }
  }
};

// ****************************************************************************

class DngOpcodes::DeltaRowOrColBase : public PixelOpcode {
public:
  struct SelectX {
    static inline uint32 select(uint32 x, uint32 /*y*/) { return x; }
  };

  struct SelectY {
    static inline uint32 select(uint32 /*x*/, uint32 y) { return y; }
  };

protected:
  vector<float> deltaF;
  vector<int> deltaI;

  DeltaRowOrColBase(ByteStream& bs, float f2iScale) : PixelOpcode(bs) {
    deltaF.resize(bs.getU32());

    for (auto& f : deltaF)
      f = bs.get<float>();

    deltaI.reserve(deltaF.size());
    for (auto f : deltaF)
      deltaI.emplace_back(static_cast<int>(f2iScale * f));
  }
};

// ****************************************************************************

template <typename S>
class DngOpcodes::OffsetPerRowOrCol final : public DeltaRowOrColBase {
public:
  explicit OffsetPerRowOrCol(ByteStream& bs)
      : DeltaRowOrColBase(bs, 65535.0F) {}

  void apply(RawImage& ri) override {
    if (ri->getDataType() == TYPE_USHORT16) {
      applyOP<ushort16>(ri, [this](uint32 x, uint32 y, ushort16 v) {
        return clampBits(deltaI[S::select(x, y)] + v, 16);
      });
    } else {
      applyOP<float>(ri, [this](uint32 x, uint32 y, float v) {
        return deltaF[S::select(x, y)] + v;
      });
    }
  }
};

template <typename S>
class DngOpcodes::ScalePerRowOrCol final : public DeltaRowOrColBase {
public:
  explicit ScalePerRowOrCol(ByteStream& bs) : DeltaRowOrColBase(bs, 1024.0F) {}

  void apply(RawImage& ri) override {
    if (ri->getDataType() == TYPE_USHORT16) {
      applyOP<ushort16>(ri, [this](uint32 x, uint32 y, ushort16 v) {
        return clampBits((deltaI[S::select(x, y)] * v + 512) >> 10, 16);
      });
    } else {
      applyOP<float>(ri, [this](uint32 x, uint32 y, float v) {
        return deltaF[S::select(x, y)] * v;
      });
    }
  }
};

// ****************************************************************************

DngOpcodes::DngOpcodes(TiffEntry* entry) {
  ByteStream bs = entry->getData();
  // DNG opcodes seem to be always stored in big endian
  bs.setInNativeByteOrder(getHostEndianness() == big);

  using OffsetPerRow = OffsetPerRowOrCol<DeltaRowOrColBase::SelectY>;
  using OffsetPerCol = OffsetPerRowOrCol<DeltaRowOrColBase::SelectX>;

  using ScalePerRow = ScalePerRowOrCol<DeltaRowOrColBase::SelectY>;
  using ScalePerCol = ScalePerRowOrCol<DeltaRowOrColBase::SelectX>;

  auto opcode_count = bs.getU32();
  for (auto i = 0U; i < opcode_count; i++) {
    auto code = bs.getU32();
    bs.getU32(); // ignore version
    auto flags = bs.getU32();
    auto expected_pos = bs.getU32() + bs.getPosition();

    switch (code) {
    case 4:
      opcodes.push_back(make_unique<FixBadPixelsConstant>(bs));
      break;
    case 5:
      opcodes.push_back(make_unique<FixBadPixelsList>(bs));
      break;
    case 6:
      opcodes.push_back(make_unique<TrimBounds>(bs));
      break;
    case 7:
      opcodes.push_back(make_unique<TableMap>(bs));
      break;
    case 8:
      opcodes.push_back(make_unique<PolynomialMap>(bs));
      break;
    case 10:
      opcodes.push_back(make_unique<OffsetPerRow>(bs));
      break;
    case 11:
      opcodes.push_back(make_unique<OffsetPerCol>(bs));
      break;
    case 12:
      opcodes.push_back(make_unique<ScalePerRow>(bs));
      break;
    case 13:
      opcodes.push_back(make_unique<ScalePerCol>(bs));
      break;
    default:
      // Throw Error if not marked as optional
      if (!(flags & 1))
        ThrowRDE("Unsupported Opcode: %d", code);
    }
    if (bs.getPosition() != expected_pos)
      ThrowRDE("Inconsistent length of opcode");
  }
}

// defined here as empty destrutor, otherwise we'd need a complete definition
// of the the DngOpcode type in DngOpcodes.h
DngOpcodes::~DngOpcodes() = default;

void DngOpcodes::applyOpCodes(RawImage& ri) {
  for (const auto& code : opcodes) {
    code->setup(ri);
    code->apply(ri);
  }
}

} // namespace rawspeed
<|endoftext|>


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

Licensed under the Apache License, Version 2.0 (the "License");
vcyou 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 "tensorflow/core/kernels/hexagon/hexagon_ops_definitions.h"

#include <unordered_map>

#include "tensorflow/core/framework/types.h"

namespace tensorflow {

enum class SupportedOpType {
  INPUT,
  OUTPUT,
  NOP,
  CONST,
  CHECK,
  CLOSE_FLOAT32,
  CLOSE_QINT8,
  CLOSE_Q_QINT8,
  CLOSE_INT32,
  CLOSE_QINT32,
  PPRINT_8,
  PPRINT_32,
  PPRINT_FLOAT,
  PREFREE,
  FLATTEN,
  QUANTIZEDCONV2D_8X8TO32,
  QUANTIZEDCONV2D_8X8TO32_REF,
  QUANTIZEDMATMUL_8X8TO32,
  QUANTIZEDMATMUL_8X8TO32_REF,
  QUANTIZEDOWNANDSHRINKRANGE_32TO8,
  QUANTIZEDOWNANDSHRINKRANGE_32TO8_REF,
  QUANTIZEDRELU_8,
  QUANTIZEDRELU_8_REF,
  QUANTIZEDRELUX_8,
  QUANTIZEDRELUX_8_REF,
  QUANTIZEDMAXPOOL_8,
  QUANTIZEDMAXPOOL_8_REF,
  QUANTIZEDAVGPOOL_8,
  QUANTIZEDAVGPOOL_8_REF,
  QUANTIZEDCONCAT_8,
  QUANTIZEDCONCAT_8_REF,
  QUANTIZEDBIASADD_8P8TO32,
  QUANTIZEDBIASADD_8P8TO32_REF,
  MIN_F,
  MIN_F_REF,
  MAX_F,
  MAX_F_REF,
  QUANTIZE,
  QUANTIZE_REF,
  DEQUANTIZE,
  DEQUANTIZE_REF,
  SUPERNODE_8X8P8TO8,
  SUPERNODE_8X8P8TO8_REF,
  QUANTIZEDFLATTEN,
  SUPPORTED_OP_TYPE_COUNT,
};

static const std::unordered_map<string, SupportedOpType>
    OP_NAME_TO_SOC_OP_TYPE_MAP{
        // Custom Op name
        {IGraphTransferOpsDefinitions::INPUT_OP_NAME, SupportedOpType::INPUT},
        {IGraphTransferOpsDefinitions::OUTPUT_OP_NAME, SupportedOpType::OUTPUT},
        // Tensorflow op name
        {"QuantizedConv2D", SupportedOpType::QUANTIZEDCONV2D_8X8TO32},
        {"QuantizedMatMul", SupportedOpType::QUANTIZEDMATMUL_8X8TO32},
        {"QuantizeDownAndShrinkRange",
         SupportedOpType::QUANTIZEDOWNANDSHRINKRANGE_32TO8},
        {"QuantizedRelu", SupportedOpType::QUANTIZEDRELU_8},
        {"QuantizedReluX", SupportedOpType::QUANTIZEDRELUX_8},
        {"QuantizedMaxPool", SupportedOpType::QUANTIZEDMAXPOOL_8},
        {"QuantizedAvgPool", SupportedOpType::QUANTIZEDAVGPOOL_8},
        {"QuantizedConcat", SupportedOpType::QUANTIZEDCONCAT_8},
        {"QuantizedBiasAdd", SupportedOpType::QUANTIZEDBIASADD_8P8TO32},
        {"Min", SupportedOpType::MIN_F},
        {"Max", SupportedOpType::MAX_F},
        {"QuantizeV2", SupportedOpType::QUANTIZE},
    };

/* static */ const IGraphTransferOpsDefinitions&
HexagonOpsDefinitions::getInstance() {
  const static HexagonOpsDefinitions instance{};
  return instance;
}

int HexagonOpsDefinitions::GetTotalOpsCount() const {
  return static_cast<int>(SupportedOpType::SUPPORTED_OP_TYPE_COUNT);
}

int HexagonOpsDefinitions::GetInputNodeOpId() const {
  return static_cast<int>(SupportedOpType::INPUT);
}

int HexagonOpsDefinitions::GetOutputNodeOpId() const {
  return static_cast<int>(SupportedOpType::OUTPUT);
}

int HexagonOpsDefinitions::GetOpIdFor(const string& op_type) const {
  if (OP_NAME_TO_SOC_OP_TYPE_MAP.count(op_type) > 0) {
    return static_cast<int>(OP_NAME_TO_SOC_OP_TYPE_MAP.at(op_type));
  }
  return IGraphTransferOpsDefinitions::INVALID_OP_ID;
}
};
<commit_msg>Fix windows cmake build by replacing enum class by enum Change: 138409704<commit_after>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
vcyou 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 "tensorflow/core/kernels/hexagon/hexagon_ops_definitions.h"

#include <unordered_map>

#include "tensorflow/core/framework/types.h"

namespace tensorflow {

enum class SupportedOpType {
  INPUT,
  OUTPUT,
  NOP,
  OP_CONST, /* OP_ is required to avoid compilation error on windows */
  CHECK,
  CLOSE_FLOAT32,
  CLOSE_QINT8,
  CLOSE_Q_QINT8,
  CLOSE_INT32,
  CLOSE_QINT32,
  PPRINT_8,
  PPRINT_32,
  PPRINT_FLOAT,
  PREFREE,
  FLATTEN,
  QUANTIZEDCONV2D_8X8TO32,
  QUANTIZEDCONV2D_8X8TO32_REF,
  QUANTIZEDMATMUL_8X8TO32,
  QUANTIZEDMATMUL_8X8TO32_REF,
  QUANTIZEDOWNANDSHRINKRANGE_32TO8,
  QUANTIZEDOWNANDSHRINKRANGE_32TO8_REF,
  QUANTIZEDRELU_8,
  QUANTIZEDRELU_8_REF,
  QUANTIZEDRELUX_8,
  QUANTIZEDRELUX_8_REF,
  QUANTIZEDMAXPOOL_8,
  QUANTIZEDMAXPOOL_8_REF,
  QUANTIZEDAVGPOOL_8,
  QUANTIZEDAVGPOOL_8_REF,
  QUANTIZEDCONCAT_8,
  QUANTIZEDCONCAT_8_REF,
  QUANTIZEDBIASADD_8P8TO32,
  QUANTIZEDBIASADD_8P8TO32_REF,
  MIN_F,
  MIN_F_REF,
  MAX_F,
  MAX_F_REF,
  QUANTIZE,
  QUANTIZE_REF,
  DEQUANTIZE,
  DEQUANTIZE_REF,
  SUPERNODE_8X8P8TO8,
  SUPERNODE_8X8P8TO8_REF,
  QUANTIZEDFLATTEN,
  SUPPORTED_OP_TYPE_COUNT,
};

static const std::unordered_map<string, SupportedOpType>
    OP_NAME_TO_SOC_OP_TYPE_MAP{
        // Custom Op name
        {IGraphTransferOpsDefinitions::INPUT_OP_NAME, SupportedOpType::INPUT},
        {IGraphTransferOpsDefinitions::OUTPUT_OP_NAME, SupportedOpType::OUTPUT},
        // Tensorflow op name
        {"QuantizedConv2D", SupportedOpType::QUANTIZEDCONV2D_8X8TO32},
        {"QuantizedMatMul", SupportedOpType::QUANTIZEDMATMUL_8X8TO32},
        {"QuantizeDownAndShrinkRange",
         SupportedOpType::QUANTIZEDOWNANDSHRINKRANGE_32TO8},
        {"QuantizedRelu", SupportedOpType::QUANTIZEDRELU_8},
        {"QuantizedReluX", SupportedOpType::QUANTIZEDRELUX_8},
        {"QuantizedMaxPool", SupportedOpType::QUANTIZEDMAXPOOL_8},
        {"QuantizedAvgPool", SupportedOpType::QUANTIZEDAVGPOOL_8},
        {"QuantizedConcat", SupportedOpType::QUANTIZEDCONCAT_8},
        {"QuantizedBiasAdd", SupportedOpType::QUANTIZEDBIASADD_8P8TO32},
        {"Min", SupportedOpType::MIN_F},
        {"Max", SupportedOpType::MAX_F},
        {"QuantizeV2", SupportedOpType::QUANTIZE},
    };

/* static */ const IGraphTransferOpsDefinitions&
HexagonOpsDefinitions::getInstance() {
  const static HexagonOpsDefinitions instance{};
  return instance;
}

int HexagonOpsDefinitions::GetTotalOpsCount() const {
  return static_cast<int>(SupportedOpType::SUPPORTED_OP_TYPE_COUNT);
}

int HexagonOpsDefinitions::GetInputNodeOpId() const {
  return static_cast<int>(SupportedOpType::INPUT);
}

int HexagonOpsDefinitions::GetOutputNodeOpId() const {
  return static_cast<int>(SupportedOpType::OUTPUT);
}

int HexagonOpsDefinitions::GetOpIdFor(const string& op_type) const {
  if (OP_NAME_TO_SOC_OP_TYPE_MAP.count(op_type) > 0) {
    return static_cast<int>(OP_NAME_TO_SOC_OP_TYPE_MAP.at(op_type));
  }
  return IGraphTransferOpsDefinitions::INVALID_OP_ID;
}
};
<|endoftext|>


<commit_before>/*******************************************************************************
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Jean-David Gadina - www.xs-labs.com / www.digidna.net
 *
 * 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.
 ******************************************************************************/

/*!
 * @copyright   (c) 2015 - Jean-David Gadina - www.xs-labs.com / www.digidna.net
 * @brief       ...
 */

/* Disabled warnings for GoogleMock */
#ifdef __clang__
#pragma clang diagnostic ignored "-Wglobal-constructors"
#pragma clang diagnostic ignored "-Wpadded"
#pragma clang diagnostic push
#if __clang_major__ >= 7
#pragma clang diagnostic ignored "-Wreserved-id-macro"
#endif
#pragma clang diagnostic ignored "-Wmissing-noreturn"
#pragma clang diagnostic ignored "-Wpadded"
#pragma clang diagnostic ignored "-Wused-but-marked-unused"
#pragma clang diagnostic ignored "-Wdeprecated"
#endif

#include <GoogleMock/GoogleMock.h>

#ifdef __clang__
#pragma clang diagnostic pop
#endif

#include <XS/Atomic-Functions.hpp>

using namespace testing;

TEST( XS_Atomic_Functions, AtomicIncrement32 )
{
    int32_t i = 0;

    ASSERT_EQ( XS::AtomicIncrement32( &i ), 1 );
    ASSERT_EQ( i, 1 );
}

TEST( XS_Atomic_Functions, AtomicIncrement64 )
{
    int64_t i = 0;

    ASSERT_EQ( XS::AtomicIncrement64( &i ), 1 );
    ASSERT_EQ( i, 1 );
}

TEST( XS_Atomic_Functions, AtomicDecrement32 )
{
    int32_t i = 0;

    ASSERT_EQ( XS::AtomicDecrement32( &i ), -1 );
    ASSERT_EQ( i, -1 );
}

TEST( XS_Atomic_Functions, AtomicDecrement64 )
{
    int64_t i = 0;

    ASSERT_EQ( XS::AtomicDecrement64( &i ), -1 );
    ASSERT_EQ( i, -1 );
}

TEST( XS_Atomic_Functions, AtomicAdd32 )
{
    int32_t i = 0;

    ASSERT_EQ( XS::AtomicAdd32( 2, &i ), 2 );
    ASSERT_EQ( i, 2 );
}

TEST( XS_Atomic_Functions, AtomicAdd64 )
{
    int64_t i = 0;

    ASSERT_EQ( XS::AtomicAdd64( 2, &i ), 2 );
    ASSERT_EQ( i, 2 );
}

TEST( XS_Atomic_Functions, AtomicCompareAndSwap32 )
{
    int32_t i = 0;

    ASSERT_FALSE( XS::AtomicCompareAndSwap32( 1, 2, &i ) );
    ASSERT_TRUE(  XS::AtomicCompareAndSwap32( 0, 2, &i ) );
    ASSERT_EQ( i, 2 );
}

TEST( XS_Atomic_Functions, AtomicCompareAndSwap64 )
{
    int64_t i = 0;

    ASSERT_FALSE( XS::AtomicCompareAndSwap64( 1, 2, &i ) );
    ASSERT_TRUE(  XS::AtomicCompareAndSwap64( 0, 2, &i ) );
    ASSERT_EQ( i, 2 );
}

TEST( XS_Atomic_Functions, AtomicCompareAndSwapPointer )
{
    void * p = nullptr;

    ASSERT_FALSE( XS::AtomicCompareAndSwapPointer( reinterpret_cast< void * >( 1 ), reinterpret_cast< void * >( 2 ), reinterpret_cast< void * volatile * >( &p ) ) );
    ASSERT_TRUE(  XS::AtomicCompareAndSwapPointer( reinterpret_cast< void * >( 0 ), reinterpret_cast< void * >( 2 ), reinterpret_cast< void * volatile * >( &p ) ) );
    ASSERT_EQ( p, reinterpret_cast< void * >( 2 ) );
}
<commit_msg>Unit tests...<commit_after>/*******************************************************************************
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Jean-David Gadina - www.xs-labs.com / www.digidna.net
 *
 * 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.
 ******************************************************************************/

/*!
 * @copyright   (c) 2015 - Jean-David Gadina - www.xs-labs.com / www.digidna.net
 * @brief       ...
 */

/* Disabled warnings for GoogleMock */
#ifdef __clang__
#pragma clang diagnostic ignored "-Wglobal-constructors"
#pragma clang diagnostic ignored "-Wpadded"
#pragma clang diagnostic push
#if __clang_major__ >= 7
#pragma clang diagnostic ignored "-Wreserved-id-macro"
#endif
#pragma clang diagnostic ignored "-Wmissing-noreturn"
#pragma clang diagnostic ignored "-Wpadded"
#pragma clang diagnostic ignored "-Wused-but-marked-unused"
#pragma clang diagnostic ignored "-Wdeprecated"
#endif

#include <GoogleMock/GoogleMock.h>

#ifdef __clang__
#pragma clang diagnostic pop
#endif

#include <XS/Atomic-Functions.hpp>

using namespace testing;

TEST( XS_Atomic_Functions, AtomicIncrement32 )
{
    int32_t i = 0;

    ASSERT_EQ( XS::AtomicIncrement32( &i ), 1 );
    ASSERT_EQ( i, 1 );
}

TEST( XS_Atomic_Functions, AtomicIncrement64 )
{
    int64_t i = 0;

    ASSERT_EQ( XS::AtomicIncrement64( &i ), 1 );
    ASSERT_EQ( i, 1 );
}

TEST( XS_Atomic_Functions, AtomicDecrement32 )
{
    int32_t i = 0;

    ASSERT_EQ( XS::AtomicDecrement32( &i ), -1 );
    ASSERT_EQ( i, -1 );
}

TEST( XS_Atomic_Functions, AtomicDecrement64 )
{
    int64_t i = 0;

    ASSERT_EQ( XS::AtomicDecrement64( &i ), -1 );
    ASSERT_EQ( i, -1 );
}

TEST( XS_Atomic_Functions, AtomicAdd32 )
{
    int32_t i = 0;

    ASSERT_EQ( XS::AtomicAdd32( 2, &i ), 2 );
    ASSERT_EQ( i, 2 );
}

TEST( XS_Atomic_Functions, AtomicAdd64 )
{
    int64_t i = 0;

    ASSERT_EQ( XS::AtomicAdd64( 2, &i ), 2 );
    ASSERT_EQ( i, 2 );
}

TEST( XS_Atomic_Functions, AtomicCompareAndSwap32 )
{
    int32_t i = 0;

    ASSERT_FALSE( XS::AtomicCompareAndSwap32( 1, 2, &i ) );
    ASSERT_TRUE(  XS::AtomicCompareAndSwap32( 0, 2, &i ) );
    ASSERT_EQ( i, 2 );
}

TEST( XS_Atomic_Functions, AtomicCompareAndSwap64 )
{
    int64_t i = 0;

    ASSERT_FALSE( XS::AtomicCompareAndSwap64( 1, 2, &i ) );
    ASSERT_TRUE(  XS::AtomicCompareAndSwap64( 0, 2, &i ) );
    ASSERT_EQ( i, 2 );
}

TEST( XS_Atomic_Functions, AtomicCompareAndSwapPointer )
{
    void * p = nullptr;

    ASSERT_FALSE( XS::AtomicCompareAndSwapPointer( reinterpret_cast< void * >( 1 ), reinterpret_cast< void * >( 2 ), reinterpret_cast< void * volatile * >( &p ) ) );
    ASSERT_TRUE(  XS::AtomicCompareAndSwapPointer( reinterpret_cast< void * >( 0 ), reinterpret_cast< void * >( 2 ), reinterpret_cast< void * volatile * >( &p ) ) );
    ASSERT_EQ( p, reinterpret_cast< void * >( 2 ) );
}

TEST( XS_Atomic_Functions, MemoryBarrier )
{
    XS::MemoryBarrier();
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015 Cryptonomex, Inc., and contributors.
 *
 * The MIT License
 *
 * 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 <graphene/app/api_access.hpp>
#include <graphene/net/node.hpp>
#include <graphene/chain/database.hpp>

#include <boost/program_options.hpp>

namespace graphene { namespace app {
   namespace detail { class application_impl; }
   using std::string;

   class abstract_plugin;

   class application_options
   {
      public:
         // TODO change default to false when GUI is ready
         bool enable_subscribe_to_all = true;
         bool has_market_history_plugin = false;
   };

   class application
   {
      public:
         application();
         ~application();

         void set_program_options( boost::program_options::options_description& command_line_options,
                                   boost::program_options::options_description& configuration_file_options )const;
         void initialize(const fc::path& data_dir, const boost::program_options::variables_map&options);
         void initialize_plugins( const boost::program_options::variables_map& options );
         void startup();
         void shutdown();
         void startup_plugins();
         void shutdown_plugins();

         template<typename PluginType>
         std::shared_ptr<PluginType> register_plugin()
         {
            auto plug = std::make_shared<PluginType>();
            plug->plugin_set_app(this);

            boost::program_options::options_description plugin_cli_options(plug->plugin_name() + " plugin. " + plug->plugin_description() + "\nOptions"), plugin_cfg_options;
            //boost::program_options::options_description plugin_cli_options("Options for plugin " + plug->plugin_name()), plugin_cfg_options;
            plug->plugin_set_program_options(plugin_cli_options, plugin_cfg_options);
            if( !plugin_cli_options.options().empty() )
               _cli_options.add(plugin_cli_options);
            if( !plugin_cfg_options.options().empty() )
               _cfg_options.add(plugin_cfg_options);

            add_available_plugin( plug );
            return plug;
         }
         std::shared_ptr<abstract_plugin> get_plugin( const string& name )const;

         template<typename PluginType>
         std::shared_ptr<PluginType> get_plugin( const string& name ) const
         {
            std::shared_ptr<abstract_plugin> abs_plugin = get_plugin( name );
            std::shared_ptr<PluginType> result = std::dynamic_pointer_cast<PluginType>( abs_plugin );
            FC_ASSERT( result != std::shared_ptr<PluginType>() );
            return result;
         }

         net::node_ptr                    p2p_node();
         std::shared_ptr<chain::database> chain_database()const;

         void set_block_production(bool producing_blocks);
         fc::optional< api_access_info > get_api_access_info( const string& username )const;
         void set_api_access_info(const string& username, api_access_info&& permissions);

         bool is_finished_syncing()const;
         /// Emitted when syncing finishes (is_finished_syncing will return true)
         boost::signals2::signal<void()> syncing_finished;

         const application_options& get_options();

      private:
         void enable_plugin( const string& name );
         void add_available_plugin( std::shared_ptr<abstract_plugin> p );
         std::shared_ptr<detail::application_impl> my;

         boost::program_options::options_description _cli_options;
         boost::program_options::options_description _cfg_options;
   };

} }
<commit_msg>Added message to FC_ASSERT in application.hpp<commit_after>/*
 * Copyright (c) 2015 Cryptonomex, Inc., and contributors.
 *
 * The MIT License
 *
 * 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 <graphene/app/api_access.hpp>
#include <graphene/net/node.hpp>
#include <graphene/chain/database.hpp>

#include <boost/program_options.hpp>

namespace graphene { namespace app {
   namespace detail { class application_impl; }
   using std::string;

   class abstract_plugin;

   class application_options
   {
      public:
         // TODO change default to false when GUI is ready
         bool enable_subscribe_to_all = true;
         bool has_market_history_plugin = false;
   };

   class application
   {
      public:
         application();
         ~application();

         void set_program_options( boost::program_options::options_description& command_line_options,
                                   boost::program_options::options_description& configuration_file_options )const;
         void initialize(const fc::path& data_dir, const boost::program_options::variables_map&options);
         void initialize_plugins( const boost::program_options::variables_map& options );
         void startup();
         void shutdown();
         void startup_plugins();
         void shutdown_plugins();

         template<typename PluginType>
         std::shared_ptr<PluginType> register_plugin()
         {
            auto plug = std::make_shared<PluginType>();
            plug->plugin_set_app(this);

            boost::program_options::options_description plugin_cli_options(plug->plugin_name() + " plugin. " + plug->plugin_description() + "\nOptions"), plugin_cfg_options;
            //boost::program_options::options_description plugin_cli_options("Options for plugin " + plug->plugin_name()), plugin_cfg_options;
            plug->plugin_set_program_options(plugin_cli_options, plugin_cfg_options);
            if( !plugin_cli_options.options().empty() )
               _cli_options.add(plugin_cli_options);
            if( !plugin_cfg_options.options().empty() )
               _cfg_options.add(plugin_cfg_options);

            add_available_plugin( plug );
            return plug;
         }
         std::shared_ptr<abstract_plugin> get_plugin( const string& name )const;

         template<typename PluginType>
         std::shared_ptr<PluginType> get_plugin( const string& name ) const
         {
            std::shared_ptr<abstract_plugin> abs_plugin = get_plugin( name );
            std::shared_ptr<PluginType> result = std::dynamic_pointer_cast<PluginType>( abs_plugin );
            FC_ASSERT( result != std::shared_ptr<PluginType>(), "Unable to load plugin '${p}'", ("p",name) );
            return result;
         }

         net::node_ptr                    p2p_node();
         std::shared_ptr<chain::database> chain_database()const;

         void set_block_production(bool producing_blocks);
         fc::optional< api_access_info > get_api_access_info( const string& username )const;
         void set_api_access_info(const string& username, api_access_info&& permissions);

         bool is_finished_syncing()const;
         /// Emitted when syncing finishes (is_finished_syncing will return true)
         boost::signals2::signal<void()> syncing_finished;

         const application_options& get_options();

      private:
         void enable_plugin( const string& name );
         void add_available_plugin( std::shared_ptr<abstract_plugin> p );
         std::shared_ptr<detail::application_impl> my;

         boost::program_options::options_description _cli_options;
         boost::program_options::options_description _cfg_options;
   };

} }
<|endoftext|>


<commit_before>#include "imgui.h"

#include <babylon/babylon_fwd.h>
#include <babylon/buffers/vertex_buffer.h>
#include <babylon/cameras/arc_rotate_camera.h>
#include <babylon/core/random.h>
#include <babylon/interfaces/irenderable_scene_with_hud.h>
#include <babylon/lights/hemispheric_light.h>
#include <babylon/materials/pbr/pbr_material.h>
#include <babylon/materials/textures/hdr_cube_texture.h>
#include <babylon/meshes/mesh.h>
#include <babylon/meshes/vertex_data.h>
#include <babylon/morph/morph_target_manager.h>
#include <babylon/samples/babylon_register_sample.h>

namespace BABYLON {

FWD_CLASS_SPTR(Mesh)
FWD_CLASS_SPTR(MorphTarget)

namespace Samples {

/**
 * @brief Morph Targets Scene. Example demonstrating how to morph a mesh between multiple targets
 * @see https://www.babylonjs-playground.com/#2JDN66#7
 * @see https://doc.babylonjs.com/how_to/how_to_use_morphtargets
 */
struct MorphTargetsScene : public IRenderableSceneWithHud {

  MorphTargetsScene(ICanvas* iCanvas = nullptr) : IRenderableSceneWithHud(iCanvas)
  {
  }

  ~MorphTargetsScene() override = default;

  const char* getName() override
  {
    return "Materials Scene";
  }

  void initializeScene(ICanvas* canvas, Scene* scene) override
  {
    // This creates and positions a free camera (non-mesh)
    auto camera
      = ArcRotateCamera::New(std::string("camera1"), 1.14f, 1.13f, 10.f, Vector3::Zero(), scene);

    // This targets the camera to scene origin
    camera->setTarget(Vector3::Zero());

    // This attaches the camera to the canvas
    camera->attachControl(canvas, true);

    // This creates a light, aiming 0,1,0 - to the sky (non-mesh)
    auto light = HemisphericLight::New("light1", Vector3(0.f, 1.f, 0.f), scene);

    // Default intensity is 1. Let's dim the light a small amount
    light->intensity = 0.f;

    // Our built-in 'sphere' shape. Params: name, subdivs, size, scene
    auto sphere = Mesh::CreateSphere("sphere1", 16, 2.f, scene);

    auto hdrTexture = HDRCubeTexture::New("/textures/room.hdr", scene, 512);

    auto exposure                         = 0.6f;
    auto contrast                         = 1.6f;
    auto glass                            = PBRMaterial::New("glass", scene);
    glass->reflectionTexture              = hdrTexture;
    glass->refractionTexture              = hdrTexture;
    glass->linkRefractionWithTransparency = true;
    glass->indexOfRefraction              = 0.52f;
    glass->alpha                          = 0.f;
    glass->cameraExposure                 = exposure;
    glass->cameraContrast                 = contrast;
    glass->microSurface                   = 1.f;
    glass->reflectivityColor              = Color3(0.2f, 0.2f, 0.2f);
    glass->albedoColor                    = Color3(0.85f, 0.85f, 0.85f);
    sphere->material                      = glass;

    auto sphere2 = Mesh::CreateSphere("sphere2", 16, 2.f, scene);
    sphere2->setEnabled(false);
    _addSpike(sphere2);

    auto sphere3 = Mesh::CreateSphere("sphere3", 16, 2.f, scene);
    sphere3->setEnabled(false);
    _addSpike(sphere3);

    auto sphere4 = Mesh::CreateSphere("sphere4", 16, 2.f, scene);
    sphere4->setEnabled(false);
    _addSpike(sphere4);

    auto sphere5 = Mesh::CreateSphere("sphere5", 16, 2.f, scene);
    sphere5->setEnabled(false);
    _addSpike(sphere5);

    auto manager               = MorphTargetManager::New();
    sphere->morphTargetManager = manager;

    _target0 = MorphTarget::FromMesh(sphere2, "sphere2", 0.25f);
    manager->addTarget(_target0);

    _target1 = MorphTarget::FromMesh(sphere3, "sphere3", 0.25f);
    manager->addTarget(_target1);

    _target2 = MorphTarget::FromMesh(sphere4, "sphere4", 0.25f);
    manager->addTarget(_target2);

    _target3 = MorphTarget::FromMesh(sphere5, "sphere5", 0.25f);
    manager->addTarget(_target3);

    // Set influences
    _target0->influence = 0.25f;
    _target1->influence = 0.50f;
    _target2->influence = 0.75f;
    _target3->influence = 1.00f;

    hudGui = [=]() {
      auto addSlider
        = [](const std::string& label, auto& floatProperty, float min = 0.f, float max = 1.f) {
            float currentValue = floatProperty;
            if (ImGui::SliderFloat(label.c_str(), &currentValue, min, max))
              floatProperty = currentValue;
          };
      addSlider("Influence #1", _target0->influence);
      addSlider("Influence #2", _target1->influence);
      addSlider("Influence #3", _target2->influence);
      addSlider("Influence #4", _target3->influence);
      addSlider("cameraContrast", glass->cameraContrast);
      addSlider("cameraExposure", glass->cameraExposure, 0., 2.);
      addSlider("microSurface", glass->microSurface, 0., 2.);
      addSlider("indexOfRefraction", glass->indexOfRefraction, 0., 2.);
      addSlider("alpha", glass->alpha, 0., 2.);
    };
  }

private:
  void _addSpike(const MeshPtr& mesh)
  {
    auto positions = mesh->getVerticesData(VertexBuffer::PositionKind);
    auto normals   = mesh->getVerticesData(VertexBuffer::NormalKind);
    auto indices   = mesh->getIndices();

    for (size_t index = 0; index < 5; ++index) {
      auto randomVertexID = static_cast<unsigned int>(mesh->getTotalVertices() * Math::random());
      auto position       = Vector3::FromArray(positions, randomVertexID * 3);
      auto normal         = Vector3::FromArray(normals, randomVertexID * 3);

      position.addInPlace(normal);

      position.toArray(positions, randomVertexID * 3);
    }

    VertexData::ComputeNormals(positions, indices, normals);
    mesh->updateVerticesData(VertexBuffer::PositionKind, positions, false, false);
    mesh->updateVerticesData(VertexBuffer::NormalKind, normals, false, false);
  }

private:
  using MeshPtr        = std::shared_ptr<Mesh>;
  using MorphTargetPtr = std::shared_ptr<MorphTarget>;

  MorphTargetPtr _target0;
  MorphTargetPtr _target1;
  MorphTargetPtr _target2;
  MorphTargetPtr _target3;
};

std::shared_ptr<BABYLON::IRenderableScene> MakeMorphTargetsScene(ICanvas* iCanvas)
{
  return std::make_shared<MorphTargetsScene>(iCanvas);
}

BABYLON_REGISTER_SAMPLE("Animations", MorphTargetsScene)

} // end of namespace Samples
} // end of namespace BABYLON
<commit_msg>Removed duplicate code<commit_after>#include "imgui.h"

#include <babylon/babylon_fwd.h>
#include <babylon/buffers/vertex_buffer.h>
#include <babylon/cameras/arc_rotate_camera.h>
#include <babylon/core/random.h>
#include <babylon/interfaces/irenderable_scene_with_hud.h>
#include <babylon/lights/hemispheric_light.h>
#include <babylon/materials/pbr/pbr_material.h>
#include <babylon/materials/textures/hdr_cube_texture.h>
#include <babylon/meshes/mesh.h>
#include <babylon/meshes/vertex_data.h>
#include <babylon/morph/morph_target_manager.h>
#include <babylon/samples/babylon_register_sample.h>

namespace BABYLON {

FWD_CLASS_SPTR(Mesh)
FWD_CLASS_SPTR(MorphTarget)

namespace Samples {

/**
 * @brief Morph Targets Scene. Example demonstrating how to morph a mesh between multiple targets
 * @see https://www.babylonjs-playground.com/#2JDN66#7
 * @see https://doc.babylonjs.com/how_to/how_to_use_morphtargets
 */
struct MorphTargetsScene : public IRenderableSceneWithHud {

  MorphTargetsScene(ICanvas* iCanvas = nullptr) : IRenderableSceneWithHud(iCanvas)
  {
  }

  ~MorphTargetsScene() override = default;

  const char* getName() override
  {
    return "Materials Scene";
  }

  void initializeScene(ICanvas* canvas, Scene* scene) override
  {
    // This creates and positions a free camera (non-mesh)
    auto camera
      = ArcRotateCamera::New(std::string("camera1"), 1.14f, 1.13f, 10.f, Vector3::Zero(), scene);

    // This targets the camera to scene origin
    camera->setTarget(Vector3::Zero());

    // This attaches the camera to the canvas
    camera->attachControl(canvas, true);

    // This creates a light, aiming 0,1,0 - to the sky (non-mesh)
    auto light = HemisphericLight::New("light1", Vector3(0.f, 1.f, 0.f), scene);

    // Default intensity is 1. Let's dim the light a small amount
    light->intensity = 0.f;

    // Our built-in 'sphere' shape. Params: name, subdivs, size, scene
    auto sphere = Mesh::CreateSphere("sphere1", 16, 2.f, scene);

    auto hdrTexture = HDRCubeTexture::New("/textures/room.hdr", scene, 512);

    auto exposure                         = 0.6f;
    auto contrast                         = 1.6f;
    auto glass                            = PBRMaterial::New("glass", scene);
    glass->reflectionTexture              = hdrTexture;
    glass->refractionTexture              = hdrTexture;
    glass->linkRefractionWithTransparency = true;
    glass->indexOfRefraction              = 0.52f;
    glass->alpha                          = 0.f;
    glass->cameraExposure                 = exposure;
    glass->cameraContrast                 = contrast;
    glass->microSurface                   = 1.f;
    glass->reflectivityColor              = Color3(0.2f, 0.2f, 0.2f);
    glass->albedoColor                    = Color3(0.85f, 0.85f, 0.85f);
    sphere->material                      = glass;

    auto sphere2 = Mesh::CreateSphere("sphere2", 16, 2.f, scene);
    sphere2->setEnabled(false);
    _addSpike(sphere2);

    auto sphere3 = Mesh::CreateSphere("sphere3", 16, 2.f, scene);
    sphere3->setEnabled(false);
    _addSpike(sphere3);

    auto sphere4 = Mesh::CreateSphere("sphere4", 16, 2.f, scene);
    sphere4->setEnabled(false);
    _addSpike(sphere4);

    auto sphere5 = Mesh::CreateSphere("sphere5", 16, 2.f, scene);
    sphere5->setEnabled(false);
    _addSpike(sphere5);

    auto manager               = MorphTargetManager::New();
    sphere->morphTargetManager = manager;

    _target0 = MorphTarget::FromMesh(sphere2, "sphere2", 0.25f);
    manager->addTarget(_target0);

    _target1 = MorphTarget::FromMesh(sphere3, "sphere3", 0.25f);
    manager->addTarget(_target1);

    _target2 = MorphTarget::FromMesh(sphere4, "sphere4", 0.25f);
    manager->addTarget(_target2);

    _target3 = MorphTarget::FromMesh(sphere5, "sphere5", 0.25f);
    manager->addTarget(_target3);

    // Set influences
    _target0->influence = 0.25f;
    _target1->influence = 0.50f;
    _target2->influence = 0.75f;
    _target3->influence = 1.00f;

    hudGui = [=]() {
      auto addSlider
        = [](const std::string& label, auto& floatProperty, float min = 0.f, float max = 1.f) {
            float currentValue = floatProperty;
            if (ImGui::SliderFloat(label.c_str(), &currentValue, min, max))
              floatProperty = currentValue;
          };
      addSlider("Influence #1", _target0->influence);
      addSlider("Influence #2", _target1->influence);
      addSlider("Influence #3", _target2->influence);
      addSlider("Influence #4", _target3->influence);
      addSlider("cameraContrast", glass->cameraContrast);
      addSlider("cameraExposure", glass->cameraExposure, 0., 2.);
      addSlider("microSurface", glass->microSurface, 0., 2.);
      addSlider("indexOfRefraction", glass->indexOfRefraction, 0., 2.);
      addSlider("alpha", glass->alpha, 0., 2.);
    };
  }

private:
  void _addSpike(const MeshPtr& mesh)
  {
    auto positions = mesh->getVerticesData(VertexBuffer::PositionKind);
    auto normals   = mesh->getVerticesData(VertexBuffer::NormalKind);
    auto indices   = mesh->getIndices();

    for (size_t index = 0; index < 5; ++index) {
      auto randomVertexID = static_cast<unsigned int>(mesh->getTotalVertices() * Math::random());
      auto position       = Vector3::FromArray(positions, randomVertexID * 3);
      auto normal         = Vector3::FromArray(normals, randomVertexID * 3);

      position.addInPlace(normal);

      position.toArray(positions, randomVertexID * 3);
    }

    VertexData::ComputeNormals(positions, indices, normals);
    mesh->updateVerticesData(VertexBuffer::PositionKind, positions, false, false);
    mesh->updateVerticesData(VertexBuffer::NormalKind, normals, false, false);
  }

private:
  MorphTargetPtr _target0;
  MorphTargetPtr _target1;
  MorphTargetPtr _target2;
  MorphTargetPtr _target3;
};

std::shared_ptr<BABYLON::IRenderableScene> MakeMorphTargetsScene(ICanvas* iCanvas)
{
  return std::make_shared<MorphTargetsScene>(iCanvas);
}

BABYLON_REGISTER_SAMPLE("Animations", MorphTargetsScene)

} // end of namespace Samples
} // end of namespace BABYLON
<|endoftext|>


<commit_before><commit_msg>kill last (ab)user of SetRanges()<commit_after><|endoftext|>


<commit_before>#pragma once

#include <raindance/Core/Headers.hh>
#include <raindance/Core/Clock.hh>
#include <raindance/Core/Camera/Camera.hh>
#include <raindance/Core/Primitives/Quad.hh>
#include <raindance/Core/Resources/Texture.hh>

#include <graphiti/Entities/MVC.hh>

#include <graphiti/Visualizers/Network/GPUGraph.hh>

class NetworkView : public GraphView
{
public:

	NetworkView()
	{
		LOG("[NETWORK] Creating network view ...\n");

		m_GraphEntity = NULL;
		m_Font = new Font();
		m_Graph = new GPUGraph();
	}

	virtual ~NetworkView()
	{
		SAFE_DELETE(m_Font);

		SAFE_DELETE(m_Graph);
	}

	virtual const char* name() const { return "network"; }

    virtual bool bind(Entity* entity)
    {
        if (entity->type() != Entity::GRAPH)
        {
            LOG("[NETWORK] Couldn't bind entity to view : Wrong entity type!\n");
            return false;
        }

		m_Camera2D.setOrthographicProjection(0.0f, getViewport().getDimension()[0], 0.0f, getViewport().getDimension()[1], 0.001f, 100.f);
		m_Camera2D.lookAt(glm::vec3(0, 0, 10), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0));

		m_Camera3D.setPerspectiveProjection(60.0f, getViewport().getDimension()[0] / getViewport().getDimension()[1], 0.1f, 1024.0f);
		m_Camera3D.lookAt(glm::vec3(0, 0, 30), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0));

        m_GraphEntity = static_cast<GraphEntity*>(entity);
        m_GraphEntity->views().push_back(this);
        m_GraphEntity->listeners().push_back(this);

        return true;
    }

	inline Camera* getCamera3D()
	{
		return &m_Camera3D;
	}

	void draw() override
	{
		glClearColor(0.0, 0.0, 0.0, 1.0);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glDisable(GL_DEPTH_TEST);
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_DST_ALPHA);

		Transformation transformation;

		m_Graph->draw(context(), m_Camera3D, transformation);
	}

	void idle() override
	{
        static bool m_Initialized = false;
        if (!m_Initialized)
        {
            m_Graph->initialize(context());
            m_Initialized = true;
        }

        m_Graph->idle(context());
	}

	void notify(IMessage* message)
	{
		(void) message;
	}

    // ----- Helpers -----

    void checkNodeUID(GPUGraph::Node::ID uid)
    {
        if (!m_NodeMap.containsRemoteID(uid))
        {
            LOG("Node UID %u not found !\n", uid);
            throw;
        }
    }

    void checkEdgeUID(GPUGraph::Edge::ID uid)
    {
        if (!m_EdgeMap.containsRemoteID(uid))
        {
            LOG("Edge UID %u not found !\n", uid);
            throw;
        }
    }

	// ----- Graph Events -----

    void onSetAttribute(const std::string& name, VariableType type, const std::string& value) override
    {
        LOG("onSetAttribute(%s, %i, %s)\n", name.c_str(), (int)type, value.c_str());
    }

    void onAddNode(Node::ID uid, const char* label) override // TODO : Attributes in Variables object
    {
        LOG("onAddNode(%lu, %s)\n", uid, label);

        GPUGraph::Node node;

        // TODO : Emitter system? (Define where particles appear)

        node.Position = 10.0f * glm::vec4
        (
            RANDOM_FLOAT(-1.0, 1.0),
            RANDOM_FLOAT(-1.0, 1.0),
            RANDOM_FLOAT(-1.0, 1.0),
            0.0
        );

        node.Color = glm::vec4(1.0, 1.0, 1.0, 1.0);

        node.Size = 1.0;

        m_Graph->addNode(node);

        static unsigned int node_count = 0;

        GPUGraph::Node::ID nid = node_count;
        m_NodeMap.addRemoteID(uid, nid);

        node_count++;
    }

    void onRemoveNode(Node::ID uid) override
    {
        LOG("onRemoveNode(%lu)\n", uid);
    }

    void onSetNodeAttribute(Node::ID uid, const std::string& name, VariableType type, const std::string& value) override
    {
        LOG("onSetNodeAttribute(%lu, %s, %i, %s)\n", uid, name.c_str(), (int)type, value.c_str());

        BooleanVariable vbool;
        Vec3Variable vvec3;
        Vec4Variable vvec4;
        FloatVariable vfloat;

        checkNodeUID(uid);

        GPUGraph::Node::ID id = m_NodeMap.getLocalID(uid);

        if ((name == "space:position" || name == "particles:position") && type == RD_VEC3)
        {
            vvec3.set(value);

            GPUGraph::Node node = m_Graph->getNode(id);
            node.Position = glm::vec4(vvec3.value(), 0.0);
            m_Graph->setNode(id, node);

        }
        else if (name == "space:color" && (type == RD_VEC3 || type == RD_VEC4))
        {
            glm::vec4 c;

            if (type == RD_VEC3)
            {
                vvec3.set(value);
                c = glm::vec4(vvec3.value(), 0.0);
            }
            else
            {
                vvec4.set(value);
                c = vvec4.value();
            }

            GPUGraph::Node node = m_Graph->getNode(id);
            node.Color = vvec4.value();
            m_Graph->setNode(id, node);
        }
        else if (name == "space:size" && type == RD_FLOAT)
        {
            vfloat.set(value);

            GPUGraph::Node node = m_Graph->getNode(id);
            node.Size = vfloat.value();
            m_Graph->setNode(id, node);
        }
    }

    void onAddEdge(Edge::ID uid, Node::ID uid1, Node::ID uid2) override
    {
        LOG("onAddEdge(%lu, %lu, %lu)\n", uid, uid1, uid2);

        GPUGraph::Node::ID nid1 = m_NodeMap.getLocalID(uid1);
        GPUGraph::Node::ID nid2 = m_NodeMap.getLocalID(uid2);

        GPUGraph::Edge edge;

        GPUGraph::Node n1 = m_Graph->getNode(nid1);
        GPUGraph::Node n2 = m_Graph->getNode(nid2);

        edge.SourcePosition = n1.Position;
        edge.SourceColor = n1.Color;

        edge.TargetPosition = n2.Position;
        edge.TargetColor =  n2.Color;

        edge.Width = 0.5; // NOTE : Half of the node size

        m_Graph->addEdge(edge);

        static unsigned int edge_count = 0;

        GPUGraph::Edge::ID eid = edge_count;
        m_EdgeMap.addRemoteID(uid, eid);

        edge_count++;
    }

    void onRemoveEdge(Edge::ID uid) override
    {
        LOG("onRemoveEdge(%lu)\n", uid);
    }

    void onSetEdgeAttribute(Edge::ID uid, const std::string& name, VariableType type, const std::string& value) override
    {
        LOG("onSetEdgeAttribute(%lu %s, %i, %s)\n", uid, name.c_str(), (int)type, value.c_str());

        FloatVariable vfloat;
        Vec3Variable vvec3;
        Vec4Variable vvec4;
        StringVariable vstring;

        checkEdgeUID(uid);
        GPUGraph::Edge::ID id = m_EdgeMap.getLocalID(uid);

        if (name == "space:color" && type == RD_VEC4)
        {
            vvec4.set(value);

            GPUGraph::Edge edge = m_Graph->getEdge(id);
            edge.SourceColor = vvec4.value();
            edge.TargetColor = vvec4.value();
            m_Graph->setEdge(id, edge);
        }
        else if (name == "space:color1" && type == RD_VEC4)
        {
            vvec4.set(value);

            GPUGraph::Edge edge = m_Graph->getEdge(id);
            edge.SourceColor = vvec4.value();
            m_Graph->setEdge(id, edge);
        }
        else if (name == "space:color2" && type == RD_VEC4)
        {
            vvec4.set(value);

            GPUGraph::Edge edge = m_Graph->getEdge(id);
            edge.TargetColor = vvec4.value();
            m_Graph->setEdge(id, edge);
        }
        else if (name == "space:width" && type == RD_FLOAT)
        {
            vfloat.set(value);

            GPUGraph::Edge edge = m_Graph->getEdge(id);
            edge.Width = vfloat.value();
            m_Graph->setEdge(id, edge);
        }
    }

	virtual IVariable* getAttribute(const std::string& name)
	{
		(void) name;
		return NULL;
	}

    virtual IVariable* getNodeAttribute(Node::ID id, std::string& name)
    {
    	(void) id;
    	(void) name;
    	return NULL;
    }

    virtual IVariable* getEdgeAttribute(Edge::ID id, std::string& name)
    {
    	(void) id;
    	(void) name;
    	return NULL;
    }

    inline GraphContext* context() { return static_cast<GraphContext*>(m_GraphEntity->context()); }

    inline GraphModel* model() { return static_cast<GraphModel*>(m_GraphEntity->model()); }

private:
	GraphEntity* m_GraphEntity;

	Camera m_Camera2D;
	Camera m_Camera3D;

	Font* m_Font;

	GPUGraph* m_Graph;
    TranslationMap<GPUGraph::Node::ID, unsigned int> m_NodeMap;
    TranslationMap<GPUGraph::Edge::ID, unsigned int> m_EdgeMap;
};

<commit_msg>Integrating OpenCL physics<commit_after>#pragma once

#include <raindance/Core/Headers.hh>
#include <raindance/Core/Clock.hh>
#include <raindance/Core/Camera/Camera.hh>
#include <raindance/Core/Primitives/Quad.hh>
#include <raindance/Core/Resources/Texture.hh>

#include <graphiti/Entities/MVC.hh>

#include <graphiti/Visualizers/Network/GPUGraph.hh>

class NetworkView : public GraphView
{
public:

	NetworkView()
	{
		LOG("[NETWORK] Creating network view ...\n");

		m_GraphEntity = NULL;
		m_Font = new Font();
		m_Graph = new GPUGraph();
	}

	virtual ~NetworkView()
	{
		SAFE_DELETE(m_Font);

		SAFE_DELETE(m_Graph);
	}

	virtual const char* name() const { return "network"; }

    virtual bool bind(Entity* entity)
    {
        if (entity->type() != Entity::GRAPH)
        {
            LOG("[NETWORK] Couldn't bind entity to view : Wrong entity type!\n");
            return false;
        }

		m_Camera2D.setOrthographicProjection(0.0f, getViewport().getDimension()[0], 0.0f, getViewport().getDimension()[1], 0.001f, 100.f);
		m_Camera2D.lookAt(glm::vec3(0, 0, 10), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0));

		m_Camera3D.setPerspectiveProjection(60.0f, getViewport().getDimension()[0] / getViewport().getDimension()[1], 0.1f, 1024.0f);
		m_Camera3D.lookAt(glm::vec3(0, 0, 30), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0));

        m_GraphEntity = static_cast<GraphEntity*>(entity);
        m_GraphEntity->views().push_back(this);
        m_GraphEntity->listeners().push_back(this);

        return true;
    }

	inline Camera* getCamera3D()
	{
		return &m_Camera3D;
	}

	void draw() override
	{
		glClearColor(0.0, 0.0, 0.0, 1.0);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glDisable(GL_DEPTH_TEST);
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_DST_ALPHA);

		Transformation transformation;

		m_Graph->draw(context(), m_Camera3D, transformation);
	}

	void idle() override
	{
        static bool m_Initialized = false;
        if (!m_Initialized)
        {
            m_Graph->initialize(context());
            m_Initialized = true;
        }

        m_Graph->idle(context());
	}

	void notify(IMessage* message)
	{
		(void) message;
	}

    // ----- Helpers -----

    void checkNodeUID(GPUGraph::Node::ID uid)
    {
        if (!m_NodeMap.containsRemoteID(uid))
        {
            LOG("Node UID %u not found !\n", uid);
            throw;
        }
    }

    void checkEdgeUID(GPUGraph::Edge::ID uid)
    {
        if (!m_EdgeMap.containsRemoteID(uid))
        {
            LOG("Edge UID %u not found !\n", uid);
            throw;
        }
    }

	// ----- Graph Events -----

    void onSetAttribute(const std::string& name, VariableType type, const std::string& value) override
    {
        LOG("onSetAttribute(%s, %i, %s)\n", name.c_str(), (int)type, value.c_str());
    }

    void onAddNode(Node::ID uid, const char* label) override // TODO : Attributes in Variables object
    {
        LOG("onAddNode(%lu, %s)\n", uid, label);

        GPUGraph::Node node;

        // TODO : Emitter system? (Define where particles appear)

        node.Position = 10.0f * glm::vec4
        (
            RANDOM_FLOAT(-1.0, 1.0),
            RANDOM_FLOAT(-1.0, 1.0),
            RANDOM_FLOAT(-1.0, 1.0),
            0.0
        );

        node.Color = glm::vec4(1.0, 1.0, 1.0, 1.0);

        node.Size = 1.0;

        m_Graph->addNode(node);

        static unsigned int node_count = 0;

        GPUGraph::Node::ID nid = node_count;
        m_NodeMap.addRemoteID(uid, nid);

        node_count++;
    }

    void onRemoveNode(Node::ID uid) override
    {
        LOG("onRemoveNode(%lu)\n", uid);
    }

    void onSetNodeAttribute(Node::ID uid, const std::string& name, VariableType type, const std::string& value) override
    {
        // LOG("onSetNodeAttribute(%lu, %s, %i, %s)\n", uid, name.c_str(), (int)type, value.c_str());

        BooleanVariable vbool;
        Vec3Variable vvec3;
        Vec4Variable vvec4;
        FloatVariable vfloat;

        checkNodeUID(uid);

        GPUGraph::Node::ID id = m_NodeMap.getLocalID(uid);

        if ((name == "space:position" || name == "particles:position") && type == RD_VEC3)
        {
            vvec3.set(value);

            GPUGraph::Node node = m_Graph->getNode(id);
            node.Position = glm::vec4(vvec3.value(), 0.0);
            m_Graph->setNode(id, node);

        }
        else if (name == "space:color" && (type == RD_VEC3 || type == RD_VEC4))
        {
            glm::vec4 c;

            if (type == RD_VEC3)
            {
                vvec3.set(value);
                c = glm::vec4(vvec3.value(), 0.0);
            }
            else
            {
                vvec4.set(value);
                c = vvec4.value();
            }

            GPUGraph::Node node = m_Graph->getNode(id);
            node.Color = vvec4.value();
            m_Graph->setNode(id, node);
        }
        else if (name == "space:size" && type == RD_FLOAT)
        {
            vfloat.set(value);

            GPUGraph::Node node = m_Graph->getNode(id);
            node.Size = vfloat.value();
            m_Graph->setNode(id, node);
        }
    }

    void onAddEdge(Edge::ID uid, Node::ID uid1, Node::ID uid2) override
    {
        // LOG("onAddEdge(%lu, %lu, %lu)\n", uid, uid1, uid2);

        GPUGraph::Node::ID nid1 = m_NodeMap.getLocalID(uid1);
        GPUGraph::Node::ID nid2 = m_NodeMap.getLocalID(uid2);

        GPUGraph::Edge edge;

        GPUGraph::Node n1 = m_Graph->getNode(nid1);
        GPUGraph::Node n2 = m_Graph->getNode(nid2);

        edge.SourcePosition = n1.Position;
        edge.SourceColor = n1.Color;

        edge.TargetPosition = n2.Position;
        edge.TargetColor =  n2.Color;

        edge.Width = 0.5; // NOTE : Half of the node size

        m_Graph->addEdge(edge);

        static unsigned int edge_count = 0;

        GPUGraph::Edge::ID eid = edge_count;
        m_EdgeMap.addRemoteID(uid, eid);

        edge_count++;
    }

    void onRemoveEdge(Edge::ID uid) override
    {
        // LOG("onRemoveEdge(%lu)\n", uid);
    }

    void onSetEdgeAttribute(Edge::ID uid, const std::string& name, VariableType type, const std::string& value) override
    {
        // LOG("onSetEdgeAttribute(%lu %s, %i, %s)\n", uid, name.c_str(), (int)type, value.c_str());

        FloatVariable vfloat;
        Vec3Variable vvec3;
        Vec4Variable vvec4;
        StringVariable vstring;

        checkEdgeUID(uid);
        GPUGraph::Edge::ID id = m_EdgeMap.getLocalID(uid);

        if (name == "space:color" && type == RD_VEC4)
        {
            vvec4.set(value);

            GPUGraph::Edge edge = m_Graph->getEdge(id);
            edge.SourceColor = vvec4.value();
            edge.TargetColor = vvec4.value();
            m_Graph->setEdge(id, edge);
        }
        else if (name == "space:color1" && type == RD_VEC4)
        {
            vvec4.set(value);

            GPUGraph::Edge edge = m_Graph->getEdge(id);
            edge.SourceColor = vvec4.value();
            m_Graph->setEdge(id, edge);
        }
        else if (name == "space:color2" && type == RD_VEC4)
        {
            vvec4.set(value);

            GPUGraph::Edge edge = m_Graph->getEdge(id);
            edge.TargetColor = vvec4.value();
            m_Graph->setEdge(id, edge);
        }
        else if (name == "space:width" && type == RD_FLOAT)
        {
            vfloat.set(value);

            GPUGraph::Edge edge = m_Graph->getEdge(id);
            edge.Width = vfloat.value();
            m_Graph->setEdge(id, edge);
        }
    }

	virtual IVariable* getAttribute(const std::string& name)
	{
		(void) name;
		return NULL;
	}

    virtual IVariable* getNodeAttribute(Node::ID id, std::string& name)
    {
    	(void) id;
    	(void) name;
    	return NULL;
    }

    virtual IVariable* getEdgeAttribute(Edge::ID id, std::string& name)
    {
    	(void) id;
    	(void) name;
    	return NULL;
    }

    inline GraphContext* context() { return static_cast<GraphContext*>(m_GraphEntity->context()); }

    inline GraphModel* model() { return static_cast<GraphModel*>(m_GraphEntity->model()); }

private:
	GraphEntity* m_GraphEntity;

	Camera m_Camera2D;
	Camera m_Camera3D;

	Font* m_Font;

	GPUGraph* m_Graph;
    TranslationMap<GPUGraph::Node::ID, unsigned int> m_NodeMap;
    TranslationMap<GPUGraph::Edge::ID, unsigned int> m_EdgeMap;
};

<|endoftext|>


<commit_before>#include <random>
#include <iostream>

using namespace std;

void
printIntVector( vector<int> &numbers ) {
    for( vector<int>::iterator it=numbers.begin(); it!=numbers.end(); it++) {
        cout << *it << "  " ;
    }
    cout << endl;
}

bool comp( const int &n1, const int &n2 ) {
    return ( n1 > n2 );
}

vector<int>
sortUsingHeapApi( vector<int> &numbers) {
    vector<int> output;

    make_heap( numbers.begin(), numbers.end(), comp );

    while( not numbers.empty() ) {
        // CRITICAL
        pop_heap( numbers.begin(), numbers.end(), comp );
        output.push_back( numbers.back() );
        numbers.pop_back();
    }
    return output;
}

int main() {
    vector<int> numbers;
    vector<int> sorted;

    for(int i=0; i<10; i++) {
        numbers.push_back( rand() % 2048 );
    }
    printIntVector(numbers);
    sorted = sortUsingHeapApi(numbers);
    printIntVector(sorted);
}

<commit_msg>pop_back needs comp function<commit_after>#include <random>
#include <iostream>

using namespace std;

void
printIntVector( vector<int> &numbers ) {
    for( vector<int>::iterator it=numbers.begin(); it!=numbers.end(); it++) {
        cout << *it << "  " ;
    }
    cout << endl;
}

bool comp( const int &n1, const int &n2 ) {
    return ( n1 > n2 );
}

vector<int>
sortUsingHeapApi( vector<int> &numbers) {
    vector<int> output;

    make_heap( numbers.begin(), numbers.end(), comp );

    while( not numbers.empty() ) {
        // CRITICAL COMMENT
        // pop_heap needs comp function to re-arrange
        // properly.
        pop_heap( numbers.begin(), numbers.end(), comp );
        output.push_back( numbers.back() );
        numbers.pop_back();
    }
    return output;
}

int main() {
    vector<int> numbers;
    vector<int> sorted;

    for(int i=0; i<10; i++) {
        numbers.push_back( rand() % 2048 );
    }
    printIntVector(numbers);
    sorted = sortUsingHeapApi(numbers);
    printIntVector(sorted);
}

<|endoftext|>


<commit_before>/*
Library EDK - How to use Extensible Development Kit
Copyright (C) 2013 Eduardo Moura Sales Martins
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
email: edimartin@gmail.com.br

AV: Walmor M. de Souza 392 Casa
Gravatai RS Brazil 94065100
*/

//Include the edk::vector::Array
#include "edk/vector/Array.h"

int main(){
    edk::int32 size1 = 5;
    //create an array with 32 bit integer where can alocate five positions
    edk::vector::Array<edk::int32> n1(size1);
    //fill the array with values
    for(edk::int32 i=0;i<size1;i++){
        //set the value
        n1.set(i,i+1);
    }
    //print the array values
    printf("\nArray N1 with size %u have values: ",n1.size());
    for(edk::int32 i=0;i<size1;i++){
        //set the value
        printf(" [%d]",n1.get(i));
    }
    printf(";");fflush(stdout);

    //Create a new array
    edk::int32 size2 = 4;
    //create the new array with 4 positions
    edk::vector::Array<edk::int32> n2(size2);
    //fill the second array
    for(edk::int32 i=0;i<size2;i++){
        //set the value
        n2.set(i,size2-i);
    }
    //print the array values
    printf("\nArray N2 with size %u have values: ",n2.size());
    for(edk::int32 i=0;i<size2;i++){
        //set the value
        printf(" [%d]",n2.get(i));
    }
    printf(";");fflush(stdout);

    //copy the vector 1 to vector 2
    n2 = n1;

    //print the array values

    //print the array values
    printf("\nAfter copy N1 to N2. The array N2 with size %u have values: ",n2.size());
    size2 = n2.size();
    for(edk::int32 i=0;i<size2;i++){
        //set the value
        printf(" [%d]",n2.get(i));
    }
    printf(";");fflush(stdout);

    printf("\n\n");
    return 0;
}
<commit_msg>I change the copy from the classes but I forgot to change this on the example<commit_after>/*
Library EDK - How to use Extensible Development Kit
Copyright (C) 2013 Eduardo Moura Sales Martins
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
email: edimartin@gmail.com.br

AV: Walmor M. de Souza 392 Casa
Gravatai RS Brazil 94065100
*/

//Include the edk::vector::Array
#include "edk/vector/Array.h"

int main(){
    edk::int32 size1 = 5;
    //create an array with 32 bit integer where can alocate five positions
    edk::vector::Array<edk::int32> n1(size1);
    //fill the array with values
    for(edk::int32 i=0;i<size1;i++){
        //set the value
        n1.set(i,i+1);
    }
    //print the array values
    printf("\nArray N1 with size %u have values: ",n1.size());
    for(edk::int32 i=0;i<size1;i++){
        //set the value
        printf(" [%d]",n1.get(i));
    }
    printf(";");fflush(stdout);

    //Create a new array
    edk::int32 size2 = 4;
    //create the new array with 4 positions
    edk::vector::Array<edk::int32> n2(size2);
    //fill the second array
    for(edk::int32 i=0;i<size2;i++){
        //set the value
        n2.set(i,size2-i);
    }
    //print the array values
    printf("\nArray N2 with size %u have values: ",n2.size());
    for(edk::int32 i=0;i<size2;i++){
        //set the value
        printf(" [%d]",n2.get(i));
    }
    printf(";");fflush(stdout);

    //copy the vector 1 to vector 2
    n2.cloneFrom(n1);

    //print the array values

    //print the array values
    printf("\nAfter copy N1 to N2. The array N2 with size %u have values: ",n2.size());
    size2 = n2.size();
    for(edk::int32 i=0;i<size2;i++){
        //set the value
        printf(" [%d]",n2.get(i));
    }
    printf(";");fflush(stdout);

    printf("\n\n");
    return 0;
}
<|endoftext|>


<commit_before>/**
 * @file LatentSvmDetector_.cpp
 * @brief mex interface for LatentSvmDetector
 * @author Kota Yamaguchi
 * @date 2012
 */
#include "mexopencv.hpp"
using namespace std;
using namespace cv;

namespace {

/// Last object id to allocate
int last_id = 0;
/// Object container
map<int,LatentSvmDetector> obj_;

/// Alias for argument number check
inline void nargchk(bool cond)
{
    if (!cond)
        mexErrMsgIdAndTxt("mexopencv:error","Wrong number of arguments");
}

/** Convert object detections to struct array
 * @param vo vector of detections
 */
mxArray* ObjectDetection2Struct(
    const vector<LatentSvmDetector::ObjectDetection> vo,
    const vector<string>& classNames)
{
    const char* fields[] = {"rect","score","class"};
    MxArray m(fields,3,1,vo.size());
    for (int i=0; i<vo.size(); ++i) {
        m.set("rect", vo[i].rect, i);
        m.set("score", vo[i].score, i);
        m.set("class", classNames[vo[i].classID], i);
    }
    return m;
}

} // local scope

/**
 * Main entry called from Matlab
 * @param nlhs number of left-hand-side arguments
 * @param plhs pointers to mxArrays in the left-hand-side
 * @param nrhs number of right-hand-side arguments
 * @param prhs pointers to mxArrays in the right-hand-side
 */
void mexFunction( int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[] )
{
    nargchk(nrhs>=2 && nlhs<=2);
    vector<MxArray> rhs(prhs,prhs+nrhs);
    int id = rhs[0].toInt();
    string method(rhs[1].toString());

    // Constructor call
    if (method == "new") {
        nargchk(nlhs<=1 && nrhs<=4);
        obj_[++last_id] = LatentSvmDetector();
        // Due to the buggy implementation of LatentSvmDetector in OpenCV
        // we cannot use the constructor syntax other than empty args.
        plhs[0] = MxArray(last_id);
        return;
    }

    // Big operation switch
    LatentSvmDetector& obj = obj_[id];
    if (method == "delete") {
        nargchk(nrhs==2 && nlhs==0);
        obj_.erase(id);
    }
    else if (method == "clear") {
        nargchk(nrhs==2 && nlhs==0);
        obj.clear();
    }
    else if (method == "empty") {
        nargchk(nrhs==2 && nlhs<=1);
        plhs[0] = MxArray(obj.empty());
    }
    else if (method == "load") {
        nargchk(nrhs<=4 && nlhs<=1);
        plhs[0] = (nrhs==3) ? MxArray(obj.load(rhs[2].toVector<string>())) :
            MxArray(obj.load(rhs[2].toVector<string>(), rhs[3].toVector<string>()));
    }
    else if (method == "detect") {
        nargchk(nrhs>=3 && (nrhs%2)==1 && nlhs<=1);
        Mat image((rhs[2].isUint8()) ? rhs[2].toMat() : rhs[2].toMat(CV_32F));
        vector<LatentSvmDetector::ObjectDetection> objectDetections;
        float overlapThreshold=0.5f;
        int numThreads=-1;
        for (int i=3; i<nrhs; i+=2) {
            string key(rhs[i].toString());
            if (key=="OverlapThreshold")
                overlapThreshold = rhs[i+1].toDouble();
            else if (key=="NumThreads")
                numThreads = rhs[i+1].toInt();
            else
                mexErrMsgIdAndTxt("mexopencv:error","Unrecognized option %s", key.c_str());
        }
        obj.detect(image,objectDetections,overlapThreshold,numThreads);
        plhs[0] = ObjectDetection2Struct(objectDetections, obj.getClassNames());
    }
    else if (method == "getClassNames") {
        nargchk(nrhs==2 && nlhs<=1);
        plhs[0] = MxArray(obj.getClassNames());
    }
    else if (method == "getClassCount") {
        nargchk(nrhs==2 && nlhs<=1);
        plhs[0] = MxArray(static_cast<int>(obj.getClassCount()));
    }
    else
        mexErrMsgIdAndTxt("mexopencv:error","Unrecognized operation %s", method.c_str());
}
<commit_msg>fix opencv_contrib/latentsvm module functions<commit_after>/**
 * @file LSVMDetector_.cpp
 * @brief mex interface for LSVMDetector
 * @author Kota Yamaguchi
 * @date 2012
 */
#include "mexopencv.hpp"
#include "opencv2/latentsvm.hpp"
using namespace std;
using namespace cv;
using namespace cv::lsvm;

namespace {

/// Last object id to allocate
int last_id = 0;
/// Object container
map<int,Ptr<LSVMDetector> > obj_;

/// Alias for argument number check
inline void nargchk(bool cond)
{
    if (!cond)
        mexErrMsgIdAndTxt("mexopencv:error","Wrong number of arguments");
}

/** Convert object detections to struct array
 * @param vo vector of detections
 */
mxArray* ObjectDetection2Struct(
    const vector<LSVMDetector::ObjectDetection>& vo,
    const vector<string>& classNames)
{
    const char* fields[] = {"rect", "score", "class"};
    MxArray m(fields, 3, 1, vo.size());
    for (size_t i=0; i<vo.size(); ++i) {
        m.set("rect", vo[i].rect, i);
        m.set("score", vo[i].score, i);
        m.set("class", classNames[vo[i].classID], i);
    }
    return m;
}

} // local scope

/**
 * Main entry called from Matlab
 * @param nlhs number of left-hand-side arguments
 * @param plhs pointers to mxArrays in the left-hand-side
 * @param nrhs number of right-hand-side arguments
 * @param prhs pointers to mxArrays in the right-hand-side
 */
void mexFunction( int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[] )
{
    nargchk(nrhs>=2 && nlhs<=2);
    vector<MxArray> rhs(prhs,prhs+nrhs);
    int id = rhs[0].toInt();
    string method(rhs[1].toString());

    // Constructor call
    if (method == "new") {
        nargchk((nrhs==3 || nrhs==4) && nlhs<=1);
        obj_[++last_id] = (nrhs == 3) ?
            LSVMDetector::create(rhs[2].toVector<string>()) :
            LSVMDetector::create(rhs[2].toVector<string>(), rhs[3].toVector<string>());
        plhs[0] = MxArray(last_id);
        return;
    }

    // Big operation switch
    Ptr<LSVMDetector> obj = obj_[id];
    if (method == "delete") {
        nargchk(nrhs==2 && nlhs==0);
        obj_.erase(id);
    }
    else if (method == "isEmpty") {
        nargchk(nrhs==2 && nlhs<=1);
        plhs[0] = MxArray(obj->isEmpty());
    }
    else if (method == "detect") {
        nargchk(nrhs>=3 && (nrhs%2)==1 && nlhs<=1);
        float overlapThreshold = 0.5f;
        for (int i=3; i<nrhs; i+=2) {
            string key(rhs[i].toString());
            if (key=="OverlapThreshold")
                overlapThreshold = rhs[i+1].toDouble();
            else
                mexErrMsgIdAndTxt("mexopencv:error","Unrecognized option %s", key.c_str());
        }
        Mat image(rhs[2].toMat(rhs[2].isUint8() ? CV_8U : CV_32F));
        vector<LSVMDetector::ObjectDetection> objects;
        obj->detect(image, objects, overlapThreshold);
        plhs[0] = ObjectDetection2Struct(objects, obj->getClassNames());
    }
    else if (method == "getClassNames") {
        nargchk(nrhs==2 && nlhs<=1);
        plhs[0] = MxArray(obj->getClassNames());
    }
    else if (method == "getClassCount") {
        nargchk(nrhs==2 && nlhs<=1);
        plhs[0] = MxArray(static_cast<int>(obj->getClassCount()));
    }
    else
        mexErrMsgIdAndTxt("mexopencv:error","Unrecognized operation %s", method.c_str());
}
<|endoftext|>


<commit_before>#include <agency/execution_policy.hpp>
#include <mutex>
#include <iostream>
#include <thread>

int main()
{
  int ball = 0;
  std::string names[2] = {"ping", "pong"};
  std::mutex mut;

  // create two concurrent agents
  agency::bulk_invoke(agency::con(2), [&](agency::concurrent_agent& self)
  {
    auto name = names[self.index()];

    // play for 20 volleys
    for(int next_state = self.index();
        next_state < 20;
        next_state += 2)
    {
      // wait for the next volley
      while(ball != next_state)
      {
        mut.lock();
        std::cout << name << " waiting for return" << std::endl;
        mut.unlock();

        std::this_thread::sleep_for(std::chrono::seconds(1));
      }

      // return the ball
      mut.lock();
      ball += 1;
      std::cout << name << "! ball is now " << ball << std::endl;
      mut.unlock();

      std::this_thread::sleep_for(std::chrono::seconds(1));
    }
  });

  return 0;
}

<commit_msg>tweak formatting<commit_after>#include <agency/execution_policy.hpp>
#include <mutex>
#include <iostream>
#include <thread>

int main()
{
  int ball = 0;
  std::string names[2] = {"ping", "pong"};
  std::mutex mut;

  // create two concurrent agents
  agency::bulk_invoke(agency::con(2), [&](agency::concurrent_agent& self)
  {
    auto name = names[self.index()];

    // play for 20 volleys
    for(int next_state = self.index(); next_state < 20; next_state += 2)
    {
      // wait for the next volley
      while(ball != next_state)
      {
        mut.lock();
        std::cout << name << " waiting for return" << std::endl;
        mut.unlock();

        std::this_thread::sleep_for(std::chrono::seconds(1));
      }

      // return the ball
      mut.lock();
      ball += 1;
      std::cout << name << "! ball is now " << ball << std::endl;
      mut.unlock();

      std::this_thread::sleep_for(std::chrono::seconds(1));
    }
  });

  return 0;
}

<|endoftext|>