<commit_before>/*
** Author(s):
**  - Herve Cuche <hcuche@aldebaran-robotics.com>
**
** Copyright (C) 2010, 2012 Aldebaran Robotics
*/

#include <gtest/gtest.h>
#include <map>
#include <qimessaging/datastream.hpp>
#include <qimessaging/buffer.hpp>

#include <limits.h>

TEST(TestBind, serializeInt)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  d << 12;

  qi::DataStream  d2(buf);
  int i;
  d2 >> i;

  EXPECT_EQ(12, i);
}

TEST(TestBind, serializeInts)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  d << 12;
  d << 13;
  d << 14;

  qi::DataStream  d2(buf);
  int i1;
  d2 >> i1;
  int i2;
  d2 >> i2;
  int i3;
  d2 >> i3;

  EXPECT_EQ(12, i1);
  EXPECT_EQ(13, i2);
  EXPECT_EQ(14, i3);
}

TEST(TestBind, serializeBool)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  d << true;

  qi::DataStream  d2(buf);
  bool b;
  d2 >> b;

  EXPECT_EQ(true, b);
}

TEST(TestBind, serializeBools)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  d << true;
  d << false;
  d << false;

  qi::DataStream  d2(buf);
  bool b1;
  d2 >> b1;
  bool b2;
  d2 >> b2;
  bool b3;
  d2 >> b3;

  EXPECT_EQ(true, b1);
  EXPECT_EQ(false, b2);
  EXPECT_EQ(false, b3);
}

TEST(TestBind, serializeChar)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  d << 'c';

  qi::DataStream  d2(buf);
  char b;
  d2 >> b;

  EXPECT_EQ('c', b);
}

TEST(TestBind, serializeChars)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  d << 'c';
  d << 'd';
  d << 'e';

  qi::DataStream  d2(buf);
  char b1;
  d2 >> b1;
  char b2;
  d2 >> b2;
  char b3;
  d2 >> b3;

  EXPECT_EQ('c', b1);
  EXPECT_EQ('d', b2);
  EXPECT_EQ('e', b3);
}

TEST(TestBind, serializeUInt)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  unsigned int ui1 = UINT_MAX;
  d << ui1;

  qi::DataStream  d2(buf);
  unsigned int ui2;
  d2 >> ui2;

  EXPECT_EQ(ui1, ui2);
}

TEST(TestBind, serializeUInts)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  unsigned int ui1 = UINT_MAX;
  unsigned int ui2 = 0;
  unsigned int ui3 = 456789;
  d << ui1;
  d << ui2;
  d << ui3;

  qi::DataStream  d2(buf);
  unsigned int ui4;
  d2 >> ui4;
  unsigned int ui5;
  d2 >> ui5;
  unsigned int ui6;
  d2 >> ui6;

  EXPECT_EQ(ui1, ui4);
  EXPECT_EQ(ui2, ui5);
  EXPECT_EQ(ui3, ui6);
}

TEST(TestBind, serializeUChar)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  unsigned char ui1 = UCHAR_MAX;
  d << ui1;

  qi::DataStream  d2(buf);
  unsigned char ui2;
  d2 >> ui2;

  EXPECT_EQ(ui1, ui2);
}

TEST(TestBind, serializeUChars)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  unsigned char ui1 = UCHAR_MAX;
  unsigned char ui2 = 0;
  unsigned char ui3 = 456789;
  d << ui1;
  d << ui2;
  d << ui3;

  qi::DataStream  d2(buf);
  unsigned char ui4;
  d2 >> ui4;
  unsigned char ui5;
  d2 >> ui5;
  unsigned char ui6;
  d2 >> ui6;

  EXPECT_EQ(ui1, ui4);
  EXPECT_EQ(ui2, ui5);
  EXPECT_EQ(ui3, ui6);
}

TEST(TestBind, serializeFloat)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  float f = 1.25f;
  d << f;

  qi::DataStream  d2(buf);
  float b;
  d2 >> b;

  EXPECT_EQ(f, b);
}

TEST(TestBind, serializeFloats)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  float f1 = 1.25f;
  float f2 = -1.25f;
  float f3 = 0.0f;
  d << f1;
  d << f2;
  d << f3;

  qi::DataStream  d2(buf);
  float b1;
  d2 >> b1;
  float b2;
  d2 >> b2;
  float b3;
  d2 >> b3;

  EXPECT_EQ(f1, b1);
  EXPECT_EQ(f2, b2);
  EXPECT_EQ(f3, b3);
}

TEST(TestBind, serializeDouble)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  double f = 1.25;
  d << f;

  qi::DataStream  d2(buf);
  double b;
  d2 >> b;

  EXPECT_EQ(f, b);
}

TEST(TestBind, serializeDoubles)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  double f1 = 1.25;
  double f2 = -1.25;
  double f3 = 0.0;
  d << f1;
  d << f2;
  d << f3;

  qi::DataStream  d2(buf);
  double b1;
  d2 >> b1;
  double b2;
  d2 >> b2;
  double b3;
  d2 >> b3;

  EXPECT_EQ(f1, b1);
  EXPECT_EQ(f2, b2);
  EXPECT_EQ(f3, b3);
}

TEST(TestBind, serializeString)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  std::string s = "1.25";
  d << s;

  qi::DataStream  d2(buf);
  std::string s2;
  d2 >> s2;

  EXPECT_EQ(s, s2);
}

TEST(TestBind, serializeStrings)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  std::string f1 = "1.25";
  std::string f2 = "-1.25";
  std::string f3 = "0.0";
  d << f1;
  d << f2;
  d << f3;

  qi::DataStream  d2(buf);
  std::string b1;
  d2 >> b1;
  std::string b2;
  d2 >> b2;
  std::string b3;
  d2 >> b3;

  EXPECT_EQ(f1, b1);
  EXPECT_EQ(f2, b2);
  EXPECT_EQ(f3, b3);
}

TEST(TestBind, serializeCChar)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  std::string s = "1.25";
  d << s.c_str();

  qi::DataStream  d2(buf);
  std::string s2;
  d2 >> s2;

  EXPECT_EQ(s, s2);
}

TEST(TestBind, serializeCChars)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  std::string f1 = "1.25";
  std::string f2 = "-1.25";
  std::string f3 = "0.0";
  d << f1.c_str();
  d << f2.c_str();
  d << f3.c_str();

  qi::DataStream  d2(buf);
  std::string b1;
  d2 >> b1;
  std::string b2;
  d2 >> b2;
  std::string b3;
  d2 >> b3;

  EXPECT_EQ(f1, b1);
  EXPECT_EQ(f2, b2);
  EXPECT_EQ(f3, b3);
}

TEST(TestBind, serializeVectorString)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  std::vector<std::string> vs;
  vs.push_back("toto");
  vs.push_back("tutu");
  vs.push_back("tata");
  d << vs;

  qi::DataStream  d2(buf);
  std::vector<std::string> vs1;
  d2 >> vs1;

  EXPECT_EQ(vs[0], vs1[0]);
  EXPECT_EQ(vs[1], vs1[1]);
  EXPECT_EQ(vs[2], vs1[2]);
}

TEST(TestBind, serializeVectorStrings)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  std::vector<std::string> vs;
  vs.push_back("toto");
  vs.push_back("tutu");
  vs.push_back("tata");

  d << vs;
  d << vs;

  qi::DataStream  d2(buf);
  std::vector<std::string> vs1;
  d2 >> vs1;
  std::vector<std::string> vs2;
  d2 >> vs2;

  EXPECT_EQ(vs[0], vs1[0]);
  EXPECT_EQ(vs[1], vs1[1]);
  EXPECT_EQ(vs[2], vs1[2]);
  EXPECT_EQ(vs[0], vs2[0]);
  EXPECT_EQ(vs[1], vs2[1]);
  EXPECT_EQ(vs[2], vs2[2]);
}

TEST(TestBind, serializeAllTypes)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  ds(buf);

  bool b = true;
  char c = 'c';
  int i = 42;
  unsigned char uc = UCHAR_MAX;
  unsigned int ui = UINT_MAX;
  float f = 23.5f;
  double d = 42.42;
  std::string s("test::string");

  ds << b;
  ds << c;
  ds << i;
  ds << uc;
  ds << ui;
  ds << f;
  ds << d;
  ds << s;
  ds << s.c_str();

  qi::DataStream  d2(buf);
  bool b1;
  char c1;
  int i1;
  unsigned char uc1;
  unsigned int ui1;
  float f1;
  double d1;
  std::string s1;
  std::string s2;
  d2 >> b1;
  d2 >> c1;
  d2 >> i1;
  d2 >> uc1;
  d2 >> ui1;
  d2 >> f1;
  d2 >> d1;
  d2 >> s1;
  d2 >> s2;

  EXPECT_EQ(b, b1);
  EXPECT_EQ(c, c1);
  EXPECT_EQ(i, i1);
  EXPECT_EQ(uc, uc1);
  EXPECT_EQ(ui, ui1);
  EXPECT_EQ(f, f1);
  EXPECT_EQ(d, d1);
  EXPECT_EQ(s, s1);
  EXPECT_EQ(s, s2);
}

<commit_msg>Fix overflow in serialization tests.<commit_after>/*
** Author(s):
**  - Herve Cuche <hcuche@aldebaran-robotics.com>
**
** Copyright (C) 2010, 2012 Aldebaran Robotics
*/

#include <gtest/gtest.h>
#include <map>
#include <qimessaging/datastream.hpp>
#include <qimessaging/buffer.hpp>

#include <limits.h>

TEST(TestBind, serializeInt)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  d << 12;

  qi::DataStream  d2(buf);
  int i;
  d2 >> i;

  EXPECT_EQ(12, i);
}

TEST(TestBind, serializeInts)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  d << 12;
  d << 13;
  d << 14;

  qi::DataStream  d2(buf);
  int i1;
  d2 >> i1;
  int i2;
  d2 >> i2;
  int i3;
  d2 >> i3;

  EXPECT_EQ(12, i1);
  EXPECT_EQ(13, i2);
  EXPECT_EQ(14, i3);
}

TEST(TestBind, serializeBool)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  d << true;

  qi::DataStream  d2(buf);
  bool b;
  d2 >> b;

  EXPECT_EQ(true, b);
}

TEST(TestBind, serializeBools)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  d << true;
  d << false;
  d << false;

  qi::DataStream  d2(buf);
  bool b1;
  d2 >> b1;
  bool b2;
  d2 >> b2;
  bool b3;
  d2 >> b3;

  EXPECT_EQ(true, b1);
  EXPECT_EQ(false, b2);
  EXPECT_EQ(false, b3);
}

TEST(TestBind, serializeChar)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  d << 'c';

  qi::DataStream  d2(buf);
  char b;
  d2 >> b;

  EXPECT_EQ('c', b);
}

TEST(TestBind, serializeChars)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  d << 'c';
  d << 'd';
  d << 'e';

  qi::DataStream  d2(buf);
  char b1;
  d2 >> b1;
  char b2;
  d2 >> b2;
  char b3;
  d2 >> b3;

  EXPECT_EQ('c', b1);
  EXPECT_EQ('d', b2);
  EXPECT_EQ('e', b3);
}

TEST(TestBind, serializeUInt)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  unsigned int ui1 = UINT_MAX;
  d << ui1;

  qi::DataStream  d2(buf);
  unsigned int ui2;
  d2 >> ui2;

  EXPECT_EQ(ui1, ui2);
}

TEST(TestBind, serializeUInts)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  unsigned int ui1 = UINT_MAX;
  unsigned int ui2 = 0;
  unsigned int ui3 = 456789;
  d << ui1;
  d << ui2;
  d << ui3;

  qi::DataStream  d2(buf);
  unsigned int ui4;
  d2 >> ui4;
  unsigned int ui5;
  d2 >> ui5;
  unsigned int ui6;
  d2 >> ui6;

  EXPECT_EQ(ui1, ui4);
  EXPECT_EQ(ui2, ui5);
  EXPECT_EQ(ui3, ui6);
}

TEST(TestBind, serializeUChar)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  unsigned char ui1 = UCHAR_MAX;
  d << ui1;

  qi::DataStream  d2(buf);
  unsigned char ui2;
  d2 >> ui2;

  EXPECT_EQ(ui1, ui2);
}

TEST(TestBind, serializeUChars)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  unsigned char ui1 = UCHAR_MAX;
  unsigned char ui2 = 0;
  unsigned char ui3 = 45;
  d << ui1;
  d << ui2;
  d << ui3;

  qi::DataStream  d2(buf);
  unsigned char ui4;
  d2 >> ui4;
  unsigned char ui5;
  d2 >> ui5;
  unsigned char ui6;
  d2 >> ui6;

  EXPECT_EQ(ui1, ui4);
  EXPECT_EQ(ui2, ui5);
  EXPECT_EQ(ui3, ui6);
}

TEST(TestBind, serializeFloat)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  float f = 1.25f;
  d << f;

  qi::DataStream  d2(buf);
  float b;
  d2 >> b;

  EXPECT_EQ(f, b);
}

TEST(TestBind, serializeFloats)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  float f1 = 1.25f;
  float f2 = -1.25f;
  float f3 = 0.0f;
  d << f1;
  d << f2;
  d << f3;

  qi::DataStream  d2(buf);
  float b1;
  d2 >> b1;
  float b2;
  d2 >> b2;
  float b3;
  d2 >> b3;

  EXPECT_EQ(f1, b1);
  EXPECT_EQ(f2, b2);
  EXPECT_EQ(f3, b3);
}

TEST(TestBind, serializeDouble)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  double f = 1.25;
  d << f;

  qi::DataStream  d2(buf);
  double b;
  d2 >> b;

  EXPECT_EQ(f, b);
}

TEST(TestBind, serializeDoubles)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  double f1 = 1.25;
  double f2 = -1.25;
  double f3 = 0.0;
  d << f1;
  d << f2;
  d << f3;

  qi::DataStream  d2(buf);
  double b1;
  d2 >> b1;
  double b2;
  d2 >> b2;
  double b3;
  d2 >> b3;

  EXPECT_EQ(f1, b1);
  EXPECT_EQ(f2, b2);
  EXPECT_EQ(f3, b3);
}

TEST(TestBind, serializeString)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  std::string s = "1.25";
  d << s;

  qi::DataStream  d2(buf);
  std::string s2;
  d2 >> s2;

  EXPECT_EQ(s, s2);
}

TEST(TestBind, serializeStrings)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  std::string f1 = "1.25";
  std::string f2 = "-1.25";
  std::string f3 = "0.0";
  d << f1;
  d << f2;
  d << f3;

  qi::DataStream  d2(buf);
  std::string b1;
  d2 >> b1;
  std::string b2;
  d2 >> b2;
  std::string b3;
  d2 >> b3;

  EXPECT_EQ(f1, b1);
  EXPECT_EQ(f2, b2);
  EXPECT_EQ(f3, b3);
}

TEST(TestBind, serializeCChar)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  std::string s = "1.25";
  d << s.c_str();

  qi::DataStream  d2(buf);
  std::string s2;
  d2 >> s2;

  EXPECT_EQ(s, s2);
}

TEST(TestBind, serializeCChars)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  std::string f1 = "1.25";
  std::string f2 = "-1.25";
  std::string f3 = "0.0";
  d << f1.c_str();
  d << f2.c_str();
  d << f3.c_str();

  qi::DataStream  d2(buf);
  std::string b1;
  d2 >> b1;
  std::string b2;
  d2 >> b2;
  std::string b3;
  d2 >> b3;

  EXPECT_EQ(f1, b1);
  EXPECT_EQ(f2, b2);
  EXPECT_EQ(f3, b3);
}

TEST(TestBind, serializeVectorString)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  std::vector<std::string> vs;
  vs.push_back("toto");
  vs.push_back("tutu");
  vs.push_back("tata");
  d << vs;

  qi::DataStream  d2(buf);
  std::vector<std::string> vs1;
  d2 >> vs1;

  EXPECT_EQ(vs[0], vs1[0]);
  EXPECT_EQ(vs[1], vs1[1]);
  EXPECT_EQ(vs[2], vs1[2]);
}

TEST(TestBind, serializeVectorStrings)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  d(buf);
  std::vector<std::string> vs;
  vs.push_back("toto");
  vs.push_back("tutu");
  vs.push_back("tata");

  d << vs;
  d << vs;

  qi::DataStream  d2(buf);
  std::vector<std::string> vs1;
  d2 >> vs1;
  std::vector<std::string> vs2;
  d2 >> vs2;

  EXPECT_EQ(vs[0], vs1[0]);
  EXPECT_EQ(vs[1], vs1[1]);
  EXPECT_EQ(vs[2], vs1[2]);
  EXPECT_EQ(vs[0], vs2[0]);
  EXPECT_EQ(vs[1], vs2[1]);
  EXPECT_EQ(vs[2], vs2[2]);
}

TEST(TestBind, serializeAllTypes)
{
  qi::Buffer     *buf = new qi::Buffer();
  qi::DataStream  ds(buf);

  bool b = true;
  char c = 'c';
  int i = 42;
  unsigned char uc = UCHAR_MAX;
  unsigned int ui = UINT_MAX;
  float f = 23.5f;
  double d = 42.42;
  std::string s("test::string");

  ds << b;
  ds << c;
  ds << i;
  ds << uc;
  ds << ui;
  ds << f;
  ds << d;
  ds << s;
  ds << s.c_str();

  qi::DataStream  d2(buf);
  bool b1;
  char c1;
  int i1;
  unsigned char uc1;
  unsigned int ui1;
  float f1;
  double d1;
  std::string s1;
  std::string s2;
  d2 >> b1;
  d2 >> c1;
  d2 >> i1;
  d2 >> uc1;
  d2 >> ui1;
  d2 >> f1;
  d2 >> d1;
  d2 >> s1;
  d2 >> s2;

  EXPECT_EQ(b, b1);
  EXPECT_EQ(c, c1);
  EXPECT_EQ(i, i1);
  EXPECT_EQ(uc, uc1);
  EXPECT_EQ(ui, ui1);
  EXPECT_EQ(f, f1);
  EXPECT_EQ(d, d1);
  EXPECT_EQ(s, s1);
  EXPECT_EQ(s, s2);
}

<|endoftext|>


<commit_before><commit_msg>Bugfix: add missing `#include` line.<commit_after><|endoftext|>


<commit_before>//=============================================================================================================
/**
 * @file     signalmodel.cpp
 * @author   Ruben Dörfel <doerfelruben@aol.com>
 * @since    0.1.9
 * @date     December, 2021
 *
 * @section  LICENSE
 *
 * Copyright (C) 2021, Ruben Dörfel. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that
 * the following conditions are met:
 *     * Redistributions of source code must retain the above copyright notice, this list of conditions and the
 *       following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
 *       the following disclaimer in the documentation and/or other materials provided with the distribution.
 *     * Neither the name of MNE-CPP authors nor the names of its contributors may be used
 *       to endorse or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 *
 * @brief    signalModel class definition.
 *
 */

//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "hpimodelparameters.h"
#include "signalmodel.h"
#include <utils/mnemath.h>
#include <iostream>

//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <qmath.h>

//=============================================================================================================
// EIGEN INCLUDES
//=============================================================================================================

#include <Eigen/Core>

//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace INVERSELIB;
using namespace Eigen;

//=============================================================================================================
// DEFINE GLOBAL METHODS
//=============================================================================================================

//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================

MatrixXd SignalModel::fitData(const HpiModelParameters& hpiModelParameters, const MatrixXd& matData)
{

    if(checkEmpty(hpiModelParameters)) {
        MatrixXd matTopo;
        return matTopo;
    }

    bool bParametersChanged = m_modelParameters != hpiModelParameters;
    bool bDimensionsChanged = m_iCurrentModelCols != matData.cols();

    if(bDimensionsChanged || bParametersChanged) {
        m_iCurrentModelCols = matData.cols();
        m_modelParameters = hpiModelParameters;
        selectModelAndCompute();
    }

    MatrixXd matTopo = m_matInverseSignalModel * matData.transpose();
    return matTopo;
}

//=============================================================================================================

bool SignalModel::checkDataDimensions(const int iCols)
{
    bool bHasChanged = false;
    if(iCols != m_iCurrentModelCols) {
        m_iCurrentModelCols = iCols;
        bHasChanged = true;
    }
    return bHasChanged;
}

//=============================================================================================================

bool SignalModel::checkModelParameters(const HpiModelParameters& hpiModelParameters)
{
    bool bHasChanged = false;
    if((m_modelParameters.iSampleFreq() != hpiModelParameters.iSampleFreq()) ||
        (m_modelParameters.iLineFreq() != hpiModelParameters.iLineFreq()) ||
        (m_modelParameters.iNHpiCoils() != hpiModelParameters.iNHpiCoils()) ||
        (m_modelParameters.vecHpiFreqs() != hpiModelParameters.vecHpiFreqs()) ||
        (m_modelParameters.bBasic() != hpiModelParameters.bBasic())) {
        bHasChanged = true;
        m_modelParameters = hpiModelParameters;
    }
    return bHasChanged;
}

//=============================================================================================================

bool SignalModel::checkEmpty(const HpiModelParameters& hpiModelParameters)
{
    if(hpiModelParameters.vecHpiFreqs().empty()) {
        std::cout << "SignalModel::checkEmpty - no Hpi frequencies set" << std::endl;
        return true;
    } else if(hpiModelParameters.iSampleFreq() == 0) {
        std::cout << "SignalModel::checkEmpty - no sampling frequencies set" << std::endl;
        return true;
    }
    return false;
}

//=============================================================================================================

void SignalModel::selectModelAndCompute()
{
    if(m_modelParameters.bBasic()) {
        computeInverseBasicModel();
    } else {
        computeInverseAdvancedModel();
    }
}

//=============================================================================================================

void SignalModel::computeInverseBasicModel()
{
    int iNumCoils = m_modelParameters.iNHpiCoils();
    MatrixXd matSimsig;
    VectorXd vecTime = VectorXd::LinSpaced(m_iCurrentModelCols, 0, m_iCurrentModelCols-1) *1.0/m_modelParameters.iSampleFreq();

    // Generate simulated data Matrix
    matSimsig.conservativeResize(m_iCurrentModelCols,iNumCoils*2);

    for(int i = 0; i < iNumCoils; ++i) {
        matSimsig.col(i) = sin(2*M_PI*m_modelParameters.vecHpiFreqs()[i]*vecTime.array());
        matSimsig.col(i+iNumCoils) = cos(2*M_PI*m_modelParameters.vecHpiFreqs()[i]*vecTime.array());
    }
    m_matInverseSignalModel = UTILSLIB::MNEMath::pinv(matSimsig);
}

//=============================================================================================================

void SignalModel::computeInverseAdvancedModel()
{
    int iNumCoils = m_modelParameters.iNHpiCoils();
    int iSampleFreq = m_modelParameters.iSampleFreq();
    MatrixXd matSimsig;
    MatrixXd matSimsigInvTemp;

    VectorXd vecTime = VectorXd::LinSpaced(m_iCurrentModelCols, 0, m_iCurrentModelCols-1) *1.0/iSampleFreq;

    // add linefreq + harmonics + DC part to model
    matSimsig.conservativeResize(m_iCurrentModelCols,iNumCoils*4+2);
    for(int i = 0; i < iNumCoils; ++i) {
        matSimsig.col(i) = sin(2*M_PI*m_modelParameters.vecHpiFreqs()[i]*vecTime.array());
        matSimsig.col(i+iNumCoils) = cos(2*M_PI*m_modelParameters.vecHpiFreqs()[i]*vecTime.array());
        matSimsig.col(i+2*iNumCoils) = sin(2*M_PI*m_modelParameters.iLineFreq()*(i+1)*vecTime.array());
        matSimsig.col(i+3*iNumCoils) = cos(2*M_PI*m_modelParameters.iLineFreq()*(i+1)*vecTime.array());
    }
    matSimsig.col(iNumCoils*4) = RowVectorXd::LinSpaced(m_iCurrentModelCols, -0.5, 0.5);
    matSimsig.col(iNumCoils*4+1).fill(1);
    matSimsigInvTemp = UTILSLIB::MNEMath::pinv(matSimsig);
    m_matInverseSignalModel = matSimsigInvTemp.block(0,0,iNumCoils*2,m_iCurrentModelCols);
}
<commit_msg>Maint: avoid copying of return values<commit_after>//=============================================================================================================
/**
 * @file     signalmodel.cpp
 * @author   Ruben Dörfel <doerfelruben@aol.com>
 * @since    0.1.9
 * @date     December, 2021
 *
 * @section  LICENSE
 *
 * Copyright (C) 2021, Ruben Dörfel. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that
 * the following conditions are met:
 *     * Redistributions of source code must retain the above copyright notice, this list of conditions and the
 *       following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
 *       the following disclaimer in the documentation and/or other materials provided with the distribution.
 *     * Neither the name of MNE-CPP authors nor the names of its contributors may be used
 *       to endorse or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 *
 * @brief    signalModel class definition.
 *
 */

//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "hpimodelparameters.h"
#include "signalmodel.h"
#include <utils/mnemath.h>
#include <iostream>

//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <qmath.h>

//=============================================================================================================
// EIGEN INCLUDES
//=============================================================================================================

#include <Eigen/Core>

//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace INVERSELIB;
using namespace Eigen;

//=============================================================================================================
// DEFINE GLOBAL METHODS
//=============================================================================================================

//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================

MatrixXd SignalModel::fitData(const HpiModelParameters& hpiModelParameters, const MatrixXd& matData)
{

    if(checkEmpty(hpiModelParameters)) {
        return MatrixXd();
    }

    bool bParametersChanged = m_modelParameters != hpiModelParameters;
    bool bDimensionsChanged = m_iCurrentModelCols != matData.cols();

    if(bDimensionsChanged || bParametersChanged) {
        m_iCurrentModelCols = matData.cols();
        m_modelParameters = hpiModelParameters;
        selectModelAndCompute();
    }

    return m_matInverseSignalModel * matData.transpose();
}

//=============================================================================================================

bool SignalModel::checkDataDimensions(const int iCols)
{
    bool bHasChanged = false;
    if(iCols != m_iCurrentModelCols) {
        m_iCurrentModelCols = iCols;
        bHasChanged = true;
    }
    return bHasChanged;
}

//=============================================================================================================

bool SignalModel::checkModelParameters(const HpiModelParameters& hpiModelParameters)
{
    bool bHasChanged = false;
    if((m_modelParameters.iSampleFreq() != hpiModelParameters.iSampleFreq()) ||
        (m_modelParameters.iLineFreq() != hpiModelParameters.iLineFreq()) ||
        (m_modelParameters.iNHpiCoils() != hpiModelParameters.iNHpiCoils()) ||
        (m_modelParameters.vecHpiFreqs() != hpiModelParameters.vecHpiFreqs()) ||
        (m_modelParameters.bBasic() != hpiModelParameters.bBasic())) {
        bHasChanged = true;
        m_modelParameters = hpiModelParameters;
    }
    return bHasChanged;
}

//=============================================================================================================

bool SignalModel::checkEmpty(const HpiModelParameters& hpiModelParameters)
{
    if(hpiModelParameters.vecHpiFreqs().empty()) {
        std::cout << "SignalModel::checkEmpty - no Hpi frequencies set" << std::endl;
        return true;
    } else if(hpiModelParameters.iSampleFreq() == 0) {
        std::cout << "SignalModel::checkEmpty - no sampling frequencies set" << std::endl;
        return true;
    }
    return false;
}

//=============================================================================================================

void SignalModel::selectModelAndCompute()
{
    if(m_modelParameters.bBasic()) {
        computeInverseBasicModel();
    } else {
        computeInverseAdvancedModel();
    }
}

//=============================================================================================================

void SignalModel::computeInverseBasicModel()
{
    int iNumCoils = m_modelParameters.iNHpiCoils();
    MatrixXd matSimsig;
    VectorXd vecTime = VectorXd::LinSpaced(m_iCurrentModelCols, 0, m_iCurrentModelCols-1) *1.0/m_modelParameters.iSampleFreq();

    // Generate simulated data Matrix
    matSimsig.conservativeResize(m_iCurrentModelCols,iNumCoils*2);

    for(int i = 0; i < iNumCoils; ++i) {
        matSimsig.col(i) = sin(2*M_PI*m_modelParameters.vecHpiFreqs()[i]*vecTime.array());
        matSimsig.col(i+iNumCoils) = cos(2*M_PI*m_modelParameters.vecHpiFreqs()[i]*vecTime.array());
    }
    m_matInverseSignalModel = UTILSLIB::MNEMath::pinv(matSimsig);
}

//=============================================================================================================

void SignalModel::computeInverseAdvancedModel()
{
    int iNumCoils = m_modelParameters.iNHpiCoils();
    int iSampleFreq = m_modelParameters.iSampleFreq();
    MatrixXd matSimsig;
    MatrixXd matSimsigInvTemp;

    VectorXd vecTime = VectorXd::LinSpaced(m_iCurrentModelCols, 0, m_iCurrentModelCols-1) *1.0/iSampleFreq;

    // add linefreq + harmonics + DC part to model
    matSimsig.conservativeResize(m_iCurrentModelCols,iNumCoils*4+2);
    for(int i = 0; i < iNumCoils; ++i) {
        matSimsig.col(i) = sin(2*M_PI*m_modelParameters.vecHpiFreqs()[i]*vecTime.array());
        matSimsig.col(i+iNumCoils) = cos(2*M_PI*m_modelParameters.vecHpiFreqs()[i]*vecTime.array());
        matSimsig.col(i+2*iNumCoils) = sin(2*M_PI*m_modelParameters.iLineFreq()*(i+1)*vecTime.array());
        matSimsig.col(i+3*iNumCoils) = cos(2*M_PI*m_modelParameters.iLineFreq()*(i+1)*vecTime.array());
    }
    matSimsig.col(iNumCoils*4) = RowVectorXd::LinSpaced(m_iCurrentModelCols, -0.5, 0.5);
    matSimsig.col(iNumCoils*4+1).fill(1);
    matSimsigInvTemp = UTILSLIB::MNEMath::pinv(matSimsig);
    m_matInverseSignalModel = matSimsigInvTemp.block(0,0,iNumCoils*2,m_iCurrentModelCols);
}
<|endoftext|>


<commit_before>/*
	Nazara Engine

	Copyright (C) 2015 Jérôme "Lynix" Leclercq (Lynix680@gmail.com)

	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.
*/

#ifndef NAZARA_PREREQUESITES_HPP
#define NAZARA_PREREQUESITES_HPP

// Identification du compilateur
///TODO: Rajouter des tests d'identification de compilateurs
#if defined(__BORLANDC__)
	#define NAZARA_COMPILER_BORDLAND
	#define NAZARA_COMPILER_SUPPORTS_CPP11 (defined(__cplusplus) && __cplusplus >= 201103L)
	#define NAZARA_DEPRECATED(txt)
	#define NAZARA_FUNCTION __FUNC__
#elif defined(__clang__)
	#define NAZARA_COMPILER_CLANG
	#define NAZARA_COMPILER_SUPPORTS_CPP11 (defined(__cplusplus) && __cplusplus >= 201103L)
	#define NAZARA_DEPRECATED(txt) __attribute__((__deprecated__(txt)))
	#define NAZARA_FUNCTION __PRETTY_FUNCTION__
#elif defined(__GNUC__) || defined(__MINGW32__)
	#define NAZARA_COMPILER_GCC
	#define NAZARA_COMPILER_SUPPORTS_CPP11 (defined(__cplusplus) && __cplusplus >= 201103L)
	#define NAZARA_DEPRECATED(txt) __attribute__((__deprecated__(txt)))
	#define NAZARA_FUNCTION __PRETTY_FUNCTION__

	#ifdef __MINGW32__
		#define NAZARA_COMPILER_MINGW
		#ifdef __MINGW64_VERSION_MAJOR
			#define NAZARA_COMPILER_MINGW_W64
		#endif
	#endif
#elif defined(__INTEL_COMPILER) || defined(__ICL)
	#define NAZARA_COMPILER_INTEL
	#define NAZARA_COMPILER_SUPPORTS_CPP11 (defined(__cplusplus) && __cplusplus >= 201103L)
	#define NAZARA_DEPRECATED(txt)
	#define NAZARA_FUNCTION __FUNCTION__
#elif defined(_MSC_VER)
	#define NAZARA_COMPILER_MSVC
	#define NAZARA_COMPILER_SUPPORTS_CPP11 (_MSC_VER >= 1900)
	#define NAZARA_DEPRECATED(txt) __declspec(deprecated(txt))
	#define NAZARA_FUNCTION __FUNCSIG__

	#pragma warning(disable: 4251)
#else
	#define NAZARA_COMPILER_UNKNOWN
	#define NAZARA_DEPRECATED(txt)
	#define NAZARA_FUNCTION __func__ // __func__ est standard depuis le C++11

	/// Cette ligne n'est là que pour prévenir, n'hésitez pas à la commenter si elle vous empêche de compiler
	#pragma message This compiler is not fully supported
#endif

#if !NAZARA_COMPILER_SUPPORTS_CPP11
	#error Nazara requires a C++11 compliant compiler
#endif

// Nazara version macro
#define NAZARA_VERSION_MAJOR 0
#define NAZARA_VERSION_MINOR 1

#include <Nazara/Core/Config.hpp>

// Identification de la plateforme
#if defined(_WIN32)
	#define NAZARA_PLATFORM_WINDOWS

	#define NAZARA_EXPORT __declspec(dllexport)
	#define NAZARA_IMPORT __declspec(dllimport)

	// Des defines pour le header Windows
	#if defined(NAZARA_BUILD) // Pour ne pas entrer en conflit avec les defines de l'application ou d'une autre bibliothèque
		#ifndef WIN32_LEAN_AND_MEAN
			#define WIN32_LEAN_AND_MEAN
		#endif

		#ifndef NOMINMAX
			#define NOMINMAX
		#endif

		#if NAZARA_CORE_WINDOWS_NT6
			// Version de Windows minimale : Vista
			#define NAZARA_WINNT 0x0600
		#else
			#define NAZARA_WINNT 0x0501
		#endif

		// Pour ne pas casser le define déjà en place s'il est applicable
		#if defined(_WIN32_WINNT)
			#if _WIN32_WINNT < NAZARA_WINNT
				#undef _WIN32_WINNT
				#define _WIN32_WINNT NAZARA_WINNT
			#endif
		#else
			#define _WIN32_WINNT NAZARA_WINNT
		#endif
	#endif
#elif defined(__linux__) || defined(__unix__)
	#define NAZARA_PLATFORM_LINUX
	#define NAZARA_PLATFORM_GLX
	#define NAZARA_PLATFORM_POSIX
	#define NAZARA_PLATFORM_X11

	#define NAZARA_EXPORT __attribute__((visibility ("default")))
	#define NAZARA_IMPORT __attribute__((visibility ("default")))
/*#elif defined(__APPLE__) && defined(__MACH__)
	#define NAZARA_CORE_API
	#define NAZARA_PLATFORM_MACOSX
	#define NAZARA_PLATFORM_POSIX*/
#else
	// À commenter pour tenter quand même une compilation
	#error This operating system is not fully supported by the Nazara Engine

	#define NAZARA_PLATFORM_UNKNOWN
	#define NAZARA_CORE_API
#endif

// Détection 64 bits
#if !defined(NAZARA_PLATFORM_x64) && (defined(_WIN64) ||  defined(__amd64__) || defined(__x86_64__) || defined(__ia64__) || defined(__ia64) || \
    defined(_M_IA64) || defined(__itanium__) || defined(__MINGW64__) || defined(_M_AMD64) || defined (_M_X64))
	#define NAZARA_PLATFORM_x64
#endif

// Définit NDEBUG si NAZARA_DEBUG n'est pas présent
#if !defined(NAZARA_DEBUG) && !defined(NDEBUG)
	#define NDEBUG
#endif

// Macros supplémentaires
#define NazaraPrefix(a, prefix) prefix ## a
#define NazaraPrefixMacro(a, prefix) NazaraPrefix(a, prefix)
#define NazaraSuffix(a, suffix) a ## suffix
#define NazaraSuffixMacro(a, suffix) NazaraSuffix(a, suffix)
#define NazaraStringify(s) #s
#define NazaraStringifyMacro(s) NazaraStringify(s) // http://gcc.gnu.org/onlinedocs/cpp/Stringification.html#Stringification
#define NazaraUnused(a) (void) a

#include <cstdint>

static_assert(sizeof(int8_t)  == 1, "int8_t is not of the correct size" );
static_assert(sizeof(int16_t) == 2, "int16_t is not of the correct size");
static_assert(sizeof(int32_t) == 4, "int32_t is not of the correct size");
static_assert(sizeof(int64_t) == 8, "int64_t is not of the correct size");

static_assert(sizeof(uint8_t)  == 1, "uint8_t is not of the correct size" );
static_assert(sizeof(uint16_t) == 2, "uint16_t is not of the correct size");
static_assert(sizeof(uint32_t) == 4, "uint32_t is not of the correct size");
static_assert(sizeof(uint64_t) == 8, "uint64_t is not of the correct size");

namespace Nz
{
    typedef int8_t Int8;
    typedef uint8_t UInt8;

    typedef int16_t Int16;
    typedef uint16_t UInt16;

    typedef int32_t Int32;
    typedef uint32_t UInt32;

    typedef int64_t Int64;
    typedef uint64_t UInt64;
}

#endif // NAZARA_PREREQUESITES_HPP
<commit_msg>Add patch version (currently 0)<commit_after>/*
	Nazara Engine

	Copyright (C) 2015 Jérôme "Lynix" Leclercq (Lynix680@gmail.com)

	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.
*/

#ifndef NAZARA_PREREQUESITES_HPP
#define NAZARA_PREREQUESITES_HPP

// Identification du compilateur
///TODO: Rajouter des tests d'identification de compilateurs
#if defined(__BORLANDC__)
	#define NAZARA_COMPILER_BORDLAND
	#define NAZARA_COMPILER_SUPPORTS_CPP11 (defined(__cplusplus) && __cplusplus >= 201103L)
	#define NAZARA_DEPRECATED(txt)
	#define NAZARA_FUNCTION __FUNC__
#elif defined(__clang__)
	#define NAZARA_COMPILER_CLANG
	#define NAZARA_COMPILER_SUPPORTS_CPP11 (defined(__cplusplus) && __cplusplus >= 201103L)
	#define NAZARA_DEPRECATED(txt) __attribute__((__deprecated__(txt)))
	#define NAZARA_FUNCTION __PRETTY_FUNCTION__
#elif defined(__GNUC__) || defined(__MINGW32__)
	#define NAZARA_COMPILER_GCC
	#define NAZARA_COMPILER_SUPPORTS_CPP11 (defined(__cplusplus) && __cplusplus >= 201103L)
	#define NAZARA_DEPRECATED(txt) __attribute__((__deprecated__(txt)))
	#define NAZARA_FUNCTION __PRETTY_FUNCTION__

	#ifdef __MINGW32__
		#define NAZARA_COMPILER_MINGW
		#ifdef __MINGW64_VERSION_MAJOR
			#define NAZARA_COMPILER_MINGW_W64
		#endif
	#endif
#elif defined(__INTEL_COMPILER) || defined(__ICL)
	#define NAZARA_COMPILER_INTEL
	#define NAZARA_COMPILER_SUPPORTS_CPP11 (defined(__cplusplus) && __cplusplus >= 201103L)
	#define NAZARA_DEPRECATED(txt)
	#define NAZARA_FUNCTION __FUNCTION__
#elif defined(_MSC_VER)
	#define NAZARA_COMPILER_MSVC
	#define NAZARA_COMPILER_SUPPORTS_CPP11 (_MSC_VER >= 1900)
	#define NAZARA_DEPRECATED(txt) __declspec(deprecated(txt))
	#define NAZARA_FUNCTION __FUNCSIG__

	#pragma warning(disable: 4251)
#else
	#define NAZARA_COMPILER_UNKNOWN
	#define NAZARA_DEPRECATED(txt)
	#define NAZARA_FUNCTION __func__ // __func__ est standard depuis le C++11

	/// Cette ligne n'est là que pour prévenir, n'hésitez pas à la commenter si elle vous empêche de compiler
	#pragma message This compiler is not fully supported
#endif

#if !NAZARA_COMPILER_SUPPORTS_CPP11
	#error Nazara requires a C++11 compliant compiler
#endif

// Nazara version macro
#define NAZARA_VERSION_MAJOR 0
#define NAZARA_VERSION_MINOR 1
#define NAZARA_VERSION_PATCH 0

#include <Nazara/Core/Config.hpp>

// Identification de la plateforme
#if defined(_WIN32)
	#define NAZARA_PLATFORM_WINDOWS

	#define NAZARA_EXPORT __declspec(dllexport)
	#define NAZARA_IMPORT __declspec(dllimport)

	// Des defines pour le header Windows
	#if defined(NAZARA_BUILD) // Pour ne pas entrer en conflit avec les defines de l'application ou d'une autre bibliothèque
		#ifndef WIN32_LEAN_AND_MEAN
			#define WIN32_LEAN_AND_MEAN
		#endif

		#ifndef NOMINMAX
			#define NOMINMAX
		#endif

		#if NAZARA_CORE_WINDOWS_NT6
			// Version de Windows minimale : Vista
			#define NAZARA_WINNT 0x0600
		#else
			#define NAZARA_WINNT 0x0501
		#endif

		// Pour ne pas casser le define déjà en place s'il est applicable
		#if defined(_WIN32_WINNT)
			#if _WIN32_WINNT < NAZARA_WINNT
				#undef _WIN32_WINNT
				#define _WIN32_WINNT NAZARA_WINNT
			#endif
		#else
			#define _WIN32_WINNT NAZARA_WINNT
		#endif
	#endif
#elif defined(__linux__) || defined(__unix__)
	#define NAZARA_PLATFORM_LINUX
	#define NAZARA_PLATFORM_GLX
	#define NAZARA_PLATFORM_POSIX
	#define NAZARA_PLATFORM_X11

	#define NAZARA_EXPORT __attribute__((visibility ("default")))
	#define NAZARA_IMPORT __attribute__((visibility ("default")))
/*#elif defined(__APPLE__) && defined(__MACH__)
	#define NAZARA_CORE_API
	#define NAZARA_PLATFORM_MACOSX
	#define NAZARA_PLATFORM_POSIX*/
#else
	// À commenter pour tenter quand même une compilation
	#error This operating system is not fully supported by the Nazara Engine

	#define NAZARA_PLATFORM_UNKNOWN
	#define NAZARA_CORE_API
#endif

// Détection 64 bits
#if !defined(NAZARA_PLATFORM_x64) && (defined(_WIN64) ||  defined(__amd64__) || defined(__x86_64__) || defined(__ia64__) || defined(__ia64) || \
    defined(_M_IA64) || defined(__itanium__) || defined(__MINGW64__) || defined(_M_AMD64) || defined (_M_X64))
	#define NAZARA_PLATFORM_x64
#endif

// Définit NDEBUG si NAZARA_DEBUG n'est pas présent
#if !defined(NAZARA_DEBUG) && !defined(NDEBUG)
	#define NDEBUG
#endif

// Macros supplémentaires
#define NazaraPrefix(a, prefix) prefix ## a
#define NazaraPrefixMacro(a, prefix) NazaraPrefix(a, prefix)
#define NazaraSuffix(a, suffix) a ## suffix
#define NazaraSuffixMacro(a, suffix) NazaraSuffix(a, suffix)
#define NazaraStringify(s) #s
#define NazaraStringifyMacro(s) NazaraStringify(s) // http://gcc.gnu.org/onlinedocs/cpp/Stringification.html#Stringification
#define NazaraUnused(a) (void) a

#include <cstdint>

static_assert(sizeof(int8_t)  == 1, "int8_t is not of the correct size" );
static_assert(sizeof(int16_t) == 2, "int16_t is not of the correct size");
static_assert(sizeof(int32_t) == 4, "int32_t is not of the correct size");
static_assert(sizeof(int64_t) == 8, "int64_t is not of the correct size");

static_assert(sizeof(uint8_t)  == 1, "uint8_t is not of the correct size" );
static_assert(sizeof(uint16_t) == 2, "uint16_t is not of the correct size");
static_assert(sizeof(uint32_t) == 4, "uint32_t is not of the correct size");
static_assert(sizeof(uint64_t) == 8, "uint64_t is not of the correct size");

namespace Nz
{
    typedef int8_t Int8;
    typedef uint8_t UInt8;

    typedef int16_t Int16;
    typedef uint16_t UInt16;

    typedef int32_t Int32;
    typedef uint32_t UInt32;

    typedef int64_t Int64;
    typedef uint64_t UInt64;
}

#endif // NAZARA_PREREQUESITES_HPP
<|endoftext|>


<commit_before>// ======================================================================== //
// Copyright 2009-2015 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#include "bvh4_builder_toplevel_new.h"

namespace embree
{
  namespace isa
  {
#define MIN_OPEN_SIZE 2000

    BVH4BuilderTopLevelNew::BVH4BuilderTopLevelNew (BVH4* bvh, Scene* scene, const createTriangleMeshAccelTy createTriangleMeshAccel)
      : bvh(bvh), objects(bvh->objects), scene(scene), createTriangleMeshAccel(createTriangleMeshAccel) {}

    BVH4BuilderTopLevelNew::~BVH4BuilderTopLevelNew ()
    {
      for (size_t i=0; i<builders.size(); i++)
	delete builders[i];
    }

    void BVH4BuilderTopLevelNew::build(size_t threadIndex, size_t threadCount)
    {
      double t0 = 0.0, dt = 0.0;
      if (g_verbose >= 1) {
	std::cout << "building BVH4<" << bvh->primTy.name << "> with " << TOSTRING(isa) << "::TwoLevel SAH builder ... " << std::flush;
        t0 = getSeconds();
      }

      /* delete some objects */
      size_t N = scene->size();
      const size_t numPrimitives = scene->getNumPrimitives<TriangleMesh,1>();
      parallel_for(N, objects.size(), [&] (const range<size_t>& r) {
        for (size_t i=r.begin(); i<r.end(); i++) {
          delete builders[i]; builders[i] = NULL;
          delete objects[i]; objects[i] = NULL;
        }
      });

      /* resize object array if scene got larger */
      if (objects.size() < N) {
        objects.resize(N);
        builders.resize(N);
        refs.resize(N);
      }
      nextRef = 0;

      /* create of acceleration structures */
      parallel_for(size_t(0), N, [&] (const range<size_t>& r)
      {
        for (size_t objectID=r.begin(); objectID<r.end(); objectID++)
        {
          TriangleMesh* mesh = scene->getTriangleMeshSafe(objectID);

          /* verify meshes got deleted properly */
          if (mesh == NULL || mesh->numTimeSteps != 1) {
            assert(objectID < objects.size () && objects[objectID] == NULL);
            assert(objectID < builders.size() && builders[objectID] == NULL);
            continue;
          }

          /* delete BVH and builder for meshes that are scheduled for deletion */
          if (mesh->state == Geometry::ERASING) {
            delete builders[objectID]; builders[objectID] = NULL;
            delete objects [objectID]; objects [objectID] = NULL;
            continue;
          }

          /* create BVH and builder for new meshes */
          if (objects[objectID] == NULL)
            createTriangleMeshAccel(mesh,objects[objectID],builders[objectID]);
        }
      });

      /* parallel build of acceleration structures */
      parallel_for(size_t(0), N, [&] (const range<size_t>& r)
      {
        for (size_t objectID=r.begin(); objectID<r.end(); objectID++)
        {
          /* ignore if no triangle mesh or not enabled */
          TriangleMesh* mesh = scene->getTriangleMeshSafe(objectID);
          if (mesh == NULL || !mesh->isEnabled() || mesh->numTimeSteps != 1)
            continue;

          BVH4*    object  = objects [objectID]; assert(object);
          Builder* builder = builders[objectID]; assert(builder);

          /* build object if it got modified */
          if (mesh->isModified()) {
            builder->build(0,0);
            mesh->state = Geometry::ENABLED;
          }

          /* create build primitive */
          if (!object->bounds.empty())
            refs[nextRef++] = BuildRef(object->bounds,object->root);
        }
      });

      refs.resize(nextRef);

      /* open all large nodes */
      open_sequential();
      prims.resize(refs.size());

      /* compute PrimRefs */
      const PrimInfo pinfo = parallel_reduce(size_t(0), refs.size(), size_t(1024), PrimInfo(empty), [&] (const range<size_t>& r)
      {
        PrimInfo pinfo(empty);
        for (size_t i=r.begin(); i<r.end(); i++) {
          pinfo.add(refs[i].bounds());
          prims[i] = PrimRef(refs[i].bounds(),(size_t)refs[i].node);
        }
        return pinfo;
      }, [] (const PrimInfo& a, const PrimInfo& b) { return PrimInfo::merge(a,b); });

      /* build hierarchy */
      BVH4::NodeRef root = bvh_builder_binned_sah_internal<BVH4::NodeRef>
        ([&] { return bvh->alloc2.threadLocal2(); },
         [&] (const isa::BuildRecord<BVH4::NodeRef>& current, BuildRecord<BVH4::NodeRef>** children, const size_t N, FastAllocator::ThreadLocal2* alloc)
         {
           BVH4::Node* node = (BVH4::Node*) alloc->alloc0.malloc(sizeof(BVH4::Node)); node->clear();
           for (size_t i=0; i<N; i++) {
             node->set(i,children[i]->geomBounds);
             children[i]->parent = &node->child(i);
           }
           *current.parent = bvh->encodeNode(node);
           return 0;
         },
         [&] (const BuildRecord<BVH4::NodeRef>& current, PrimRef* prims, FastAllocator::ThreadLocal2* alloc) // FIXME: why are prims passed here but not for createNode
         {
           assert(current.prims.size() == 1);
           *current.parent = (BVH4::NodeRef) prims[current.prims.begin()].ID();
           return 1;
         },
         prims.data(),pinfo,BVH4::N,BVH4::maxBuildDepthLeaf,1,1,1);

      bvh->set(root,pinfo.geomBounds,numPrimitives);

      if (g_verbose >= 1) {
        dt = getSeconds()-t0;
        std::cout << "[DONE] " << 1000.0f*dt << "ms (" << numPrimitives/dt*1E-6 << " Mprim/s)" << std::endl;
      }
      if (g_verbose >= 2)
        bvh->printStatistics();
    }

    void BVH4BuilderTopLevelNew::open_sequential()
    {
      if (refs.size() == 0)
	return;

      size_t N = max(2*refs.size(),size_t(MIN_OPEN_SIZE));
      refs.reserve(N);

      std::make_heap(refs.begin(),refs.end());
      while (refs.size()+3 <= N)
      {
        std::pop_heap (refs.begin(),refs.end());
        BVH4::NodeRef ref = refs.back().node;
        if (ref.isLeaf()) break;
        refs.pop_back();

        BVH4::Node* node = ref.node();
        for (size_t i=0; i<4; i++) {
          if (node->child(i) == BVH4::emptyNode) continue;
          refs.push_back(BuildRef(node->bounds(i),node->child(i)));
          std::push_heap (refs.begin(),refs.end());
        }
      }
    }

    Builder* BVH4BuilderTopLevelBinnedSAH (BVH4* bvh, Scene* scene, const createTriangleMeshAccelTy createTriangleMeshAccel) {
      return new BVH4BuilderTopLevelNew(bvh,scene,createTriangleMeshAccel);
    }
  }
}
<commit_msg>bugfix in new twolevel builder<commit_after>// ======================================================================== //
// Copyright 2009-2015 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#include "bvh4_builder_toplevel_new.h"

namespace embree
{
  namespace isa
  {
#define MIN_OPEN_SIZE 2000

    BVH4BuilderTopLevelNew::BVH4BuilderTopLevelNew (BVH4* bvh, Scene* scene, const createTriangleMeshAccelTy createTriangleMeshAccel)
      : bvh(bvh), objects(bvh->objects), scene(scene), createTriangleMeshAccel(createTriangleMeshAccel) {}

    BVH4BuilderTopLevelNew::~BVH4BuilderTopLevelNew ()
    {
      for (size_t i=0; i<builders.size(); i++)
	delete builders[i];
    }

    void BVH4BuilderTopLevelNew::build(size_t threadIndex, size_t threadCount)
    {
      /* delete some objects */
      size_t N = scene->size();
      parallel_for(N, objects.size(), [&] (const range<size_t>& r) {
        for (size_t i=r.begin(); i<r.end(); i++) {
          delete builders[i]; builders[i] = NULL;
          delete objects[i]; objects[i] = NULL;
        }
      });

      /* skip build for empty scene */
      const size_t numPrimitives = scene->getNumPrimitives<TriangleMesh,1>();
      if (numPrimitives == 0) {
        prims.resize(0);
        bvh->set(BVH4::emptyNode,empty,0);
        return;
      }

      double t0 = 0.0, dt = 0.0;
      if (g_verbose >= 1) {
	std::cout << "building BVH4<" << bvh->primTy.name << "> with " << TOSTRING(isa) << "::TwoLevel SAH builder ... " << std::flush;
        t0 = getSeconds();
      }

      /* resize object array if scene got larger */
      if (objects.size() < N) {
        objects.resize(N);
        builders.resize(N);
        refs.resize(N);
      }
      nextRef = 0;

      /* create of acceleration structures */
      parallel_for(size_t(0), N, [&] (const range<size_t>& r)
      {
        for (size_t objectID=r.begin(); objectID<r.end(); objectID++)
        {
          TriangleMesh* mesh = scene->getTriangleMeshSafe(objectID);

          /* verify meshes got deleted properly */
          if (mesh == NULL || mesh->numTimeSteps != 1) {
            assert(objectID < objects.size () && objects[objectID] == NULL);
            assert(objectID < builders.size() && builders[objectID] == NULL);
            continue;
          }

          /* delete BVH and builder for meshes that are scheduled for deletion */
          if (mesh->state == Geometry::ERASING) {
            delete builders[objectID]; builders[objectID] = NULL;
            delete objects [objectID]; objects [objectID] = NULL;
            continue;
          }

          /* create BVH and builder for new meshes */
          if (objects[objectID] == NULL)
            createTriangleMeshAccel(mesh,objects[objectID],builders[objectID]);
        }
      });

      /* parallel build of acceleration structures */
      parallel_for(size_t(0), N, [&] (const range<size_t>& r)
      {
        for (size_t objectID=r.begin(); objectID<r.end(); objectID++)
        {
          /* ignore if no triangle mesh or not enabled */
          TriangleMesh* mesh = scene->getTriangleMeshSafe(objectID);
          if (mesh == NULL || !mesh->isEnabled() || mesh->numTimeSteps != 1)
            continue;

          BVH4*    object  = objects [objectID]; assert(object);
          Builder* builder = builders[objectID]; assert(builder);

          /* build object if it got modified */
          if (mesh->isModified()) {
            builder->build(0,0);
            mesh->state = Geometry::ENABLED;
          }

          /* create build primitive */
          if (!object->bounds.empty())
            refs[nextRef++] = BuildRef(object->bounds,object->root);
        }
      });

      refs.resize(nextRef);

      /* open all large nodes */
      open_sequential();
      prims.resize(refs.size());

      /* compute PrimRefs */
      const PrimInfo pinfo = parallel_reduce(size_t(0), refs.size(), size_t(1024), PrimInfo(empty), [&] (const range<size_t>& r)
      {
        PrimInfo pinfo(empty);
        for (size_t i=r.begin(); i<r.end(); i++) {
          pinfo.add(refs[i].bounds());
          prims[i] = PrimRef(refs[i].bounds(),(size_t)refs[i].node);
        }
        return pinfo;
      }, [] (const PrimInfo& a, const PrimInfo& b) { return PrimInfo::merge(a,b); });

      /* build hierarchy */
      BVH4::NodeRef root = bvh_builder_binned_sah_internal<BVH4::NodeRef>
        ([&] { return bvh->alloc2.threadLocal2(); },
         [&] (const isa::BuildRecord<BVH4::NodeRef>& current, BuildRecord<BVH4::NodeRef>** children, const size_t N, FastAllocator::ThreadLocal2* alloc)
         {
           BVH4::Node* node = (BVH4::Node*) alloc->alloc0.malloc(sizeof(BVH4::Node)); node->clear();
           for (size_t i=0; i<N; i++) {
             node->set(i,children[i]->geomBounds);
             children[i]->parent = &node->child(i);
           }
           *current.parent = bvh->encodeNode(node);
           return 0;
         },
         [&] (const BuildRecord<BVH4::NodeRef>& current, PrimRef* prims, FastAllocator::ThreadLocal2* alloc) // FIXME: why are prims passed here but not for createNode
         {
           assert(current.prims.size() == 1);
           *current.parent = (BVH4::NodeRef) prims[current.prims.begin()].ID();
           return 1;
         },
         prims.data(),pinfo,BVH4::N,BVH4::maxBuildDepthLeaf,1,1,1);

      bvh->set(root,pinfo.geomBounds,numPrimitives);

      if (g_verbose >= 1) {
        dt = getSeconds()-t0;
        std::cout << "[DONE] " << 1000.0f*dt << "ms (" << numPrimitives/dt*1E-6 << " Mprim/s)" << std::endl;
      }
      if (g_verbose >= 2)
        bvh->printStatistics();
    }

    void BVH4BuilderTopLevelNew::open_sequential()
    {
      if (refs.size() == 0)
	return;

      size_t N = max(2*refs.size(),size_t(MIN_OPEN_SIZE));
      refs.reserve(N);

      std::make_heap(refs.begin(),refs.end());
      while (refs.size()+3 <= N)
      {
        std::pop_heap (refs.begin(),refs.end());
        BVH4::NodeRef ref = refs.back().node;
        if (ref.isLeaf()) break;
        refs.pop_back();

        BVH4::Node* node = ref.node();
        for (size_t i=0; i<4; i++) {
          if (node->child(i) == BVH4::emptyNode) continue;
          refs.push_back(BuildRef(node->bounds(i),node->child(i)));
          std::push_heap (refs.begin(),refs.end());
        }
      }
    }

    Builder* BVH4BuilderTopLevelBinnedSAH (BVH4* bvh, Scene* scene, const createTriangleMeshAccelTy createTriangleMeshAccel) {
      return new BVH4BuilderTopLevelNew(bvh,scene,createTriangleMeshAccel);
    }
  }
}
<|endoftext|>


<commit_before>/*
 *  AlloSphere Research Group / Media Arts & Technology, UCSB, 2009
 */

/*
	Copyright (C) 2006-2008. The Regents of the University of California (REGENTS).
	All Rights Reserved.

	Permission to use, copy, modify, distribute, and distribute modified versions
	of this software and its documentation without fee and without a signed
	licensing agreement, is hereby granted, provided that the above copyright
	notice, the list of contributors, this paragraph and the following two paragraphs
	appear in all copies, modifications, and distributions.

	IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
	SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING
	OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS
	BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

	REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
	THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
	PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
	HEREUNDER IS PROVIDED "AS IS". REGENTS HAS  NO OBLIGATION TO PROVIDE
	MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/

/*! \mainpage AlloCore

	\section intro_sec About

	The AlloCore is a cross-platform suite of C++ components for building
	interactive multimedia tools and applications.
*/

#include "allocore/graphics/al_Graphics.hpp"
#include "allocore/graphics/al_GraphicsOpenGL.hpp"
#include "allocore/graphics/al_Image.hpp"
//#include "allocore/graphics/al_Isosurface.hpp"
#include "allocore/graphics/al_Light.hpp"
#include "allocore/graphics/al_Model.hpp"
#include "allocore/graphics/al_Shapes.hpp"
#include "allocore/graphics/al_Stereographic.hpp"
#include "allocore/io/al_AudioIO.hpp"
#include "allocore/io/al_File.hpp"
#include "allocore/io/al_Socket.hpp"
#include "allocore/io/al_Window.hpp"
#include "allocore/math/al_Complex.hpp"
#include "allocore/math/al_Constants.hpp"
#include "allocore/math/al_Frustum.hpp"
#include "allocore/math/al_Functions.hpp"
#include "allocore/math/al_Generators.hpp"
#include "allocore/math/al_Interpolation.hpp"
#include "allocore/math/al_Interval.hpp"
#include "allocore/math/al_Plane.hpp"
#include "allocore/math/al_Quat.hpp"
#include "allocore/math/al_Random.hpp"
#include "allocore/math/al_Vec.hpp"
#include "allocore/protocol/al_OSC.hpp"
#include "allocore/protocol/al_Serialize.hpp"
#include "allocore/sound/al_Reverb.hpp"
#include "allocore/sound/al_AudioScene.hpp"
#include "allocore/spatial/al_Camera.hpp"
#include "allocore/spatial/al_CoordinateFrame.hpp"
#include "allocore/system/al_Info.hpp"
#include "allocore/system/al_MainLoop.hpp"
#include "allocore/system/al_Printing.hpp"
#include "allocore/system/al_Thread.hpp"
#include "allocore/system/al_Time.hpp"
#include "allocore/types/al_Buffer.hpp"
#include "allocore/types/al_Conversion.hpp"
#include "allocore/types/al_Array.hpp"
<commit_msg>rm Model from al_Allocore.hpp<commit_after>/*
 *  AlloSphere Research Group / Media Arts & Technology, UCSB, 2009
 */

/*
	Copyright (C) 2006-2008. The Regents of the University of California (REGENTS).
	All Rights Reserved.

	Permission to use, copy, modify, distribute, and distribute modified versions
	of this software and its documentation without fee and without a signed
	licensing agreement, is hereby granted, provided that the above copyright
	notice, the list of contributors, this paragraph and the following two paragraphs
	appear in all copies, modifications, and distributions.

	IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
	SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING
	OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS
	BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

	REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
	THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
	PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
	HEREUNDER IS PROVIDED "AS IS". REGENTS HAS  NO OBLIGATION TO PROVIDE
	MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/

/*! \mainpage AlloCore

	\section intro_sec About

	The AlloCore is a cross-platform suite of C++ components for building
	interactive multimedia tools and applications.
*/

#include "allocore/graphics/al_Graphics.hpp"
#include "allocore/graphics/al_GraphicsOpenGL.hpp"
#include "allocore/graphics/al_Image.hpp"
//#include "allocore/graphics/al_Isosurface.hpp"
#include "allocore/graphics/al_Light.hpp"
#include "allocore/graphics/al_Shapes.hpp"
#include "allocore/graphics/al_Stereographic.hpp"
#include "allocore/io/al_AudioIO.hpp"
#include "allocore/io/al_File.hpp"
#include "allocore/io/al_Socket.hpp"
#include "allocore/io/al_Window.hpp"
#include "allocore/math/al_Complex.hpp"
#include "allocore/math/al_Constants.hpp"
#include "allocore/math/al_Frustum.hpp"
#include "allocore/math/al_Functions.hpp"
#include "allocore/math/al_Generators.hpp"
#include "allocore/math/al_Interpolation.hpp"
#include "allocore/math/al_Interval.hpp"
#include "allocore/math/al_Plane.hpp"
#include "allocore/math/al_Quat.hpp"
#include "allocore/math/al_Random.hpp"
#include "allocore/math/al_Vec.hpp"
#include "allocore/protocol/al_OSC.hpp"
#include "allocore/protocol/al_Serialize.hpp"
#include "allocore/sound/al_Reverb.hpp"
#include "allocore/sound/al_AudioScene.hpp"
#include "allocore/spatial/al_Camera.hpp"
#include "allocore/spatial/al_CoordinateFrame.hpp"
#include "allocore/system/al_Info.hpp"
#include "allocore/system/al_MainLoop.hpp"
#include "allocore/system/al_Printing.hpp"
#include "allocore/system/al_Thread.hpp"
#include "allocore/system/al_Time.hpp"
#include "allocore/types/al_Buffer.hpp"
#include "allocore/types/al_Conversion.hpp"
#include "allocore/types/al_Array.hpp"
<|endoftext|>


<commit_before>/*
* SMARTCARDPP
*
* This software is released under either the GNU Library General Public
* License (see LICENSE.LGPL) or the BSD License (see LICENSE.BSD).
*
* Note that the only valid version of the LGPL license as far as this
* project is concerned is the original GNU Library General Public License
* Version 2.1, February 1999
*
*/

#include "common.h"
#include "SCError.h"

SCError::SCError(long err) : runtime_error("smart card API error"),error(err)
{
	std::ostringstream buf;
	switch(err & 0xFFFFFFFF)
	{
		case 0x80100017 : //SCARD_E_READER_UNAVAILABLE
			buf << "No smart card readers"; break;
		case 0x80100069 : //SCARD_W_REMOVED_CARD
			buf << "No card in specified reader"; break;
		case 0x80100011 : //SCARD_E_INVALID_VALUE .. needs trapping
			buf << "Another application is using the card"; break;
		case 0x8010000b : //SCARD_E_SHARING_VIOLATION
			buf << "The smart card cannot be accessed because of other connections outstanding"; break;
		case 0x8010000f : //SCARD_E_PROTO_MISMATCH
			buf << "The requested protocols are incompatible with the protocol currently in use with the smart card"; break;
		case 0x8010001D : // SCARD_E_NO_SERVICE
			buf << "Smart card manager (PC/SC service) is not running"; break;
		case 0x80100066 : // SCARD_W_UNRESPONSIVE_CARD
			buf << "The card is not responding to reset"; break;
		default:
			buf << "exception:'" << runtime_error::what() <<
				"' code:'0x" <<std::hex << std::setfill('0') <<
				std::setw(8) << error << "'";
	}
	desc = buf.str();
}

void SCError::check(long err, int cid, int tid)
{
	if(err)
		SCardLog::writeMessage("[%i:%i][%s:%d] ERROR CODE RECIEVED 0x%08X", cid, tid, __FUNC__, __LINE__, err);

    if((uint32_t)err == (uint32_t)SCARD_W_RESET_CARD)
    {
        SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_W_RESET_CARD", cid, tid, __FUNC__, __LINE__, err);
        throw CardResetError();
    }
    else if((uint32_t)err == (uint32_t)SCARD_W_UNPOWERED_CARD)
    {
        SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_W_UNPOWERED_CARD", cid, tid, __FUNC__, __LINE__, err);
        throw CardResetError();
    }
    else if((uint32_t)err == (uint32_t)SCARD_E_NOT_TRANSACTED)
    {
        SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_E_NOT_TRANSACTED", cid, tid, __FUNC__, __LINE__, err);
        throw CardResetError();
    }
    else if((uint32_t)err == (uint32_t)SCARD_E_NO_SMARTCARD)
    {
        SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_E_NO_SMARTCARD", cid, tid, __FUNC__, __LINE__, err);
        throw NoCardInReaderError();
    }
    else if((uint32_t)err == (uint32_t)SCARD_W_REMOVED_CARD)
    {
        SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_W_REMOVED_CARD", cid, tid, __FUNC__, __LINE__, err);
        throw NoCardInReaderError();
    }
    else if((uint32_t)err == (uint32_t)SCARD_W_UNRESPONSIVE_CARD)
    {
        SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_W_UNRESPONSIVE_CARD", cid, tid, __FUNC__, __LINE__, err);
        throw CardResetError();
    }
    else if((uint32_t)err == (uint32_t)SCARD_E_NO_READERS_AVAILABLE)
    {
        SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_E_NO_READERS_AVAILABLE", cid, tid, __FUNC__, __LINE__, err);
        throw NoReadersAvailible();
    }
    else if((uint32_t)err == (uint32_t)ERROR_NO_MEDIA_IN_DRIVE)
    {
        SCardLog::writeMessage("[%i:%i][%s:%d] ERROR_NO_MEDIA_IN_DRIVE", cid, tid, __FUNC__, __LINE__, err);
        throw NoCardInReaderError();
    }
    else if((uint32_t)err == (uint32_t)SCARD_E_READER_UNAVAILABLE)
    {
        SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_E_READER_UNAVAILABLE", cid, tid, __FUNC__, __LINE__, err);
        throw CardResetError();
    }
    else if((uint32_t)err == (uint32_t)SCARD_E_SHARING_VIOLATION)
    {
        SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_E_SHARING_VIOLATION", cid, tid, __FUNC__, __LINE__, err);
        throw CardResetError();
    }
    else if((uint32_t)err == (uint32_t)SCARD_E_TIMEOUT)
    {
        SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_E_TIMEOUT", cid, tid, __FUNC__, __LINE__, err);
        return;
    }

	if (err)
	{
		throw SCError(err);
	}
}
<commit_msg>Refactoring<commit_after>/*
* SMARTCARDPP
*
* This software is released under either the GNU Library General Public
* License (see LICENSE.LGPL) or the BSD License (see LICENSE.BSD).
*
* Note that the only valid version of the LGPL license as far as this
* project is concerned is the original GNU Library General Public License
* Version 2.1, February 1999
*
*/

#include "common.h"
#include "SCError.h"

SCError::SCError(long err) : runtime_error("smart card API error"),error(err)
{
	std::ostringstream buf;
	switch(err & 0xFFFFFFFF)
	{
		case 0x80100017 : //SCARD_E_READER_UNAVAILABLE
			buf << "No smart card readers"; break;
		case 0x80100069 : //SCARD_W_REMOVED_CARD
			buf << "No card in specified reader"; break;
		case 0x80100011 : //SCARD_E_INVALID_VALUE .. needs trapping
			buf << "Another application is using the card"; break;
		case 0x8010000b : //SCARD_E_SHARING_VIOLATION
			buf << "The smart card cannot be accessed because of other connections outstanding"; break;
		case 0x8010000f : //SCARD_E_PROTO_MISMATCH
			buf << "The requested protocols are incompatible with the protocol currently in use with the smart card"; break;
		case 0x8010001D : // SCARD_E_NO_SERVICE
			buf << "Smart card manager (PC/SC service) is not running"; break;
		case 0x80100066 : // SCARD_W_UNRESPONSIVE_CARD
			buf << "The card is not responding to reset"; break;
		default:
			buf << "exception:'" << runtime_error::what() <<
				"' code:'0x" <<std::hex << std::setfill('0') <<
				std::setw(8) << error << "'";
	}
	desc = buf.str();
}

void SCError::check(long err, int cid, int tid)
{
	if(err)
		SCardLog::writeMessage("[%i:%i][%s:%d] ERROR CODE RECIEVED 0x%08X", cid, tid, __FUNC__, __LINE__, err);

    switch((uint32_t)err) {

        case (uint32_t)SCARD_W_RESET_CARD :
            SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_W_RESET_CARD", cid, tid, __FUNC__, __LINE__, err);
            throw CardResetError();

        case (uint32_t)SCARD_W_UNPOWERED_CARD :
            SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_W_UNPOWERED_CARD", cid, tid, __FUNC__, __LINE__, err);
            throw CardResetError();

        case (uint32_t)SCARD_E_NOT_TRANSACTED :
            SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_E_NOT_TRANSACTED", cid, tid, __FUNC__, __LINE__, err);
            throw CardResetError();

        case (uint32_t)SCARD_E_NO_SMARTCARD :
            SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_E_NO_SMARTCARD", cid, tid, __FUNC__, __LINE__, err);
            throw NoCardInReaderError();

        case (uint32_t)SCARD_W_REMOVED_CARD :
            SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_W_REMOVED_CARD", cid, tid, __FUNC__, __LINE__, err);
            throw NoCardInReaderError();

        case (uint32_t)SCARD_W_UNRESPONSIVE_CARD :
            SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_W_UNRESPONSIVE_CARD", cid, tid, __FUNC__, __LINE__, err);
            throw CardResetError();

        case (uint32_t)SCARD_E_NO_READERS_AVAILABLE :
            SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_E_NO_READERS_AVAILABLE", cid, tid, __FUNC__, __LINE__, err);
            throw NoReadersAvailible();

        case (uint32_t)ERROR_NO_MEDIA_IN_DRIVE :
            SCardLog::writeMessage("[%i:%i][%s:%d] ERROR_NO_MEDIA_IN_DRIVE", cid, tid, __FUNC__, __LINE__, err);
            throw NoCardInReaderError();

        case (uint32_t)SCARD_E_READER_UNAVAILABLE :
            SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_E_READER_UNAVAILABLE", cid, tid, __FUNC__, __LINE__, err);
            throw CardResetError();

        case (uint32_t)SCARD_E_SHARING_VIOLATION :
            SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_E_SHARING_VIOLATION", cid, tid, __FUNC__, __LINE__, err);
            throw CardResetError();

        case (uint32_t)SCARD_E_TIMEOUT :
            SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_E_TIMEOUT", cid, tid, __FUNC__, __LINE__, err);
            return;

        default :
            if (err)
                throw SCError(err);
     }
}
<|endoftext|>


<commit_before>/* Copyright 2019 Benjamin Worpitz, René Widera
 *
 * This file is part of alpaka.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#pragma once

#include <alpaka/core/Positioning.hpp>
#include <alpaka/core/Common.hpp>
#include <alpaka/core/Concepts.hpp>

#include <type_traits>

namespace alpaka
{
    struct ConceptAtomicGrids{};
    struct ConceptAtomicBlocks{};
    struct ConceptAtomicThreads{};

    namespace detail
    {
        template<
            typename THierarchy
        >
        struct AtomicHierarchyConceptType;

        template<>
        struct AtomicHierarchyConceptType<
            hierarchy::Threads>
        {
            using type = ConceptAtomicThreads;
        };

        template<>
        struct AtomicHierarchyConceptType<
            hierarchy::Blocks>
        {
            using type = ConceptAtomicBlocks;
        };

        template<>
        struct AtomicHierarchyConceptType<
            hierarchy::Grids>
        {
            using type = ConceptAtomicGrids;
        };
    }

    template<
        typename THierarchy
    >
    using AtomicHierarchyConcept = typename detail::AtomicHierarchyConceptType<THierarchy>::type;

    //-----------------------------------------------------------------------------
    //! The atomic operation traits.
    namespace traits
    {
        //#############################################################################
        //! The atomic operation trait.
        template<
            typename TOp,
            typename TAtomic,
            typename T,
            typename THierarchy,
            typename TSfinae = void>
        struct AtomicOp;
    }

    //-----------------------------------------------------------------------------
    //! Executes the given operation atomically.
    //!
    //! \tparam TOp The operation type.
    //! \tparam T The value type.
    //! \tparam TAtomic The atomic implementation type.
    //! \param addr The value to change atomically.
    //! \param value The value used in the atomic operation.
    //! \param atomic The atomic implementation.
    ALPAKA_NO_HOST_ACC_WARNING
    template<
        typename TOp,
        typename TAtomic,
        typename T,
        typename THierarchy = hierarchy::Grids>
    ALPAKA_FN_HOST_ACC auto atomicOp(
        TAtomic const & atomic,
        T * const addr,
        T const & value,
        THierarchy const & = THierarchy())
    -> T
    {
        using ImplementationBase = typename concepts::ImplementationBase<AtomicHierarchyConcept<THierarchy>, TAtomic>;
        return
            traits::AtomicOp<
                TOp,
                ImplementationBase,
                T,
                THierarchy>
            ::atomicOp(
                atomic,
                addr,
                value);
    }

    //-----------------------------------------------------------------------------
    //! Executes the given operation atomically.
    //!
    //! \tparam TOp The operation type.
    //! \tparam TAtomic The atomic implementation type.
    //! \tparam T The value type.
    //! \param atomic The atomic implementation.
    //! \param addr The value to change atomically.
    //! \param compare The comparison value used in the atomic operation.
    //! \param value The value used in the atomic operation.
    ALPAKA_NO_HOST_ACC_WARNING
    template<
        typename TOp,
        typename TAtomic,
        typename T,
        typename THierarchy = hierarchy::Grids>
    ALPAKA_FN_HOST_ACC auto atomicOp(
        TAtomic const & atomic,
        T * const addr,
        T const & compare,
        T const & value,
        THierarchy const & = THierarchy())
    -> T
    {
        using ImplementationBase = typename concepts::ImplementationBase<AtomicHierarchyConcept<THierarchy>, TAtomic>;
        return
            traits::AtomicOp<
                TOp,
                ImplementationBase,
                T,
                THierarchy>
            ::atomicOp(
                atomic,
                addr,
                compare,
                value);
    }
}
<commit_msg>add explicitly spelled atomic functions that call the generic atomicOp<commit_after>/* Copyright 2019 Benjamin Worpitz, René Widera
 *
 * This file is part of alpaka.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#pragma once

#include <alpaka/core/Positioning.hpp>
#include <alpaka/core/Common.hpp>
#include <alpaka/core/Concepts.hpp>
#include <alpaka/atomic/Op.hpp>

#include <type_traits>

namespace alpaka
{
    struct ConceptAtomicGrids{};
    struct ConceptAtomicBlocks{};
    struct ConceptAtomicThreads{};

    namespace detail
    {
        template<
            typename THierarchy
        >
        struct AtomicHierarchyConceptType;

        template<>
        struct AtomicHierarchyConceptType<
            hierarchy::Threads>
        {
            using type = ConceptAtomicThreads;
        };

        template<>
        struct AtomicHierarchyConceptType<
            hierarchy::Blocks>
        {
            using type = ConceptAtomicBlocks;
        };

        template<>
        struct AtomicHierarchyConceptType<
            hierarchy::Grids>
        {
            using type = ConceptAtomicGrids;
        };
    }

    template<
        typename THierarchy
    >
    using AtomicHierarchyConcept = typename detail::AtomicHierarchyConceptType<THierarchy>::type;

    //-----------------------------------------------------------------------------
    //! The atomic operation traits.
    namespace traits
    {
        //#############################################################################
        //! The atomic operation trait.
        template<
            typename TOp,
            typename TAtomic,
            typename T,
            typename THierarchy,
            typename TSfinae = void>
        struct AtomicOp;
    }

    //-----------------------------------------------------------------------------
    //! Executes the given operation atomically.
    //!
    //! \tparam TOp The operation type.
    //! \tparam T The value type.
    //! \tparam TAtomic The atomic implementation type.
    //! \param addr The value to change atomically.
    //! \param value The value used in the atomic operation.
    //! \param atomic The atomic implementation.
    ALPAKA_NO_HOST_ACC_WARNING
    template<
        typename TOp,
        typename TAtomic,
        typename T,
        typename THierarchy = hierarchy::Grids>
    ALPAKA_FN_HOST_ACC auto atomicOp(
        TAtomic const & atomic,
        T * const addr,
        T const & value,
        THierarchy const & = THierarchy())
    -> T
    {
        using ImplementationBase = typename concepts::ImplementationBase<AtomicHierarchyConcept<THierarchy>, TAtomic>;
        return
            traits::AtomicOp<
                TOp,
                ImplementationBase,
                T,
                THierarchy>
            ::atomicOp(
                atomic,
                addr,
                value);
    }

    //-----------------------------------------------------------------------------
    //! Executes the given operation atomically.
    //!
    //! \tparam TOp The operation type.
    //! \tparam TAtomic The atomic implementation type.
    //! \tparam T The value type.
    //! \param atomic The atomic implementation.
    //! \param addr The value to change atomically.
    //! \param compare The comparison value used in the atomic operation.
    //! \param value The value used in the atomic operation.
    ALPAKA_NO_HOST_ACC_WARNING
    template<
        typename TOp,
        typename TAtomic,
        typename T,
        typename THierarchy = hierarchy::Grids>
    ALPAKA_FN_HOST_ACC auto atomicOp(
        TAtomic const & atomic,
        T * const addr,
        T const & compare,
        T const & value,
        THierarchy const & = THierarchy())
    -> T
    {
        using ImplementationBase = typename concepts::ImplementationBase<AtomicHierarchyConcept<THierarchy>, TAtomic>;
        return
            traits::AtomicOp<
                TOp,
                ImplementationBase,
                T,
                THierarchy>
            ::atomicOp(
                atomic,
                addr,
                compare,
                value);
    }

    //-----------------------------------------------------------------------------
    //! Executes an atomic add operation.
    //!
    //! \tparam T The value type.
    //! \tparam TAtomic The atomic implementation type.
    //! \param addr The value to change atomically.
    //! \param value The value used in the atomic operation.
    //! \param atomic The atomic implementation.
    ALPAKA_NO_HOST_ACC_WARNING
        template<
        typename TAtomic,
        typename T,
        typename THierarchy = hierarchy::Grids>
        ALPAKA_FN_HOST_ACC auto atomicAdd(
            TAtomic const& atomic,
            T* const addr,
            T const& value,
            THierarchy const& hier = THierarchy())
        -> T
    {
        return atomicOp<op::Add>(atomic, addr, value, hier);
    }

    //-----------------------------------------------------------------------------
    //! Executes an atomic sub operation.
    //!
    //! \tparam T The value type.
    //! \tparam TAtomic The atomic implementation type.
    //! \param addr The value to change atomically.
    //! \param value The value used in the atomic operation.
    //! \param atomic The atomic implementation.
    ALPAKA_NO_HOST_ACC_WARNING
        template<
        typename TAtomic,
        typename T,
        typename THierarchy = hierarchy::Grids>
        ALPAKA_FN_HOST_ACC auto atomicSub(
            TAtomic const& atomic,
            T* const addr,
            T const& value,
            THierarchy const& hier = THierarchy())
        -> T
    {
        return atomicOp<op::Sub>(atomic, addr, value, hier);
    }

    //-----------------------------------------------------------------------------
    //! Executes an atomic min operation.
    //!
    //! \tparam T The value type.
    //! \tparam TAtomic The atomic implementation type.
    //! \param addr The value to change atomically.
    //! \param value The value used in the atomic operation.
    //! \param atomic The atomic implementation.
    ALPAKA_NO_HOST_ACC_WARNING
        template<
        typename TAtomic,
        typename T,
        typename THierarchy = hierarchy::Grids>
        ALPAKA_FN_HOST_ACC auto atomicMin(
            TAtomic const& atomic,
            T* const addr,
            T const& value,
            THierarchy const& hier = THierarchy())
        -> T
    {
        return atomicOp<op::Min>(atomic, addr, value, hier);
    }

    //-----------------------------------------------------------------------------
    //! Executes an atomic max operation.
    //!
    //! \tparam T The value type.
    //! \tparam TAtomic The atomic implementation type.
    //! \param addr The value to change atomically.
    //! \param value The value used in the atomic operation.
    //! \param atomic The atomic implementation.
    ALPAKA_NO_HOST_ACC_WARNING
        template<
        typename TAtomic,
        typename T,
        typename THierarchy = hierarchy::Grids>
        ALPAKA_FN_HOST_ACC auto atomicMax(
            TAtomic const& atomic,
            T* const addr,
            T const& value,
            THierarchy const& hier = THierarchy())
        -> T
    {
        return atomicOp<op::Max>(atomic, addr, value, hier);
    }

    //-----------------------------------------------------------------------------
    //! Executes an atomic exchange operation.
    //!
    //! \tparam T The value type.
    //! \tparam TAtomic The atomic implementation type.
    //! \param addr The value to change atomically.
    //! \param value The value used in the atomic operation.
    //! \param atomic The atomic implementation.
    ALPAKA_NO_HOST_ACC_WARNING
        template<
        typename TAtomic,
        typename T,
        typename THierarchy = hierarchy::Grids>
        ALPAKA_FN_HOST_ACC auto atomicExch(
            TAtomic const& atomic,
            T* const addr,
            T const& value,
            THierarchy const& hier = THierarchy())
        -> T
    {
        return atomicOp<op::Exch>(atomic, addr, value, hier);
    }

    //-----------------------------------------------------------------------------
    //! Executes an atomic increment operation.
    //!
    //! \tparam T The value type.
    //! \tparam TAtomic The atomic implementation type.
    //! \param addr The value to change atomically.
    //! \param value The value used in the atomic operation.
    //! \param atomic The atomic implementation.
    ALPAKA_NO_HOST_ACC_WARNING
        template<
        typename TAtomic,
        typename T,
        typename THierarchy = hierarchy::Grids>
        ALPAKA_FN_HOST_ACC auto atomicInc(
            TAtomic const& atomic,
            T* const addr,
            T const& value,
            THierarchy const& hier = THierarchy())
        -> T
    {
        return atomicOp<op::Inc>(atomic, addr, value, hier);
    }

    //-----------------------------------------------------------------------------
    //! Executes an atomic decrement operation.
    //!
    //! \tparam T The value type.
    //! \tparam TAtomic The atomic implementation type.
    //! \param addr The value to change atomically.
    //! \param value The value used in the atomic operation.
    //! \param atomic The atomic implementation.
    ALPAKA_NO_HOST_ACC_WARNING
        template<
        typename TAtomic,
        typename T,
        typename THierarchy = hierarchy::Grids>
        ALPAKA_FN_HOST_ACC auto atomicDec(
            TAtomic const& atomic,
            T* const addr,
            T const& value,
            THierarchy const& hier = THierarchy())
        -> T
    {
        return atomicOp<op::Dec>(atomic, addr, value, hier);
    }

    //-----------------------------------------------------------------------------
    //! Executes an atomic and operation.
    //!
    //! \tparam T The value type.
    //! \tparam TAtomic The atomic implementation type.
    //! \param addr The value to change atomically.
    //! \param value The value used in the atomic operation.
    //! \param atomic The atomic implementation.
    ALPAKA_NO_HOST_ACC_WARNING
        template<
        typename TAtomic,
        typename T,
        typename THierarchy = hierarchy::Grids>
        ALPAKA_FN_HOST_ACC auto atomicAnd(
            TAtomic const& atomic,
            T* const addr,
            T const& value,
            THierarchy const& hier = THierarchy())
        -> T
    {
        return atomicOp<op::And>(atomic, addr, value, hier);
    }

    //-----------------------------------------------------------------------------
    //! Executes an atomic or operation.
    //!
    //! \tparam T The value type.
    //! \tparam TAtomic The atomic implementation type.
    //! \param addr The value to change atomically.
    //! \param value The value used in the atomic operation.
    //! \param atomic The atomic implementation.
    ALPAKA_NO_HOST_ACC_WARNING
        template<
        typename TAtomic,
        typename T,
        typename THierarchy = hierarchy::Grids>
        ALPAKA_FN_HOST_ACC auto atomicOr(
            TAtomic const& atomic,
            T* const addr,
            T const& value,
            THierarchy const& hier = THierarchy())
        -> T
    {
        return atomicOp<op::Or>(atomic, addr, value, hier);
    }

    //-----------------------------------------------------------------------------
    //! Executes an atomic xor operation.
    //!
    //! \tparam T The value type.
    //! \tparam TAtomic The atomic implementation type.
    //! \param addr The value to change atomically.
    //! \param value The value used in the atomic operation.
    //! \param atomic The atomic implementation.
    ALPAKA_NO_HOST_ACC_WARNING
        template<
        typename TAtomic,
        typename T,
        typename THierarchy = hierarchy::Grids>
        ALPAKA_FN_HOST_ACC auto atomicXor(
            TAtomic const& atomic,
            T* const addr,
            T const& value,
            THierarchy const& hier = THierarchy())
        -> T
    {
        return atomicOp<op::Xor>(atomic, addr, value, hier);
    }

    //-----------------------------------------------------------------------------
    //! Executes an atomic compare-and-swap operation.
    //!
    //! \tparam TAtomic The atomic implementation type.
    //! \tparam T The value type.
    //! \param atomic The atomic implementation.
    //! \param addr The value to change atomically.
    //! \param compare The comparison value used in the atomic operation.
    //! \param value The value used in the atomic operation.
    ALPAKA_NO_HOST_ACC_WARNING
        template<
        typename TAtomic,
        typename T,
        typename THierarchy = hierarchy::Grids>
        ALPAKA_FN_HOST_ACC auto atomicCas(
            TAtomic const& atomic,
            T* const addr,
            T const& compare,
            T const& value,
            THierarchy const& hier = THierarchy())
        -> T
    {
        return atomicOp<op::Cas>(atomic, addr, compare, value, hier);
    }
}
<|endoftext|>


<commit_before><commit_msg>Do seek, not doSeek directly.<commit_after><|endoftext|>


<commit_before>#ifndef FORMAST_DETAIL_PARSE_HPP_INCLUDED
#define FORMAST_DETAIL_PARSE_HPP_INCLUDED

#define BOOST_SPIRIT_NO_PREDEFINED_TERMINALS
// #define BOOST_SPIRIT_QI_DEBUG

#include <boost/spirit/include/phoenix_function.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/qi.hpp>

#include "formast/detail/ast.hpp"

namespace formast
{
namespace detail
{
namespace parse
{

// a few shorthands

namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;

// phoenix functions for constructing the abstract syntax tree with
// semantic actions

template <typename T> // T is a terminal type, i.e. uint64_t or std::string
struct assign_func {
    template <typename T1, typename T2 = void>
    struct result {
        typedef void type;
    };

    void operator()(formast::detail::ast::Expr & left, const T & right) const {
        left = formast::detail::ast::Expr(new formast::detail::ast::ExprNode(right));
    }
};

template <char Op>
struct binary_func {
    template <typename T1, typename T2 = void>
    struct result {
        typedef void type;
    };

    void operator()(formast::detail::ast::Expr & left, formast::detail::ast::Expr const & right) const {
        left = formast::detail::ast::Expr(new formast::detail::ast::ExprNode(formast::detail::ast::binary_op(Op, left, right)));
    }
};

template <char Op>
struct unary_func {
    template <typename T1, typename T2 = void>
    struct result {
        typedef void type;
    };

    void operator()(formast::detail::ast::Expr & right) const {
        right = formast::detail::ast::Expr(new formast::detail::ast::ExprNode(formast::detail::ast::unary_op(Op, right)));
    }
};

boost::phoenix::function<binary_func<'+'> > const add;
boost::phoenix::function<binary_func<'-'> > const sub;
boost::phoenix::function<binary_func<'*'> > const mul;
boost::phoenix::function<binary_func<'/'> > const div;
boost::phoenix::function<unary_func<'+'> > const pos;
boost::phoenix::function<unary_func<'-'> > const neg;
boost::phoenix::function<assign_func<boost::uint64_t> > const assign_uint;

// error handler

struct error_handler_ {
    template <typename, typename, typename>
    struct result {
        typedef void type;
    };

    template <typename Iterator>
    void operator()(
        qi::info const& what, Iterator err_pos, Iterator last) const {
        std::cerr
                << "Error! Expecting "
                << what
                << " here: \""
                << std::string(err_pos, last)
                << "\""
                << std::endl
                ;
    }
};

boost::phoenix::function<error_handler_> const error_handler = error_handler_();

// the actual grammar

template <typename Iterator>
struct parser : qi::grammar<Iterator, formast::detail::ast::Expr(), ascii::space_type> {

    parser() : parser::base_type(expr) {

    qi::char_type char_;
    qi::uint_type uint_;
    qi::_val_type _val;
    qi::_1_type _1;
    qi::_2_type _2;
    qi::_3_type _3;
    qi::_4_type _4;

    using qi::on_error;
    using qi::fail;

    expr =
        term                            [_val = _1]
        >> *(   ('+' > term             [add(_val, _1)])
                |   ('-' > term         [sub(_val, _1)])
            )
        ;

    term =
        factor                          [_val = _1]
        >> *(   ('*' > factor           [mul(_val, _1)])
                |   ('/' > factor       [div(_val, _1)])
            )
        ;

    factor =
        uint_                           [assign_uint(_val, _1)]
        |   '(' > expr                  [_val = _1] > ')'
        |   ('-' > factor               [neg(_1)])
        |   ('+' > factor               [pos(_1)])
        ;

    // Debugging and error handling and reporting support.
    BOOST_SPIRIT_DEBUG_NODE(expr);
    BOOST_SPIRIT_DEBUG_NODE(term);
    BOOST_SPIRIT_DEBUG_NODE(factor);

    // Error handling
    on_error<fail>(expr, error_handler(_4, _3, _2));
}

qi::rule<Iterator, formast::detail::ast::Expr(), ascii::space_type> expr, term, factor;
};

}
}
}

#endif
<commit_msg>Abbreviate long namespace.<commit_after>#ifndef FORMAST_DETAIL_PARSE_HPP_INCLUDED
#define FORMAST_DETAIL_PARSE_HPP_INCLUDED

#define BOOST_SPIRIT_NO_PREDEFINED_TERMINALS
// #define BOOST_SPIRIT_QI_DEBUG

#include <boost/spirit/include/phoenix_function.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/qi.hpp>

#include "formast/detail/ast.hpp"

namespace formast
{
namespace detail
{
namespace parse
{

// a few shorthands

namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
namespace ast = formast::detail::ast;

// phoenix functions for constructing the abstract syntax tree with
// semantic actions

template <typename T> // T is a terminal type, i.e. uint64_t or std::string
struct assign_func {
    template <typename T1, typename T2 = void>
    struct result {
        typedef void type;
    };

    void operator()(ast::Expr & left, const T & right) const {
        left = ast::Expr(new ast::ExprNode(right));
    }
};

template <char Op>
struct binary_func {
    template <typename T1, typename T2 = void>
    struct result {
        typedef void type;
    };

    void operator()(ast::Expr & left, ast::Expr const & right) const {
        left = ast::Expr(new ast::ExprNode(ast::binary_op(Op, left, right)));
    }
};

template <char Op>
struct unary_func {
    template <typename T1, typename T2 = void>
    struct result {
        typedef void type;
    };

    void operator()(ast::Expr & right) const {
        right = ast::Expr(new ast::ExprNode(ast::unary_op(Op, right)));
    }
};

boost::phoenix::function<binary_func<'+'> > const add;
boost::phoenix::function<binary_func<'-'> > const sub;
boost::phoenix::function<binary_func<'*'> > const mul;
boost::phoenix::function<binary_func<'/'> > const div;
boost::phoenix::function<unary_func<'+'> > const pos;
boost::phoenix::function<unary_func<'-'> > const neg;
boost::phoenix::function<assign_func<boost::uint64_t> > const assign_uint;

// error handler

struct error_handler_ {
    template <typename, typename, typename>
    struct result {
        typedef void type;
    };

    template <typename Iterator>
    void operator()(
        qi::info const& what, Iterator err_pos, Iterator last) const {
        std::cerr
                << "Error! Expecting "
                << what
                << " here: \""
                << std::string(err_pos, last)
                << "\""
                << std::endl
                ;
    }
};

boost::phoenix::function<error_handler_> const error_handler = error_handler_();

// the actual grammar

template <typename Iterator>
struct parser : qi::grammar<Iterator, ast::Expr(), ascii::space_type> {

    parser() : parser::base_type(expr) {

    qi::char_type char_;
    qi::uint_type uint_;
    qi::_val_type _val;
    qi::_1_type _1;
    qi::_2_type _2;
    qi::_3_type _3;
    qi::_4_type _4;

    using qi::on_error;
    using qi::fail;

    expr =
        term                            [_val = _1]
        >> *(   ('+' > term             [add(_val, _1)])
                |   ('-' > term         [sub(_val, _1)])
            )
        ;

    term =
        factor                          [_val = _1]
        >> *(   ('*' > factor           [mul(_val, _1)])
                |   ('/' > factor       [div(_val, _1)])
            )
        ;

    factor =
        uint_                           [assign_uint(_val, _1)]
        |   '(' > expr                  [_val = _1] > ')'
        |   ('-' > factor               [neg(_1)])
        |   ('+' > factor               [pos(_1)])
        ;

    // Debugging and error handling and reporting support.
    BOOST_SPIRIT_DEBUG_NODE(expr);
    BOOST_SPIRIT_DEBUG_NODE(term);
    BOOST_SPIRIT_DEBUG_NODE(factor);

    // Error handling
    on_error<fail>(expr, error_handler(_4, _3, _2));
}

qi::rule<Iterator, ast::Expr(), ascii::space_type> expr, term, factor;
};

}
}
}

#endif
<|endoftext|>