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

#include "base/path_service.h"

#ifdef OS_WIN
#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
#endif

#include "base/hash_tables.h"
#include "base/file_util.h"
#include "base/lock.h"
#include "base/logging.h"
#include "base/singleton.h"
#include "base/string_util.h"

namespace base {
  bool PathProvider(int key, std::wstring* result);
#if defined(OS_WIN)
  bool PathProviderWin(int key, std::wstring* result);
#elif defined(OS_MACOSX)
  bool PathProviderMac(int key, std::wstring* result);
#elif defined(OS_LINUX)
  bool PathProviderLinux(int key, std::wstring* result);
#endif
}

namespace {

typedef base::hash_map<int, std::wstring> PathMap;
typedef base::hash_set<int> PathSet;

// We keep a linked list of providers.  In a debug build we ensure that no two
// providers claim overlapping keys.
struct Provider {
  PathService::ProviderFunc func;
  struct Provider* next;
#ifndef NDEBUG
  int key_start;
  int key_end;
#endif
};

static Provider base_provider = {
  base::PathProvider,
  NULL,
#ifndef NDEBUG
  base::PATH_START,
  base::PATH_END
#endif
};

#ifdef OS_WIN
static Provider base_provider_win = {
  base::PathProviderWin,
  &base_provider,
#ifndef NDEBUG
  base::PATH_WIN_START,
  base::PATH_WIN_END
#endif
};
#endif

#ifdef OS_MACOSX
  static Provider base_provider_mac = {
  base::PathProviderMac,
  &base_provider,
#ifndef NDEBUG
  base::PATH_MAC_START,
  base::PATH_MAC_END
#endif
  };
#endif

#if defined(OS_LINUX)
static Provider base_provider_linux = {
  base::PathProviderLinux,
  &base_provider,
#ifndef NDEBUG
  base::PATH_LINUX_START,
  base::PATH_LINUX_END
#endif
  };
#endif

struct PathData {
  Lock      lock;
  PathMap   cache;      // Track mappings from path key to path value.
  PathSet   overrides;  // Track whether a path has been overridden.
  Provider* providers;  // Linked list of path service providers.

  PathData() {
#if defined(OS_WIN)
    providers = &base_provider_win;
#elif defined(OS_MACOSX)
    providers = &base_provider_mac;
#elif defined(OS_LINUX)
    providers = &base_provider_linux;
#endif
  }
};

static PathData* GetPathData() {
  return Singleton<PathData>::get();
}

}  // namespace

// static
bool PathService::GetFromCache(int key, std::wstring* result) {
  PathData* path_data = GetPathData();
  AutoLock scoped_lock(path_data->lock);

  // check for a cached version
  PathMap::const_iterator it = path_data->cache.find(key);
  if (it != path_data->cache.end()) {
    *result = it->second;
    return true;
  }
  return false;
}

// static
void PathService::AddToCache(int key, const std::wstring& path) {
  PathData* path_data = GetPathData();
  AutoLock scoped_lock(path_data->lock);
  // Save the computed path in our cache.
  path_data->cache[key] = path;
}

// TODO(brettw): this function does not handle long paths (filename > MAX_PATH)
// characters). This isn't supported very well by Windows right now, so it is
// moot, but we should keep this in mind for the future.
// static
bool PathService::Get(int key, std::wstring* result) {
  PathData* path_data = GetPathData();
  DCHECK(path_data);
  DCHECK(result);
  DCHECK(key >= base::DIR_CURRENT);

  // special case the current directory because it can never be cached
  if (key == base::DIR_CURRENT)
    return file_util::GetCurrentDirectory(result);

  if (GetFromCache(key, result))
    return true;

  std::wstring path;

  // search providers for the requested path
  // NOTE: it should be safe to iterate here without the lock
  // since RegisterProvider always prepends.
  Provider* provider = path_data->providers;
  while (provider) {
    if (provider->func(key, &path))
      break;
    DCHECK(path.empty()) << "provider should not have modified path";
    provider = provider->next;
  }

  if (path.empty())
    return false;

  AddToCache(key, path);

  result->swap(path);
  return true;
}

bool PathService::IsOverridden(int key) {
  PathData* path_data = GetPathData();
  DCHECK(path_data);

  AutoLock scoped_lock(path_data->lock);
  return path_data->overrides.find(key) != path_data->overrides.end();
}

bool PathService::Override(int key, const std::wstring& path) {
  PathData* path_data = GetPathData();
  DCHECK(path_data);
  DCHECK(key > base::DIR_CURRENT) << "invalid path key";

  std::wstring file_path = path;
  if (!file_util::AbsolutePath(&file_path))
    return false;

  // make sure the directory exists:
  if (!file_util::PathExists(file_path) &&
      // TODO(darin): what if this path is not that of a directory?
      !file_util::CreateDirectory(file_path))
    return false;

  file_util::TrimTrailingSeparator(&file_path);

  AutoLock scoped_lock(path_data->lock);
  path_data->cache[key] = file_path;
  path_data->overrides.insert(key);
  return true;
}

bool PathService::SetCurrentDirectory(const std::wstring& current_directory) {
  return file_util::SetCurrentDirectory(current_directory);
}

void PathService::RegisterProvider(ProviderFunc func, int key_start,
                                   int key_end) {
  PathData* path_data = GetPathData();
  DCHECK(path_data);
  DCHECK(key_end > key_start);

  AutoLock scoped_lock(path_data->lock);

  Provider* p;

#ifndef NDEBUG
  p = path_data->providers;
  while (p) {
    DCHECK(key_start >= p->key_end || key_end <= p->key_start) <<
      "path provider collision";
    p = p->next;
  }
#endif

  p = new Provider;
  p->func = func;
  p->next = path_data->providers;
#ifndef NDEBUG
  p->key_start = key_start;
  p->key_end = key_end;
#endif
  path_data->providers = p;
}
<commit_msg>For some reason, when I changed PathData to be a singleton (r722) Purify started noticing the leak that had existed in this data structure all along.  Now we clean up the heap objects correctly.<commit_after>// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//    * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//    * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//    * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "base/path_service.h"

#ifdef OS_WIN
#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
#endif

#include "base/hash_tables.h"
#include "base/file_util.h"
#include "base/lock.h"
#include "base/logging.h"
#include "base/singleton.h"
#include "base/string_util.h"

namespace base {
  bool PathProvider(int key, std::wstring* result);
#if defined(OS_WIN)
  bool PathProviderWin(int key, std::wstring* result);
#elif defined(OS_MACOSX)
  bool PathProviderMac(int key, std::wstring* result);
#elif defined(OS_LINUX)
  bool PathProviderLinux(int key, std::wstring* result);
#endif
}

namespace {

typedef base::hash_map<int, std::wstring> PathMap;
typedef base::hash_set<int> PathSet;

// We keep a linked list of providers.  In a debug build we ensure that no two
// providers claim overlapping keys.
struct Provider {
  PathService::ProviderFunc func;
  struct Provider* next;
#ifndef NDEBUG
  int key_start;
  int key_end;
#endif
  bool is_static;
};

static Provider base_provider = {
  base::PathProvider,
  NULL,
#ifndef NDEBUG
  base::PATH_START,
  base::PATH_END,
#endif
  true
};

#ifdef OS_WIN
static Provider base_provider_win = {
  base::PathProviderWin,
  &base_provider,
#ifndef NDEBUG
  base::PATH_WIN_START,
  base::PATH_WIN_END,
#endif
  true
};
#endif

#ifdef OS_MACOSX
static Provider base_provider_mac = {
  base::PathProviderMac,
  &base_provider,
#ifndef NDEBUG
  base::PATH_MAC_START,
  base::PATH_MAC_END,
#endif
  true
};
#endif

#if defined(OS_LINUX)
static Provider base_provider_linux = {
  base::PathProviderLinux,
  &base_provider,
#ifndef NDEBUG
  base::PATH_LINUX_START,
  base::PATH_LINUX_END,
#endif
  true
};
#endif

struct PathData {
  Lock      lock;
  PathMap   cache;      // Track mappings from path key to path value.
  PathSet   overrides;  // Track whether a path has been overridden.
  Provider* providers;  // Linked list of path service providers.

  PathData() {
#if defined(OS_WIN)
    providers = &base_provider_win;
#elif defined(OS_MACOSX)
    providers = &base_provider_mac;
#elif defined(OS_LINUX)
    providers = &base_provider_linux;
#endif
  }

  ~PathData() {
    Provider* p = providers;
    while (p) {
      Provider* next = p->next;
      if (!p->is_static)
        delete p;
      p = next;
    }
  }
};

static PathData* GetPathData() {
  return Singleton<PathData>::get();
}

}  // namespace

// static
bool PathService::GetFromCache(int key, std::wstring* result) {
  PathData* path_data = GetPathData();
  AutoLock scoped_lock(path_data->lock);

  // check for a cached version
  PathMap::const_iterator it = path_data->cache.find(key);
  if (it != path_data->cache.end()) {
    *result = it->second;
    return true;
  }
  return false;
}

// static
void PathService::AddToCache(int key, const std::wstring& path) {
  PathData* path_data = GetPathData();
  AutoLock scoped_lock(path_data->lock);
  // Save the computed path in our cache.
  path_data->cache[key] = path;
}

// TODO(brettw): this function does not handle long paths (filename > MAX_PATH)
// characters). This isn't supported very well by Windows right now, so it is
// moot, but we should keep this in mind for the future.
// static
bool PathService::Get(int key, std::wstring* result) {
  PathData* path_data = GetPathData();
  DCHECK(path_data);
  DCHECK(result);
  DCHECK(key >= base::DIR_CURRENT);

  // special case the current directory because it can never be cached
  if (key == base::DIR_CURRENT)
    return file_util::GetCurrentDirectory(result);

  if (GetFromCache(key, result))
    return true;

  std::wstring path;

  // search providers for the requested path
  // NOTE: it should be safe to iterate here without the lock
  // since RegisterProvider always prepends.
  Provider* provider = path_data->providers;
  while (provider) {
    if (provider->func(key, &path))
      break;
    DCHECK(path.empty()) << "provider should not have modified path";
    provider = provider->next;
  }

  if (path.empty())
    return false;

  AddToCache(key, path);

  result->swap(path);
  return true;
}

bool PathService::IsOverridden(int key) {
  PathData* path_data = GetPathData();
  DCHECK(path_data);

  AutoLock scoped_lock(path_data->lock);
  return path_data->overrides.find(key) != path_data->overrides.end();
}

bool PathService::Override(int key, const std::wstring& path) {
  PathData* path_data = GetPathData();
  DCHECK(path_data);
  DCHECK(key > base::DIR_CURRENT) << "invalid path key";

  std::wstring file_path = path;
  if (!file_util::AbsolutePath(&file_path))
    return false;

  // make sure the directory exists:
  if (!file_util::PathExists(file_path) &&
      // TODO(darin): what if this path is not that of a directory?
      !file_util::CreateDirectory(file_path))
    return false;

  file_util::TrimTrailingSeparator(&file_path);

  AutoLock scoped_lock(path_data->lock);
  path_data->cache[key] = file_path;
  path_data->overrides.insert(key);
  return true;
}

bool PathService::SetCurrentDirectory(const std::wstring& current_directory) {
  return file_util::SetCurrentDirectory(current_directory);
}

void PathService::RegisterProvider(ProviderFunc func, int key_start,
                                   int key_end) {
  PathData* path_data = GetPathData();
  DCHECK(path_data);
  DCHECK(key_end > key_start);

  AutoLock scoped_lock(path_data->lock);

  Provider* p;

#ifndef NDEBUG
  p = path_data->providers;
  while (p) {
    DCHECK(key_start >= p->key_end || key_end <= p->key_start) <<
      "path provider collision";
    p = p->next;
  }
#endif

  p = new Provider;
  p->is_static = false;
  p->func = func;
  p->next = path_data->providers;
#ifndef NDEBUG
  p->key_start = key_start;
  p->key_end = key_end;
#endif
  path_data->providers = p;
}
<|endoftext|>


<commit_before>#include <typeinfo>
#include <Eigen/Core>
#include "BenchTimer.h"
using namespace Eigen;
using namespace std;

template<typename T>
EIGEN_DONT_INLINE typename T::Scalar sqsumNorm(const T& v)
{
  return v.norm();
}

template<typename T>
EIGEN_DONT_INLINE typename T::Scalar hypotNorm(const T& v)
{
  return v.stableNorm();
}

template<typename T>
EIGEN_DONT_INLINE typename T::Scalar blueNorm(const T& v)
{
  return v.blueNorm();
}

template<typename T>
EIGEN_DONT_INLINE typename T::Scalar lapackNorm(T& v)
{
  typedef typename T::Scalar Scalar;
  int n = v.size();
  Scalar scale = 1;
  Scalar ssq = 0;
  for (int i=0;i<n;++i)
  {
    Scalar ax = ei_abs(v.coeff(i));
    if (scale < ax)
    {
      ssq = Scalar(1) + ssq * ei_abs2(scale/ax);
      scale = ax;
    }
    else
      ssq += ei_abs2(ax/scale);
  }
  return scale * ei_sqrt(ssq);
}

template<typename T>
EIGEN_DONT_INLINE typename T::Scalar divacNorm(T& v)
{
  int n =v.size() / 2;
  for (int i=0;i<n;++i)
    v(i) = v(2*i)*v(2*i) + v(2*i+1)*v(2*i+1);
  n = n/2;
  while (n>0)
  {
    for (int i=0;i<n;++i)
      v(i) = v(2*i) + v(2*i+1);
    n = n/2;
  }
  return ei_sqrt(v(0));
}

#ifdef EIGEN_VECTORIZE
Packet4f ei_plt(const Packet4f& a, Packet4f& b) { return _mm_cmplt_ps(a,b); }
Packet2d ei_plt(const Packet2d& a, Packet2d& b) { return _mm_cmplt_pd(a,b); }

Packet4f ei_pandnot(const Packet4f& a, Packet4f& b) { return _mm_andnot_ps(a,b); }
Packet2d ei_pandnot(const Packet2d& a, Packet2d& b) { return _mm_andnot_pd(a,b); }
#endif

template<typename T>
EIGEN_DONT_INLINE typename T::Scalar pblueNorm(const T& v)
{
  #ifndef EIGEN_VECTORIZE
  return v.blueNorm();
  #else
  typedef typename T::Scalar Scalar;

  static int nmax = 0;
  static Scalar b1, b2, s1m, s2m, overfl, rbig, relerr;
  int n;

  if(nmax <= 0)
  {
    int nbig, ibeta, it, iemin, iemax, iexp;
    Scalar abig, eps;

    nbig  = std::numeric_limits<int>::max();            // largest integer
    ibeta = std::numeric_limits<Scalar>::radix; //NumTraits<Scalar>::Base;                    // base for floating-point numbers
    it    = std::numeric_limits<Scalar>::digits; //NumTraits<Scalar>::Mantissa;                // number of base-beta digits in mantissa
    iemin = std::numeric_limits<Scalar>::min_exponent;  // minimum exponent
    iemax = std::numeric_limits<Scalar>::max_exponent;  // maximum exponent
    rbig  = std::numeric_limits<Scalar>::max();         // largest floating-point number

    // Check the basic machine-dependent constants.
    if(iemin > 1 - 2*it || 1+it>iemax || (it==2 && ibeta<5)
      || (it<=4 && ibeta <= 3 ) || it<2)
    {
      ei_assert(false && "the algorithm cannot be guaranteed on this computer");
    }
    iexp  = -((1-iemin)/2);
    b1    = std::pow(ibeta, iexp);  // lower boundary of midrange
    iexp  = (iemax + 1 - it)/2;
    b2    = std::pow(ibeta,iexp);   // upper boundary of midrange

    iexp  = (2-iemin)/2;
    s1m   = std::pow(ibeta,iexp);   // scaling factor for lower range
    iexp  = - ((iemax+it)/2);
    s2m   = std::pow(ibeta,iexp);   // scaling factor for upper range

    overfl  = rbig*s2m;          // overfow boundary for abig
    eps     = std::pow(ibeta, 1-it);
    relerr  = ei_sqrt(eps);      // tolerance for neglecting asml
    abig    = 1.0/eps - 1.0;
    if (Scalar(nbig)>abig)  nmax = abig;  // largest safe n
    else                    nmax = nbig;
  }

  typedef typename ei_packet_traits<Scalar>::type Packet;
  const int ps = ei_packet_traits<Scalar>::size;
  Packet pasml = ei_pset1(Scalar(0));
  Packet pamed = ei_pset1(Scalar(0));
  Packet pabig = ei_pset1(Scalar(0));
  Packet ps2m = ei_pset1(s2m);
  Packet ps1m = ei_pset1(s1m);
  Packet pb2  = ei_pset1(b2);
  Packet pb1  = ei_pset1(b1);
  for(int j=0; j<v.size(); j+=ps)
  {
    Packet ax = ei_pabs(v.template packet<Aligned>(j));
    Packet ax_s2m = ei_pmul(ax,ps2m);
    Packet ax_s1m = ei_pmul(ax,ps1m);
    Packet maskBig = ei_plt(pb2,ax);
    Packet maskSml = ei_plt(ax,pb1);
    pabig = ei_padd(pabig, ei_pand(maskBig, ei_pmul(ax_s2m,ax_s2m)));
    pasml = ei_padd(pasml, ei_pand(maskSml, ei_pmul(ax_s1m,ax_s1m)));
    pamed = ei_padd(pamed, ei_pandnot(ei_pmul(ax,ax),ei_pand(maskSml,maskBig)));
  }
  Scalar abig = ei_predux(pabig);
  Scalar asml = ei_predux(pasml);
  Scalar amed = ei_predux(pamed);
  if(abig > Scalar(0))
  {
    abig = ei_sqrt(abig);
    if(abig > overfl)
    {
      ei_assert(false && "overflow");
      return rbig;
    }
    if(amed > Scalar(0))
    {
      abig = abig/s2m;
      amed = ei_sqrt(amed);
    }
    else
    {
      return abig/s2m;
    }

  }
  else if(asml > Scalar(0))
  {
    if (amed > Scalar(0))
    {
      abig = ei_sqrt(amed);
      amed = ei_sqrt(asml) / s1m;
    }
    else
    {
      return ei_sqrt(asml)/s1m;
    }
  }
  else
  {
    return ei_sqrt(amed);
  }
  asml = std::min(abig, amed);
  abig = std::max(abig, amed);
  if(asml <= abig*relerr)
    return abig;
  else
    return abig * ei_sqrt(Scalar(1) + ei_abs2(asml/abig));
  #endif
}

#define BENCH_PERF(NRM) { \
  Eigen::BenchTimer tf, td; tf.reset(); td.reset();\
  for (int k=0; k<tries; ++k) { \
    tf.start(); \
    for (int i=0; i<iters; ++i) NRM(vf); \
    tf.stop(); \
  } \
  for (int k=0; k<tries; ++k) { \
    td.start(); \
    for (int i=0; i<iters; ++i) NRM(vd); \
    td.stop(); \
  } \
  std::cout << #NRM << "\t" << tf.value() << "   " << td.value() << "\n"; \
}

void check_accuracy(double basef, double based, int s)
{
  double yf = basef * ei_abs(ei_random<double>());
  double yd = based * ei_abs(ei_random<double>());
  VectorXf vf = VectorXf::Ones(s) * yf;
  VectorXd vd = VectorXd::Ones(s) * yd;

  std::cout << "reference\t" << ei_sqrt(double(s))*yf << "\t" << ei_sqrt(double(s))*yd << "\n";
  std::cout << "sqsumNorm\t" << sqsumNorm(vf) << "\t" << sqsumNorm(vd) << "\n";
  std::cout << "hypotNorm\t" << hypotNorm(vf) << "\t" << hypotNorm(vd) << "\n";
  std::cout << "blueNorm\t" << blueNorm(vf) << "\t" << blueNorm(vd) << "\n";
  std::cout << "pblueNorm\t" << pblueNorm(vf) << "\t" << pblueNorm(vd) << "\n";
  std::cout << "lapackNorm\t" << lapackNorm(vf) << "\t" << lapackNorm(vd) << "\n";
}

void check_accuracy_var(int ef0, int ef1, int ed0, int ed1, int s)
{
  VectorXf vf(s);
  VectorXd vd(s);
  for (int i=0; i<s; ++i)
  {
    vf[i] = ei_abs(ei_random<double>()) * std::pow(double(10), ei_random<int>(ef0,ef1));
    vd[i] = ei_abs(ei_random<double>()) * std::pow(double(10), ei_random<int>(ed0,ed1));
  }

  //std::cout << "reference\t" << ei_sqrt(double(s))*yf << "\t" << ei_sqrt(double(s))*yd << "\n";
  std::cout << "sqsumNorm\t"  << sqsumNorm(vf)  << "\t" << sqsumNorm(vd)  << "\t" << sqsumNorm(vf.cast<long double>()) << "\t" << sqsumNorm(vd.cast<long double>()) << "\n";
  std::cout << "hypotNorm\t"  << hypotNorm(vf)  << "\t" << hypotNorm(vd)  << "\t" << hypotNorm(vf.cast<long double>()) << "\t" << hypotNorm(vd.cast<long double>()) << "\n";
  std::cout << "blueNorm\t"   << blueNorm(vf)   << "\t" << blueNorm(vd)   << "\t" << blueNorm(vf.cast<long double>()) << "\t" << blueNorm(vd.cast<long double>()) << "\n";
  std::cout << "pblueNorm\t"  << pblueNorm(vf)  << "\t" << pblueNorm(vd)  << "\t" << blueNorm(vf.cast<long double>()) << "\t" << blueNorm(vd.cast<long double>()) << "\n";
  std::cout << "lapackNorm\t" << lapackNorm(vf) << "\t" << lapackNorm(vd) << "\t" << lapackNorm(vf.cast<long double>()) << "\t" << lapackNorm(vd.cast<long double>()) << "\n";
}

int main(int argc, char** argv)
{
  int tries = 5;
  int iters = 100000;
  double y = 1.1345743233455785456788e12 * ei_random<double>();
  VectorXf v = VectorXf::Ones(1024) * y;

  std::cerr << "Performance (out of cache):\n";
  {
    int iters = 1;
    VectorXf vf = VectorXf::Ones(1024*1024*32) * y;
    VectorXd vd = VectorXd::Ones(1024*1024*32) * y;
    BENCH_PERF(sqsumNorm);
    BENCH_PERF(blueNorm);
    BENCH_PERF(pblueNorm);
    BENCH_PERF(lapackNorm);
    BENCH_PERF(hypotNorm);
  }

  std::cerr << "\nPerformance (in cache):\n";
  {
    int iters = 100000;
    VectorXf vf = VectorXf::Ones(512) * y;
    VectorXd vd = VectorXd::Ones(512) * y;
    BENCH_PERF(sqsumNorm);
    BENCH_PERF(blueNorm);
    BENCH_PERF(pblueNorm);
    BENCH_PERF(lapackNorm);
    BENCH_PERF(hypotNorm);
  }

  int s = 10000;
  double basef_ok = 1.1345743233455785456788e15;
  double based_ok = 1.1345743233455785456788e95;

  double basef_under = 1.1345743233455785456788e-27;
  double based_under = 1.1345743233455785456788e-315;

  double basef_over = 1.1345743233455785456788e+27;
  double based_over = 1.1345743233455785456788e+302;

  std::cout.precision(20);

  std::cerr << "\nNo under/overflow:\n";
  check_accuracy(basef_ok, based_ok, s);

  std::cerr << "\nUnderflow:\n";
  check_accuracy(basef_under, based_under, 1);

  std::cerr << "\nOverflow:\n";
  check_accuracy(basef_over, based_over, s);

  std::cerr << "\nVarying (over):\n";
  for (int k=0; k<5; ++k)
  {
    check_accuracy_var(20,27,190,302,s);
    std::cout << "\n";
  }
}
<commit_msg>add other stable norm impl. in the benchmark<commit_after>#include <typeinfo>
#include <Eigen/Array>
#include "BenchTimer.h"
using namespace Eigen;
using namespace std;

template<typename T>
EIGEN_DONT_INLINE typename T::Scalar sqsumNorm(const T& v)
{
  return v.norm();
}

template<typename T>
EIGEN_DONT_INLINE typename T::Scalar hypotNorm(const T& v)
{
  return v.stableNorm();
}

template<typename T>
EIGEN_DONT_INLINE typename T::Scalar blueNorm(const T& v)
{
  return v.blueNorm();
}

template<typename T>
EIGEN_DONT_INLINE typename T::Scalar lapackNorm(T& v)
{
  typedef typename T::Scalar Scalar;
  int n = v.size();
  Scalar scale = 0;
  Scalar ssq = 1;
  for (int i=0;i<n;++i)
  {
    Scalar ax = ei_abs(v.coeff(i));
    if (scale >= ax)
    {
      ssq += ei_abs2(ax/scale);
    }
    else
    {
      ssq = Scalar(1) + ssq * ei_abs2(scale/ax);
      scale = ax;
    }
  }
  return scale * ei_sqrt(ssq);
}

template<typename T>
EIGEN_DONT_INLINE typename T::Scalar twopassNorm(T& v)
{
  typedef typename T::Scalar Scalar;
  Scalar s = v.cwise().abs().maxCoeff();
  return s*(v/s).norm();
}

template<typename T>
EIGEN_DONT_INLINE typename T::Scalar bl2passNorm(T& v)
{
  const int blockSize = 4096;
  typedef typename T::Scalar Scalar;
  Scalar s = 0;
  Scalar ssq = 0;
  for (int bi=0; bi<v.size(); bi+=blockSize)
  {
    int r = std::min(blockSize, v.size() - bi);
    Eigen::Block<typename ei_cleantype<T>::type,Eigen::Dynamic,1,Eigen::ForceAligned> sv(v,bi,0,r,1);
    Scalar m = sv.cwise().abs().maxCoeff();
    if (m>s)
    {
      ssq = ssq * ei_abs2(s/m);
      s = m;
    }
    ssq += (sv/s).squaredNorm();
  }
  return s*ei_sqrt(ssq);
}

template<typename T>
EIGEN_DONT_INLINE typename T::Scalar divacNorm(T& v)
{
  int n =v.size() / 2;
  for (int i=0;i<n;++i)
    v(i) = v(2*i)*v(2*i) + v(2*i+1)*v(2*i+1);
  n = n/2;
  while (n>0)
  {
    for (int i=0;i<n;++i)
      v(i) = v(2*i) + v(2*i+1);
    n = n/2;
  }
  return ei_sqrt(v(0));
}

#ifdef EIGEN_VECTORIZE
Packet4f ei_plt(const Packet4f& a, Packet4f& b) { return _mm_cmplt_ps(a,b); }
Packet2d ei_plt(const Packet2d& a, Packet2d& b) { return _mm_cmplt_pd(a,b); }

Packet4f ei_pandnot(const Packet4f& a, Packet4f& b) { return _mm_andnot_ps(a,b); }
Packet2d ei_pandnot(const Packet2d& a, Packet2d& b) { return _mm_andnot_pd(a,b); }
#endif

template<typename T>
EIGEN_DONT_INLINE typename T::Scalar pblueNorm(const T& v)
{
  #ifndef EIGEN_VECTORIZE
  return v.blueNorm();
  #else
  typedef typename T::Scalar Scalar;

  static int nmax = 0;
  static Scalar b1, b2, s1m, s2m, overfl, rbig, relerr;
  int n;

  if(nmax <= 0)
  {
    int nbig, ibeta, it, iemin, iemax, iexp;
    Scalar abig, eps;

    nbig  = std::numeric_limits<int>::max();            // largest integer
    ibeta = std::numeric_limits<Scalar>::radix; //NumTraits<Scalar>::Base;                    // base for floating-point numbers
    it    = std::numeric_limits<Scalar>::digits; //NumTraits<Scalar>::Mantissa;                // number of base-beta digits in mantissa
    iemin = std::numeric_limits<Scalar>::min_exponent;  // minimum exponent
    iemax = std::numeric_limits<Scalar>::max_exponent;  // maximum exponent
    rbig  = std::numeric_limits<Scalar>::max();         // largest floating-point number

    // Check the basic machine-dependent constants.
    if(iemin > 1 - 2*it || 1+it>iemax || (it==2 && ibeta<5)
      || (it<=4 && ibeta <= 3 ) || it<2)
    {
      ei_assert(false && "the algorithm cannot be guaranteed on this computer");
    }
    iexp  = -((1-iemin)/2);
    b1    = std::pow(ibeta, iexp);  // lower boundary of midrange
    iexp  = (iemax + 1 - it)/2;
    b2    = std::pow(ibeta,iexp);   // upper boundary of midrange

    iexp  = (2-iemin)/2;
    s1m   = std::pow(ibeta,iexp);   // scaling factor for lower range
    iexp  = - ((iemax+it)/2);
    s2m   = std::pow(ibeta,iexp);   // scaling factor for upper range

    overfl  = rbig*s2m;          // overfow boundary for abig
    eps     = std::pow(ibeta, 1-it);
    relerr  = ei_sqrt(eps);      // tolerance for neglecting asml
    abig    = 1.0/eps - 1.0;
    if (Scalar(nbig)>abig)  nmax = abig;  // largest safe n
    else                    nmax = nbig;
  }

  typedef typename ei_packet_traits<Scalar>::type Packet;
  const int ps = ei_packet_traits<Scalar>::size;
  Packet pasml = ei_pset1(Scalar(0));
  Packet pamed = ei_pset1(Scalar(0));
  Packet pabig = ei_pset1(Scalar(0));
  Packet ps2m = ei_pset1(s2m);
  Packet ps1m = ei_pset1(s1m);
  Packet pb2  = ei_pset1(b2);
  Packet pb1  = ei_pset1(b1);
  for(int j=0; j<v.size(); j+=ps)
  {
    Packet ax = ei_pabs(v.template packet<Aligned>(j));
    Packet ax_s2m = ei_pmul(ax,ps2m);
    Packet ax_s1m = ei_pmul(ax,ps1m);
    Packet maskBig = ei_plt(pb2,ax);
    Packet maskSml = ei_plt(ax,pb1);
    pabig = ei_padd(pabig, ei_pand(maskBig, ei_pmul(ax_s2m,ax_s2m)));
    pasml = ei_padd(pasml, ei_pand(maskSml, ei_pmul(ax_s1m,ax_s1m)));
    pamed = ei_padd(pamed, ei_pandnot(ei_pmul(ax,ax),ei_pand(maskSml,maskBig)));
  }
  Scalar abig = ei_predux(pabig);
  Scalar asml = ei_predux(pasml);
  Scalar amed = ei_predux(pamed);
  if(abig > Scalar(0))
  {
    abig = ei_sqrt(abig);
    if(abig > overfl)
    {
      ei_assert(false && "overflow");
      return rbig;
    }
    if(amed > Scalar(0))
    {
      abig = abig/s2m;
      amed = ei_sqrt(amed);
    }
    else
    {
      return abig/s2m;
    }

  }
  else if(asml > Scalar(0))
  {
    if (amed > Scalar(0))
    {
      abig = ei_sqrt(amed);
      amed = ei_sqrt(asml) / s1m;
    }
    else
    {
      return ei_sqrt(asml)/s1m;
    }
  }
  else
  {
    return ei_sqrt(amed);
  }
  asml = std::min(abig, amed);
  abig = std::max(abig, amed);
  if(asml <= abig*relerr)
    return abig;
  else
    return abig * ei_sqrt(Scalar(1) + ei_abs2(asml/abig));
  #endif
}

#define BENCH_PERF(NRM) { \
  Eigen::BenchTimer tf, td; tf.reset(); td.reset();\
  for (int k=0; k<tries; ++k) { \
    tf.start(); \
    for (int i=0; i<iters; ++i) NRM(vf); \
    tf.stop(); \
  } \
  for (int k=0; k<tries; ++k) { \
    td.start(); \
    for (int i=0; i<iters; ++i) NRM(vd); \
    td.stop(); \
  } \
  std::cout << #NRM << "\t" << tf.value() << "   " << td.value() << "\n"; \
}

void check_accuracy(double basef, double based, int s)
{
  double yf = basef * ei_abs(ei_random<double>());
  double yd = based * ei_abs(ei_random<double>());
  VectorXf vf = VectorXf::Ones(s) * yf;
  VectorXd vd = VectorXd::Ones(s) * yd;

  std::cout << "reference\t" << ei_sqrt(double(s))*yf << "\t" << ei_sqrt(double(s))*yd << "\n";
  std::cout << "sqsumNorm\t" << sqsumNorm(vf) << "\t" << sqsumNorm(vd) << "\n";
  std::cout << "hypotNorm\t" << hypotNorm(vf) << "\t" << hypotNorm(vd) << "\n";
  std::cout << "blueNorm\t" << blueNorm(vf) << "\t" << blueNorm(vd) << "\n";
  std::cout << "pblueNorm\t" << pblueNorm(vf) << "\t" << pblueNorm(vd) << "\n";
  std::cout << "lapackNorm\t" << lapackNorm(vf) << "\t" << lapackNorm(vd) << "\n";
  std::cout << "twopassNorm\t" << twopassNorm(vf) << "\t" << twopassNorm(vd) << "\n";
  std::cout << "bl2passNorm\t" << bl2passNorm(vf) << "\t" << bl2passNorm(vd) << "\n";
}

void check_accuracy_var(int ef0, int ef1, int ed0, int ed1, int s)
{
  VectorXf vf(s);
  VectorXd vd(s);
  for (int i=0; i<s; ++i)
  {
    vf[i] = ei_abs(ei_random<double>()) * std::pow(double(10), ei_random<int>(ef0,ef1));
    vd[i] = ei_abs(ei_random<double>()) * std::pow(double(10), ei_random<int>(ed0,ed1));
  }

  //std::cout << "reference\t" << ei_sqrt(double(s))*yf << "\t" << ei_sqrt(double(s))*yd << "\n";
  std::cout << "sqsumNorm\t"  << sqsumNorm(vf)  << "\t" << sqsumNorm(vd)  << "\t" << sqsumNorm(vf.cast<long double>()) << "\t" << sqsumNorm(vd.cast<long double>()) << "\n";
  std::cout << "hypotNorm\t"  << hypotNorm(vf)  << "\t" << hypotNorm(vd)  << "\t" << hypotNorm(vf.cast<long double>()) << "\t" << hypotNorm(vd.cast<long double>()) << "\n";
  std::cout << "blueNorm\t"   << blueNorm(vf)   << "\t" << blueNorm(vd)   << "\t" << blueNorm(vf.cast<long double>()) << "\t" << blueNorm(vd.cast<long double>()) << "\n";
  std::cout << "pblueNorm\t"  << pblueNorm(vf)  << "\t" << pblueNorm(vd)  << "\t" << blueNorm(vf.cast<long double>()) << "\t" << blueNorm(vd.cast<long double>()) << "\n";
  std::cout << "lapackNorm\t" << lapackNorm(vf) << "\t" << lapackNorm(vd) << "\t" << lapackNorm(vf.cast<long double>()) << "\t" << lapackNorm(vd.cast<long double>()) << "\n";
  std::cout << "twopassNorm\t" << twopassNorm(vf) << "\t" << twopassNorm(vd) << "\t" << twopassNorm(vf.cast<long double>()) << "\t" << twopassNorm(vd.cast<long double>()) << "\n";
  std::cout << "bl2passNorm\t" << bl2passNorm(vf) << "\t" << bl2passNorm(vd) << "\t" << bl2passNorm(vf.cast<long double>()) << "\t" << bl2passNorm(vd.cast<long double>()) << "\n";
}

int main(int argc, char** argv)
{
  int tries = 10;
  int iters = 100000;
  double y = 1.1345743233455785456788e12 * ei_random<double>();
  VectorXf v = VectorXf::Ones(1024) * y;

  std::cerr << "Performance (out of cache):\n";
  {
    int iters = 1;
    VectorXf vf = VectorXf::Random(1024*1024*32) * y;
    VectorXd vd = VectorXd::Random(1024*1024*32) * y;
    BENCH_PERF(sqsumNorm);
    BENCH_PERF(blueNorm);
    BENCH_PERF(pblueNorm);
    BENCH_PERF(lapackNorm);
    BENCH_PERF(hypotNorm);
    BENCH_PERF(twopassNorm);
    BENCH_PERF(bl2passNorm);
  }

  std::cerr << "\nPerformance (in cache):\n";
  {
    int iters = 100000;
    VectorXf vf = VectorXf::Random(512) * y;
    VectorXd vd = VectorXd::Random(512) * y;
    BENCH_PERF(sqsumNorm);
    BENCH_PERF(blueNorm);
    BENCH_PERF(pblueNorm);
    BENCH_PERF(lapackNorm);
    BENCH_PERF(hypotNorm);
    BENCH_PERF(twopassNorm);
    BENCH_PERF(bl2passNorm);
  }
return 0;
  int s = 10000;
  double basef_ok = 1.1345743233455785456788e15;
  double based_ok = 1.1345743233455785456788e95;

  double basef_under = 1.1345743233455785456788e-27;
  double based_under = 1.1345743233455785456788e-303;

  double basef_over = 1.1345743233455785456788e+27;
  double based_over = 1.1345743233455785456788e+302;

  std::cout.precision(20);

  std::cerr << "\nNo under/overflow:\n";
  check_accuracy(basef_ok, based_ok, s);

  std::cerr << "\nUnderflow:\n";
  check_accuracy(basef_under, based_under, 1);

  std::cerr << "\nOverflow:\n";
  check_accuracy(basef_over, based_over, s);

  std::cerr << "\nVarying (over):\n";
  for (int k=0; k<1; ++k)
  {
    check_accuracy_var(20,27,190,302,s);
    std::cout << "\n";
  }

  std::cerr << "\nVarying (under):\n";
  for (int k=0; k<1; ++k)
  {
    check_accuracy_var(-27,20,-302,-190,s);
    std::cout << "\n";
  }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: twain.hxx,v $
 *
 *  $Revision: 1.1.1.1 $
 *
 *  last change: $Author: hr $ $Date: 2000-09-18 16:58:54 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _TWAIN_HXX
#define _TWAIN_HXX

// please add new platforms if TWAIN is available
#if defined WIN || defined WNT || defined UNX
#define TWAIN_AVAILABLE 1
#else
#undef  TWAIN_AVAILABLE
#endif

// include following only, if define is not set
#ifndef _TWAIN_HXX_CHECK

#ifndef _SV_BITMAP_HXX //autogen
#include <vcl/bitmap.hxx>
#endif

// -----------
// - Defines -
// -----------

#define TWAIN_ERR_NO_ERROR                  0
#define TWAIN_ERR_MODULE_NOT_LOADED         2
#define TWAIN_ERR_DSMENTRY_NOT_FOUND        4
#define TWAIN_ERR_SOURCE_MANAGER_NOT_OPENED 6
#define TWAIN_ERR_SOURCE_SELECTION_DIALOG   8

// ---------
// - Twain -
// ---------

struct TwainImp;
namespace com { namespace sun { namespace star { namespace lang { struct EventObject; } } } }

class Twain
{
friend class TwainEventListener;

private:

    TwainImp*           mpImp;

    Bitmap              maBitmap;
    Link                maUpdateLink;
    USHORT              mnErrorCode;
    BOOL                mbScanning;

                        Twain();
                        Twain( const Twain& rTwain );
    const Twain&        operator=( const Twain& rTwain ) { return *this; }

protected:

    void                Disposing( const com::sun::star::lang::EventObject& rEventObject );

public:

                        Twain( const Link& rUpdateLink );
                        ~Twain();

    BOOL                SelectSource();
    BOOL                PerformTransfer();

    Bitmap              GetBitmap();

    BOOL                IsScanning() const { return mbScanning; }
    USHORT              GetErrorCode() const { return mnErrorCode; }
};

#endif // _TWAIN_HXX_CHECK
#endif // _TWAIN_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.1110); FILE MERGED 2005/09/05 14:51:16 rt 1.1.1.1.1110.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: twain.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 14:11:47 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _TWAIN_HXX
#define _TWAIN_HXX

// please add new platforms if TWAIN is available
#if defined WIN || defined WNT || defined UNX
#define TWAIN_AVAILABLE 1
#else
#undef  TWAIN_AVAILABLE
#endif

// include following only, if define is not set
#ifndef _TWAIN_HXX_CHECK

#ifndef _SV_BITMAP_HXX //autogen
#include <vcl/bitmap.hxx>
#endif

// -----------
// - Defines -
// -----------

#define TWAIN_ERR_NO_ERROR                  0
#define TWAIN_ERR_MODULE_NOT_LOADED         2
#define TWAIN_ERR_DSMENTRY_NOT_FOUND        4
#define TWAIN_ERR_SOURCE_MANAGER_NOT_OPENED 6
#define TWAIN_ERR_SOURCE_SELECTION_DIALOG   8

// ---------
// - Twain -
// ---------

struct TwainImp;
namespace com { namespace sun { namespace star { namespace lang { struct EventObject; } } } }

class Twain
{
friend class TwainEventListener;

private:

    TwainImp*           mpImp;

    Bitmap              maBitmap;
    Link                maUpdateLink;
    USHORT              mnErrorCode;
    BOOL                mbScanning;

                        Twain();
                        Twain( const Twain& rTwain );
    const Twain&        operator=( const Twain& rTwain ) { return *this; }

protected:

    void                Disposing( const com::sun::star::lang::EventObject& rEventObject );

public:

                        Twain( const Link& rUpdateLink );
                        ~Twain();

    BOOL                SelectSource();
    BOOL                PerformTransfer();

    Bitmap              GetBitmap();

    BOOL                IsScanning() const { return mbScanning; }
    USHORT              GetErrorCode() const { return mnErrorCode; }
};

#endif // _TWAIN_HXX_CHECK
#endif // _TWAIN_HXX
<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkXMLFile.cxx
  Language:  C++
  Date:      $Date$
  Version:   $1.0$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

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

=========================================================================*/
#ifndef __itkXMLFile_txx
#define __itkXMLFile_txx

#include "itkXMLFile.h"
#include "itkExceptionObject.h"
#include <itksys/SystemTools.hxx>
#include <fstream>

namespace itk
{

//----------------------------------------------------------------------------
static void itkXMLParserStartElement(void* parser, const char *name,
                              const char **atts)
{
  // Begin element handler that is registered with the XML_Parser.
  // This just casts the user data to a itkXMLParser and calls
  // StartElement.
  static_cast<XMLReaderBase*>(parser)->StartElement(name, atts);
}

//----------------------------------------------------------------------------
static void itkXMLParserEndElement(void* parser, const char *name)
{
  // End element handler that is registered with the XML_Parser.  This
  // just casts the user data to a itkXMLParser and calls EndElement.
  static_cast<XMLReaderBase*>(parser)->EndElement(name);
}

//----------------------------------------------------------------------------
static void itkXMLParserCharacterDataHandler(void* parser, const char* data,
                                      int length)
{
  // Character data handler that is registered with the XML_Parser.
  // This just casts the user data to a itkXMLParser and calls
  // CharacterDataHandler.
  static_cast<XMLReaderBase*>(parser)->CharacterDataHandler(data, length);
}

void
XMLReaderBase::
parse(void)
{
  XML_Parser Parser = XML_ParserCreate(0);

  XML_SetElementHandler(Parser,
                        &itkXMLParserStartElement,
                        &itkXMLParserEndElement);

  XML_SetCharacterDataHandler(Parser,
                              &itkXMLParserCharacterDataHandler);
  XML_SetUserData(Parser,this);

  std::ifstream inputstream;

  inputstream.open(m_Filename.c_str(), std::ios::binary | std::ios::in);
  if(inputstream.fail())
    {
    ExceptionObject exception(__FILE__, __LINE__);
    std::string message = "Can't open ";
    message += m_Filename;
    message += '\n';
    exception.SetDescription(message.c_str());
    throw exception;
    }

  // Default stream parser just reads a block at a time.
  std::streamsize filesize =
    itksys::SystemTools::FileLength(m_Filename.c_str());

  char *buffer = new char [filesize];

  inputstream.read(buffer,filesize);

  if(inputstream.gcount() != filesize)
    {
    ExceptionObject exception(__FILE__, __LINE__);
    exception.SetDescription("File Read Error");
    throw exception;
    }
  bool result = XML_Parse(Parser,buffer,inputstream.gcount(),false);
  delete [] buffer;
  if(!result)
    {
    ExceptionObject exception(__FILE__, __LINE__);

    std::string message(XML_ErrorString(XML_GetErrorCode(Parser)));
    message += " ";
    message += m_Filename;
    message += '\n';
    exception.SetDescription(message.c_str());
    throw exception;

    }
  return;
}

void
XMLReaderBase::
GenerateOutputInformation()
{
  this->parse();
}

}

#endif
<commit_msg>ERR: Work around for bogus warning.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkXMLFile.cxx
  Language:  C++
  Date:      $Date$
  Version:   $1.0$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

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

=========================================================================*/
#ifndef __itkXMLFile_txx
#define __itkXMLFile_txx

#include "itkXMLFile.h"
#include "itkExceptionObject.h"
#include <itksys/SystemTools.hxx>
#include <fstream>

namespace itk
{

//----------------------------------------------------------------------------
static void itkXMLParserStartElement(void* parser, const char *name,
                              const char **atts)
{
  // Begin element handler that is registered with the XML_Parser.
  // This just casts the user data to a itkXMLParser and calls
  // StartElement.
  static_cast<XMLReaderBase*>(parser)->StartElement(name, atts);
}

//----------------------------------------------------------------------------
static void itkXMLParserEndElement(void* parser, const char *name)
{
  // End element handler that is registered with the XML_Parser.  This
  // just casts the user data to a itkXMLParser and calls EndElement.
  static_cast<XMLReaderBase*>(parser)->EndElement(name);
}

//----------------------------------------------------------------------------
static void itkXMLParserCharacterDataHandler(void* parser, const char* data,
                                      int length)
{
  // Character data handler that is registered with the XML_Parser.
  // This just casts the user data to a itkXMLParser and calls
  // CharacterDataHandler.
  static_cast<XMLReaderBase*>(parser)->CharacterDataHandler(data, length);
}

void
XMLReaderBase::
parse(void)
{
  XML_Parser Parser = XML_ParserCreate(0);

  XML_SetElementHandler(Parser,
                        &itkXMLParserStartElement,
                        &itkXMLParserEndElement);

  XML_SetCharacterDataHandler(Parser,
                              &itkXMLParserCharacterDataHandler);
  XML_SetUserData(Parser,this);

  std::ifstream inputstream;

  inputstream.open(m_Filename.c_str(), std::ios::binary | std::ios::in);
  if(inputstream.fail())
    {
    ExceptionObject exception(__FILE__, __LINE__);
    std::string message = "Can't open ";
    message += m_Filename;
    message += '\n';
    exception.SetDescription(message.c_str());
    throw exception;
    }

  // Default stream parser just reads a block at a time.
  std::streamsize filesize =
    itksys::SystemTools::FileLength(m_Filename.c_str());

  char *buffer = new char [filesize];

  inputstream.read(buffer,filesize);

  if(static_cast<std::streamsize>(inputstream.gcount()) != filesize)
    {
    ExceptionObject exception(__FILE__, __LINE__);
    exception.SetDescription("File Read Error");
    throw exception;
    }
  bool result = XML_Parse(Parser,buffer,inputstream.gcount(),false);
  delete [] buffer;
  if(!result)
    {
    ExceptionObject exception(__FILE__, __LINE__);

    std::string message(XML_ErrorString(XML_GetErrorCode(Parser)));
    message += " ";
    message += m_Filename;
    message += '\n';
    exception.SetDescription(message.c_str());
    throw exception;

    }
  return;
}

void
XMLReaderBase::
GenerateOutputInformation()
{
  this->parse();
}

}

#endif
<|endoftext|>


<commit_before>/*
* Copyright 2008, 2010 Free Software Foundation, Inc.
*
*
* This software is distributed under the terms of the GNU Affero Public License.
* See the COPYING file in the main directory for details.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.

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

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

	You should have received a copy of the GNU Affero General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

#include <unistd.h>
#include <fcntl.h>
#include <cstdio>
#include <sys/select.h>

#include "Threads.h"
#include "Sockets.h"
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

#include <string.h>
#include <stdlib.h>

//mutex for protecting non-thread safe gethostbyname
static Mutex sgGethostbynameLock;

bool resolveAddress(struct sockaddr_in *address, const char *hostAndPort)
{
	assert(address);
	assert(hostAndPort);
	char *copy = strdup(hostAndPort);
	char *colon = strchr(copy,':');
	if (!colon) return false;
	*colon = '\0';
	char *host = copy;
	unsigned port = strtol(colon+1,NULL,10);
	bool retVal = resolveAddress(address,host,port);
	free(copy);
	return retVal;
}

bool resolveAddress(struct sockaddr_in *address, const char *host, unsigned short port)
{
	assert(address);
	assert(host);
	//gethostbyname not thread safe
	ScopedLock lock(sgGethostbynameLock);
	// FIXME -- Need to ignore leading/trailing spaces in hostname.
	struct hostent *hp = gethostbyname(host);
	if (hp==NULL) {
		CERR("WARNING -- gethostbyname() failed for " << host << ", " << hstrerror(h_errno));
		return false;
	}
	address->sin_family = AF_INET;
	bcopy(hp->h_addr, &(address->sin_addr), hp->h_length);
	address->sin_port = htons(port);
	return true;
}

DatagramSocket::DatagramSocket()
{
	bzero(mDestination,sizeof(mDestination));
}

void DatagramSocket::nonblocking()
{
	fcntl(mSocketFD,F_SETFL,O_NONBLOCK);
}

void DatagramSocket::blocking()
{
	fcntl(mSocketFD,F_SETFL,0);
}

void DatagramSocket::close()
{
	::close(mSocketFD);
}

DatagramSocket::~DatagramSocket()
{
	close();
}

int DatagramSocket::write( const char * message, size_t length )
{
	assert(length<=MAX_UDP_LENGTH);
	int retVal = sendto(mSocketFD, message, length, 0,
		(struct sockaddr *)mDestination, addressSize());
	if (retVal == -1 ) perror("DatagramSocket::write() failed");
	return retVal;
}

int DatagramSocket::writeBack( const char * message, size_t length )
{
	assert(length<=MAX_UDP_LENGTH);
	int retVal = sendto(mSocketFD, message, length, 0,
		(struct sockaddr *)mSource, addressSize());
	if (retVal == -1 ) perror("DatagramSocket::write() failed");
	return retVal;
}

int DatagramSocket::write( const char * message)
{
	size_t length=strlen(message)+1;
	return write(message,length);
}

int DatagramSocket::writeBack( const char * message)
{
	size_t length=strlen(message)+1;
	return writeBack(message,length);
}

int DatagramSocket::send(const struct sockaddr* dest, const char * message, size_t length )
{
	assert(length<=MAX_UDP_LENGTH);
	int retVal = sendto(mSocketFD, message, length, 0, dest, addressSize());
	if (retVal == -1 ) perror("DatagramSocket::send() failed");
	return retVal;
}

int DatagramSocket::send(const struct sockaddr* dest, const char * message)
{
	size_t length=strlen(message)+1;
	return send(dest,message,length);
}

int DatagramSocket::read(char* buffer)
{
	socklen_t temp_len = sizeof(mSource);
	int length = recvfrom(mSocketFD, (void*)buffer, MAX_UDP_LENGTH, 0,
	    (struct sockaddr*)&mSource,&temp_len);
	if ((length==-1) && (errno!=EAGAIN)) {
		perror("DatagramSocket::read() failed");
		throw SocketError();
	}
	return length;
}

int DatagramSocket::read(char* buffer, unsigned timeout)
{
	fd_set fds;
	FD_ZERO(&fds);
	struct timeval tv;
	tv.tv_sec = timeout/1000;
	tv.tv_usec = (timeout%1000)*1000;
	int sel = select(mSocketFD+1,&fds,NULL,NULL,&tv);
	if (sel<0) {
		perror("DatagramSocket::read() select() failed");
		throw SocketError();
	}
	if (sel==0) return -1;
	return read(buffer);
}

UDPSocket::UDPSocket(unsigned short wSrcPort)
	:DatagramSocket()
{
	open(wSrcPort);
}

UDPSocket::UDPSocket(unsigned short wSrcPort,
          	 const char * wDestIP, unsigned short wDestPort )
	:DatagramSocket()
{
	open(wSrcPort);
	destination(wDestPort, wDestIP);
}

void UDPSocket::destination( unsigned short wDestPort, const char * wDestIP )
{
	resolveAddress((sockaddr_in*)mDestination, wDestIP, wDestPort );
}

void UDPSocket::open(unsigned short localPort)
{
	// create
	mSocketFD = socket(AF_INET,SOCK_DGRAM,0);
	if (mSocketFD<0) {
		perror("socket() failed");
		throw SocketError();
	}

	// bind
	struct sockaddr_in address;
	size_t length = sizeof(address);
	bzero(&address,length);
	address.sin_family = AF_INET;
	address.sin_addr.s_addr = INADDR_ANY;
	address.sin_port = htons(localPort);
	if (bind(mSocketFD,(struct sockaddr*)&address,length)<0) {
		perror("bind() failed");
		throw SocketError();
	}
}

unsigned short UDPSocket::port() const
{
	struct sockaddr_in name;
	socklen_t nameSize = sizeof(name);
	int retVal = getsockname(mSocketFD, (struct sockaddr*)&name, &nameSize);
	if (retVal==-1) throw SocketError();
	return ntohs(name.sin_port);
}

UDDSocket::UDDSocket(const char* localPath, const char* remotePath)
	:DatagramSocket()
{
	if (localPath!=NULL) open(localPath);
	if (remotePath!=NULL) destination(remotePath);
}

void UDDSocket::open(const char* localPath)
{
	// create
	mSocketFD = socket(AF_UNIX,SOCK_DGRAM,0);
	if (mSocketFD<0) {
		perror("socket() failed");
		throw SocketError();
	}

	// bind
	struct sockaddr_un address;
	size_t length = sizeof(address);
	bzero(&address,length);
	address.sun_family = AF_UNIX;
	strcpy(address.sun_path,localPath);
	unlink(localPath);
	if (bind(mSocketFD,(struct sockaddr*)&address,length)<0) {
		perror("bind() failed");
		throw SocketError();
	}
}

void UDDSocket::destination(const char* remotePath)
{
	struct sockaddr_un* unAddr = (struct sockaddr_un*)mDestination;
	strcpy(unAddr->sun_path,remotePath);
}

// vim:ts=4:sw=4
<commit_msg>r4425 in private: Double check the FD set to be sure that the correct FD was really touched.<commit_after>/*
* Copyright 2008, 2010 Free Software Foundation, Inc.
*
*
* This software is distributed under the terms of the GNU Affero Public License.
* See the COPYING file in the main directory for details.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.

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

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

	You should have received a copy of the GNU Affero General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

#include <unistd.h>
#include <fcntl.h>
#include <cstdio>
#include <sys/select.h>

#include "Threads.h"
#include "Sockets.h"
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

#include <string.h>
#include <stdlib.h>

//mutex for protecting non-thread safe gethostbyname
static Mutex sgGethostbynameLock;

bool resolveAddress(struct sockaddr_in *address, const char *hostAndPort)
{
	assert(address);
	assert(hostAndPort);
	char *copy = strdup(hostAndPort);
	char *colon = strchr(copy,':');
	if (!colon) return false;
	*colon = '\0';
	char *host = copy;
	unsigned port = strtol(colon+1,NULL,10);
	bool retVal = resolveAddress(address,host,port);
	free(copy);
	return retVal;
}

bool resolveAddress(struct sockaddr_in *address, const char *host, unsigned short port)
{
	assert(address);
	assert(host);
	//gethostbyname not thread safe
	ScopedLock lock(sgGethostbynameLock);
	// FIXME -- Need to ignore leading/trailing spaces in hostname.
	struct hostent *hp = gethostbyname(host);
	if (hp==NULL) {
		CERR("WARNING -- gethostbyname() failed for " << host << ", " << hstrerror(h_errno));
		return false;
	}
	address->sin_family = AF_INET;
	bcopy(hp->h_addr, &(address->sin_addr), hp->h_length);
	address->sin_port = htons(port);
	return true;
}

DatagramSocket::DatagramSocket()
{
	bzero(mDestination,sizeof(mDestination));
}

void DatagramSocket::nonblocking()
{
	fcntl(mSocketFD,F_SETFL,O_NONBLOCK);
}

void DatagramSocket::blocking()
{
	fcntl(mSocketFD,F_SETFL,0);
}

void DatagramSocket::close()
{
	::close(mSocketFD);
}

DatagramSocket::~DatagramSocket()
{
	close();
}

int DatagramSocket::write( const char * message, size_t length )
{
	assert(length<=MAX_UDP_LENGTH);
	int retVal = sendto(mSocketFD, message, length, 0,
		(struct sockaddr *)mDestination, addressSize());
	if (retVal == -1 ) perror("DatagramSocket::write() failed");
	return retVal;
}

int DatagramSocket::writeBack( const char * message, size_t length )
{
	assert(length<=MAX_UDP_LENGTH);
	int retVal = sendto(mSocketFD, message, length, 0,
		(struct sockaddr *)mSource, addressSize());
	if (retVal == -1 ) perror("DatagramSocket::write() failed");
	return retVal;
}

int DatagramSocket::write( const char * message)
{
	size_t length=strlen(message)+1;
	return write(message,length);
}

int DatagramSocket::writeBack( const char * message)
{
	size_t length=strlen(message)+1;
	return writeBack(message,length);
}

int DatagramSocket::send(const struct sockaddr* dest, const char * message, size_t length )
{
	assert(length<=MAX_UDP_LENGTH);
	int retVal = sendto(mSocketFD, message, length, 0, dest, addressSize());
	if (retVal == -1 ) perror("DatagramSocket::send() failed");
	return retVal;
}

int DatagramSocket::send(const struct sockaddr* dest, const char * message)
{
	size_t length=strlen(message)+1;
	return send(dest,message,length);
}

int DatagramSocket::read(char* buffer)
{
	socklen_t temp_len = sizeof(mSource);
	int length = recvfrom(mSocketFD, (void*)buffer, MAX_UDP_LENGTH, 0,
	    (struct sockaddr*)&mSource,&temp_len);
	if ((length==-1) && (errno!=EAGAIN)) {
		perror("DatagramSocket::read() failed");
		throw SocketError();
	}
	return length;
}

int DatagramSocket::read(char* buffer, unsigned timeout)
{
	fd_set fds;
	FD_ZERO(&fds);
	struct timeval tv;
	tv.tv_sec = timeout/1000;
	tv.tv_usec = (timeout%1000)*1000;
	int sel = select(mSocketFD+1,&fds,NULL,NULL,&tv);
	if (sel<0) {
		perror("DatagramSocket::read() select() failed");
		throw SocketError();
	}
	if (sel==0) return -1;
	if (FD_ISSET(mSocketFD,&fds)) return read(buffer);
	return -1;
}

UDPSocket::UDPSocket(unsigned short wSrcPort)
	:DatagramSocket()
{
	open(wSrcPort);
}

UDPSocket::UDPSocket(unsigned short wSrcPort,
          	 const char * wDestIP, unsigned short wDestPort )
	:DatagramSocket()
{
	open(wSrcPort);
	destination(wDestPort, wDestIP);
}

void UDPSocket::destination( unsigned short wDestPort, const char * wDestIP )
{
	resolveAddress((sockaddr_in*)mDestination, wDestIP, wDestPort );
}

void UDPSocket::open(unsigned short localPort)
{
	// create
	mSocketFD = socket(AF_INET,SOCK_DGRAM,0);
	if (mSocketFD<0) {
		perror("socket() failed");
		throw SocketError();
	}

	// bind
	struct sockaddr_in address;
	size_t length = sizeof(address);
	bzero(&address,length);
	address.sin_family = AF_INET;
	address.sin_addr.s_addr = INADDR_ANY;
	address.sin_port = htons(localPort);
	if (bind(mSocketFD,(struct sockaddr*)&address,length)<0) {
		perror("bind() failed");
		throw SocketError();
	}
}

unsigned short UDPSocket::port() const
{
	struct sockaddr_in name;
	socklen_t nameSize = sizeof(name);
	int retVal = getsockname(mSocketFD, (struct sockaddr*)&name, &nameSize);
	if (retVal==-1) throw SocketError();
	return ntohs(name.sin_port);
}

UDDSocket::UDDSocket(const char* localPath, const char* remotePath)
	:DatagramSocket()
{
	if (localPath!=NULL) open(localPath);
	if (remotePath!=NULL) destination(remotePath);
}

void UDDSocket::open(const char* localPath)
{
	// create
	mSocketFD = socket(AF_UNIX,SOCK_DGRAM,0);
	if (mSocketFD<0) {
		perror("socket() failed");
		throw SocketError();
	}

	// bind
	struct sockaddr_un address;
	size_t length = sizeof(address);
	bzero(&address,length);
	address.sun_family = AF_UNIX;
	strcpy(address.sun_path,localPath);
	unlink(localPath);
	if (bind(mSocketFD,(struct sockaddr*)&address,length)<0) {
		perror("bind() failed");
		throw SocketError();
	}
}

void UDDSocket::destination(const char* remotePath)
{
	struct sockaddr_un* unAddr = (struct sockaddr_un*)mDestination;
	strcpy(unAddr->sun_path,remotePath);
}

// vim:ts=4:sw=4
<|endoftext|>


<commit_before>/*
	Conrad 'Condzi' Kubacki 2017
	https://github.com/condzi
*/

#pragma once

#include <algorithm>
#include <cinttypes>
#include <memory>
#include <vector>

namespace con
{
	using messageID_t = int8_t;

	namespace internal
	{
		struct messageInterface_t
		{
			messageID_t id = 0;
			virtual ~messageInterface_t() {}
		};
	}

	/*
	===============================================================================
	Created by: Condzi
		Non-inheritable struct that contains message id and data of type T.

	===============================================================================
	*/
	template <typename T>
	struct message_t final :
		internal::messageInterface_t
	{
		T data;

		message_t( messageID_t _id, T _data ) :
			id( _id ), data( std::move( _data ) )
		{}
	};

	/*
	===============================================================================
	Created by: Condzi
		Contains messages. GetMessage return temporary reference - it'll be invalid
		at next update, so don't store it - copy it's message_t::data.

	===============================================================================
	*/
	class Messenger final
	{
	public:
		template <typename T>
		void AddMessage( const messageID_t id, const T& data )
		{
			this->messages.emplace_back( std::make_unique<message_t<T>>( id, data ) );
		}
		template <typename T>
		message_t<T>& GetMessage( const messageID_t id )
		{
			auto result = this->findMessage( id );
			if ( result != this->messages.end() )
				return static_cast<message_t<T>&>( ( *result ).get() );
		}
		void ClearMessages()
		{
			this->messages.clear();
		}

	private:
		std::vector<std::unique_ptr<internal::messageInterface_t>> messages;

		auto findMessage( const messageID_t id ) const
		{
			return std::find_if( this->messages.begin(), this->messages.end(),
				[id]( auto& ptr )
			{
				return ptr->id == id;
			} );
		}
	};
}<commit_msg>add unique message id<commit_after>/*
	Conrad 'Condzi' Kubacki 2017
	https://github.com/condzi
*/

#pragma once

#include <algorithm>
#include <cinttypes>
#include <memory>
#include <vector>

namespace con
{
	using messageID_t = int8_t;

	namespace internal
	{
		struct messageInterface_t
		{
			messageID_t id = 0;
			const size_t uniqueID;
			virtual ~messageInterface_t() {}
		};
	}

	/*
	===============================================================================
	Created by: Condzi
		Non-inheritable struct that contains message id and data of type T. It
		also contains constant uniqueID to distinguish messages (unique for current
		frame).

	===============================================================================
	*/
	template <typename T>
	struct message_t final :
		internal::messageInterface_t
	{
		T data;

		message_t( messageID_t _id, T _data, size_t _uniqueID ) :
			id( _id ), data( std::move( _data ) ),
			uniqueID( std::move( _uniqueID ) )
		{}
	};

	/*
	===============================================================================
	Created by: Condzi
		Contains messages. GetMessage return temporary reference - it'll be invalid
		at next update, so don't store it - copy it's message_t::data.

	===============================================================================
	*/
	class Messenger final
	{
	public:
		template <typename T>
		void AddMessage( const messageID_t id, const T& data )
		{
			this->messages.emplace_back( std::make_unique<message_t<T>>( id, data, this->messages.size() ) );
		}
		template <typename T>
		message_t<T>& GetUniqueMessage( const messageID_t id )
		{
			auto result = this->findMessage( id );
			if ( result != this->messages.end() )
				return static_cast<message_t<T>&>( ( *result ).get() );
		}
		template <typename T>
		std::vector<message_t<T>*> GetAllMessages( const messageID_t id )
		{
			std::vector<message_t<T>*> vec;
			vec.reserve( this->messages.size() );

			for ( auto& message : this->messages )
				if ( message->id == id )
					vec.push_back( static_cast<message_t<T>*>( ( *result ).get() ) );

			return vec;
		}

		void ClearMessages()
		{
			this->messages.clear();
		}

	private:
		std::vector<std::unique_ptr<internal::messageInterface_t>> messages;

		auto findMessage( const messageID_t id ) const
		{
			return std::find_if( this->messages.begin(), this->messages.end(),
				[id]( auto& ptr )
			{
				return ptr->id == id;
			} );
		}
	};
}<|endoftext|>


<commit_before>#include "OJGL.h"
#define STB_IMAGE_IMPLEMENTATION
#include "EmbeddedResources.h"
#include "thirdparty\stb_image.h"
#include "utility\ShaderReader.h"
#include <fstream>
#include <functional>
#include <iostream>
#include <memory>
#include <set>
#include <sstream>
#include <streambuf>
#include <string>
#include <thread>
#include <unordered_map>

using namespace ojgl;

void buildSceneGraph(GLState& glState, int x, int y)
{
    glState.clearScenes();

    auto pre = Buffer::construct(1024, 768, "main", "demo.vs", "demo.fs");
    auto post = Buffer::construct(1024, 768, "post", "post.vs", "post.fs");

    auto DOFScene = Buffer::construct(1024, 768, "DOFScene", "demo.vs", "dofScene.fs");
    auto DOFBlur1 = Buffer::construct(1024, 768, "DOFBlur1", "demo.vs", "dofBlur1.fs", DOFScene);
    auto DOFBlur2 = Buffer::construct(1024, 768, "DOFBlur2", "demo.vs", "dofBlur2.fs", DOFBlur1);
    auto DOFFinal = Buffer::construct(1024, 768, "DOFFinal", "demo.vs", "dofFinal.fs", DOFScene, DOFBlur2, DOFBlur1);

    auto tunnel = Buffer::construct(1024, 768, "tunnel", "demo.vs", "tunnelScene.fs");

    auto base = Buffer::construct(1024, 768, "base", "demo.vs", "demo.fs");

    auto intro = Buffer::construct(x, y, "intro", "demo.vs", "introScene.fs");

    auto grave = Buffer::construct(x, y, "grave", "demo.vs", "graveScene.fs");
    auto graveFxaa = Buffer::construct(x, y, "fxaa", "fxaa.vs", "fxaa.fs", grave);
    auto gravePost = Buffer::construct(x, y, "gravePost", "demo.vs", "graveScenePost.fs", graveFxaa);

    auto room = Buffer::construct(x, y, "room", "demo.vs", "roomScene.fs");
    auto roomFxaa = Buffer::construct(x, y, "fxaa", "fxaa.vs", "fxaa.fs", room);
    auto roomPost = Buffer::construct(x, y, "roomPost", "demo.vs", "roomScenePost.fs", roomFxaa);

    glState.addScene("introScene", intro, Duration::milliseconds(7000));
    glState.addScene("graveScene", gravePost, Duration::milliseconds(3000000));
    glState.addScene("roomScene", roomPost, Duration::milliseconds(3000000));

    glState.addScene("baseScene", base, Duration::milliseconds(3000000));
    glState.addScene("DOFScene", DOFFinal, Duration::milliseconds(30000));
    glState.addScene("tunnelScene", tunnel, Duration::milliseconds(30000));
    glState.addScene("imageScene", pre, Duration::milliseconds(30000));
}

std::tuple<int, int, int, std::unique_ptr<unsigned char, decltype(&stbi_image_free)>> readTexture(const std::string& filepath)
{
    int width = 0, height = 0, channels = 0;
    unsigned char* data = stbi_load(filepath.c_str(), &width, &height, &channels, 0);
    std::unique_ptr<unsigned char, decltype(&stbi_image_free)> dataptr(data, stbi_image_free);
    return std::make_tuple(width, height, channels, std::move(dataptr));
}

int main()
{
    int x = 1920 / 2;
    int y = 1080 / 2;
    ShaderReader::setBasePath("examples/shaders/");
    ShaderReader::preLoad("demo.vs", resources::vertex::demo);
    ShaderReader::preLoad("post.vs", resources::vertex::post);
    ShaderReader::preLoad("post.fs", resources::fragment::post);
    ShaderReader::preLoad("demo.fs", resources::fragment::demo);
    ShaderReader::preLoad("dofScene.fs", resources::fragment::dofScene);
    ShaderReader::preLoad("dofBlur1.fs", resources::fragment::dofBlur1);
    ShaderReader::preLoad("dofBlur2.fs", resources::fragment::dofBlur2);
    ShaderReader::preLoad("dofFinal.fs", resources::fragment::dofFinal);
    ShaderReader::preLoad("tunnel.fs", resources::fragment::tunnel);

    ShaderReader::preLoad("introScene.fs", resources::fragment::intro);
    ShaderReader::preLoad("graveScene.fs", resources::fragment::grave);
    ShaderReader::preLoad("fxaa.fs", resources::fragment::fxaa);
    ShaderReader::preLoad("fxaa.vs", resources::vertex::fxaa);
    ShaderReader::preLoad("graveScenePost.fs", resources::fragment::gravePost);
    ShaderReader::preLoad("roomScene.fs", resources::fragment::room);
    ShaderReader::preLoad("roomScenePost.fs", resources::fragment::roomPost);

    const auto desiredFrameTime = Duration::milliseconds(17);

    Window window(x, y, false);
    GLState glState;

    Music music(resources::songs::song);
    music.play();

    buildSceneGraph(glState, x, y);

    auto[width, height, channels, data] = readTexture("examples/textures/image.png");
    auto texture = Texture::construct(width, height, channels, data.get());

    glState["imageScene"]["main"] << Uniform1t("image", texture);
    glState.setStartTime(Timepoint::now());

    auto previousPrintTime = Timepoint::now();
    while (true) {
        Timer timer;
        timer.start();

        window.getMessages();

        for (auto key : window.getPressedKeys()) {
            if (key == Window::KEY_ESCAPE) {
                return 0;
            }
#ifdef _DEBUG
            bool timeChanged(false);
            LOG_INFO("key: " << key);
            if (key == Window::KEY_LEFT) {
                glState.changeTime(Duration::milliseconds(-1000));
                timeChanged = true;
            }
            if (key == Window::KEY_RIGHT) {
                glState.changeTime(Duration::milliseconds(1000));
                timeChanged = true;
            }
            if (key == Window::KEY_SPACE) {
                glState.togglePause();
                if (glState.isPaused()) {
                    music.stop();
                }
                timeChanged = true;
            }

            if (key == Window::KEY_R) {
                glState.restart();
                timeChanged = true;
            }
            if (key == Window::KEY_UP) {
                glState.nextScene();
                timeChanged = true;
            }
            if (key == Window::KEY_DOWN) {
                glState.previousScene();
                timeChanged = true;
            }
            if (!glState.isPaused() && timeChanged) {
                music.setTime(glState.elapsedTime());
            }
#endif
        }

        auto iGlobalTime = glState.relativeSceneTime();

        /* glState["baseScene"]["base"] << Uniform1f("iGlobalTime", iGlobalTime.toMilliseconds() / 1000.f);
        glState["tunnelScene"]["tunnel"] << Uniform1f("iGlobalTime", iGlobalTime.toMilliseconds() / 1000.f)
                                         << Uniform1f("CHANNEL_12_TOTAL", static_cast<GLfloat>(music.syncChannels()[12].getTotalHitsPerNote(0)))
                                         << Uniform1f("CHANNEL_13_TOTAL", static_cast<GLfloat>(music.syncChannels()[13].getTotalHitsPerNote(0)));

        for (auto& kv : music.syncChannels()) {
            const auto& sc = kv.second;
            std::vector<GLfloat> valuesSince;
            std::vector<GLfloat> valuesTo;

            for (int i = 0; i < sc.numNotes; i++) {
                valuesSince.push_back(static_cast<GLfloat>(sc.getTimeSinceLast(i).toMilliseconds()));
                valuesTo.push_back(static_cast<GLfloat>(sc.getTimeToNext(i).toMilliseconds()));
            }

            glState["baseScene"]["base"] << Uniform1fv("CHANNEL_" + std::to_string(sc.channel) + "_TIME_SINCE", valuesSince)
                                         << Uniform1fv("CHANNEL_" + std::to_string(sc.channel) + "_TIME_TO", valuesTo);
        }*/

        glState << Uniform1f("iGlobalTime", iGlobalTime.toSeconds());
        glState << Uniform1f("resolutionWidth", static_cast<float>(x));
        glState << Uniform1f("resolutionHeight", static_cast<float>(y));

        glState["graveScene"]["gravePost"] << Uniform1f("CHANNEL_4_TO", min(music.syncChannels()[4].getTimeToNext(0).toSeconds(), music.syncChannels()[4].getTimeToNext(1).toSeconds()));
        glState["graveScene"]["gravePost"] << Uniform1f("CHANNEL_4_TOTAL", static_cast<float>(music.syncChannels()[4].getTotalHitsPerNote(0) + music.syncChannels()[4].getTotalHitsPerNote(1)));
        glState["graveScene"]["gravePost"] << Uniform1f("CHANNEL_11_SINCE", music.syncChannels()[11].getTimeSinceLast(0).toSeconds());
        glState["graveScene"]["grave"] << Uniform1f("CHANNEL_11_SINCE", music.syncChannels()[11].getTimeSinceLast(0).toSeconds());
        glState["graveScene"]["grave"] << Uniform1f("CHANNEL_11_TOTAL", static_cast<float>(music.syncChannels()[11].getTotalHits()));
        std::vector<float> since;
        since.push_back(music.syncChannels()[4].getTimeSinceLast(0).toSeconds());
        since.push_back(music.syncChannels()[4].getTimeSinceLast(1).toSeconds());
        glState["graveScene"]["grave"] << Uniform1fv("CHANNEL_4_SINCE", since);

        glState.render();
        if (!glState.isPaused()) {
            music.updateSync();
        }
        timer.end();

        auto timeSinceLastPrint = Timepoint::now() - previousPrintTime;
        if (timeSinceLastPrint > Duration::seconds(2)) {
            LOG_INFO("Frame time: " << timer.currentTime());
            previousPrintTime = Timepoint::now();
        }
    }
    return 0;
}
<commit_msg>Main cleanup<commit_after>#include "OJGL.h"
#define STB_IMAGE_IMPLEMENTATION
#include "EmbeddedResources.h"
#include "thirdparty\stb_image.h"
#include "utility\ShaderReader.h"
#include <fstream>
#include <functional>
#include <iostream>
#include <memory>
#include <set>
#include <sstream>
#include <streambuf>
#include <string>
#include <thread>
#include <unordered_map>

using namespace ojgl;

void buildSceneGraph(GLState& glState, int x, int y)
{
    glState.clearScenes();

    auto pre = Buffer::construct(1024, 768, "main", "demo.vs", "demo.fs");
    auto post = Buffer::construct(1024, 768, "post", "post.vs", "post.fs");
    auto DOFScene = Buffer::construct(1024, 768, "DOFScene", "demo.vs", "dofScene.fs");
    auto DOFBlur1 = Buffer::construct(1024, 768, "DOFBlur1", "demo.vs", "dofBlur1.fs", DOFScene);
    auto DOFBlur2 = Buffer::construct(1024, 768, "DOFBlur2", "demo.vs", "dofBlur2.fs", DOFBlur1);
    auto DOFFinal = Buffer::construct(1024, 768, "DOFFinal", "demo.vs", "dofFinal.fs", DOFScene, DOFBlur2, DOFBlur1);
    auto tunnel = Buffer::construct(1024, 768, "tunnel", "demo.vs", "tunnelScene.fs");
    auto base = Buffer::construct(1024, 768, "base", "demo.vs", "demo.fs");
    auto intro = Buffer::construct(x, y, "intro", "demo.vs", "introScene.fs");
    auto grave = Buffer::construct(x, y, "grave", "demo.vs", "graveScene.fs");
    auto graveFxaa = Buffer::construct(x, y, "fxaa", "fxaa.vs", "fxaa.fs", grave);
    auto gravePost = Buffer::construct(x, y, "gravePost", "demo.vs", "graveScenePost.fs", graveFxaa);
    auto room = Buffer::construct(x, y, "room", "demo.vs", "roomScene.fs");
    auto roomFxaa = Buffer::construct(x, y, "fxaa", "fxaa.vs", "fxaa.fs", room);
    auto roomPost = Buffer::construct(x, y, "roomPost", "demo.vs", "roomScenePost.fs", roomFxaa);

    glState.addScene("introScene", intro, Duration::milliseconds(7000));
    glState.addScene("graveScene", gravePost, Duration::milliseconds(3000000));
    glState.addScene("roomScene", roomPost, Duration::milliseconds(3000000));
    glState.addScene("baseScene", base, Duration::milliseconds(3000000));
    glState.addScene("DOFScene", DOFFinal, Duration::milliseconds(30000));
    glState.addScene("tunnelScene", tunnel, Duration::milliseconds(30000));
    glState.addScene("imageScene", pre, Duration::milliseconds(30000));
}

std::tuple<int, int, int, std::unique_ptr<unsigned char, decltype(&stbi_image_free)>> readTexture(const std::string& filepath)
{
    int width = 0, height = 0, channels = 0;
    unsigned char* data = stbi_load(filepath.c_str(), &width, &height, &channels, 0);
    std::unique_ptr<unsigned char, decltype(&stbi_image_free)> dataptr(data, stbi_image_free);
    return std::make_tuple(width, height, channels, std::move(dataptr));
}

int main()
{
    int width = 1920 / 2;
    int height = 1080 / 2;
    ShaderReader::setBasePath("examples/shaders/");
    ShaderReader::preLoad("demo.vs", resources::vertex::demo);
    ShaderReader::preLoad("post.vs", resources::vertex::post);
    ShaderReader::preLoad("post.fs", resources::fragment::post);
    ShaderReader::preLoad("demo.fs", resources::fragment::demo);
    ShaderReader::preLoad("dofScene.fs", resources::fragment::dofScene);
    ShaderReader::preLoad("dofBlur1.fs", resources::fragment::dofBlur1);
    ShaderReader::preLoad("dofBlur2.fs", resources::fragment::dofBlur2);
    ShaderReader::preLoad("dofFinal.fs", resources::fragment::dofFinal);
    ShaderReader::preLoad("tunnel.fs", resources::fragment::tunnel);

    ShaderReader::preLoad("introScene.fs", resources::fragment::intro);
    ShaderReader::preLoad("graveScene.fs", resources::fragment::grave);
    ShaderReader::preLoad("fxaa.fs", resources::fragment::fxaa);
    ShaderReader::preLoad("fxaa.vs", resources::vertex::fxaa);
    ShaderReader::preLoad("graveScenePost.fs", resources::fragment::gravePost);
    ShaderReader::preLoad("roomScene.fs", resources::fragment::room);
    ShaderReader::preLoad("roomScenePost.fs", resources::fragment::roomPost);

    const auto desiredFrameTime = Duration::milliseconds(17);

    Window window(width, height, false);
    GLState glState;

    Music music(resources::songs::song);
    music.play();

    buildSceneGraph(glState, width, height);

    auto[textureWidth, textureHeight, channels, data] = readTexture("examples/textures/image.png");
    auto texture = Texture::construct(textureWidth, textureHeight, channels, data.get());

    glState["imageScene"]["main"] << Uniform1t("image", texture);
    glState.setStartTime(Timepoint::now());

    auto previousPrintTime = Timepoint::now();
    while (true) {
        Timer timer;
        timer.start();
        window.getMessages();

        for (auto key : window.getPressedKeys()) {
            LOG_INFO("Key pressed: " << key);
            bool timeChanged = false;

            switch (key) {
            case Window::KEY_ESCAPE:
                return 0;
#ifdef _DEBUG
            case Window::KEY_LEFT:
                glState.changeTime(Duration::milliseconds(-1000));
                timeChanged = true;
                break;

            case Window::KEY_RIGHT:
                glState.changeTime(Duration::milliseconds(1000));
                timeChanged = true;
                break;

            case Window::KEY_SPACE:
                glState.togglePause();
                if (glState.isPaused())
                    music.stop();
                timeChanged = true;
                break;

            case Window::KEY_R:
                glState.restart();
                timeChanged = true;
                break;

            case Window::KEY_UP:
                glState.nextScene();
                timeChanged = true;
                break;

            case Window::KEY_DOWN:
                glState.previousScene();
                timeChanged = true;
                break;
            }

            if (!glState.isPaused() && timeChanged)
                music.setTime(glState.elapsedTime());
#endif
        }

        glState << Uniform1f("iGlobalTime", glState.relativeSceneTime().toSeconds());
        glState << Uniform1f("resolutionWidth", static_cast<float>(width));
        glState << Uniform1f("resolutionHeight", static_cast<float>(height));

        glState["graveScene"]["gravePost"] << Uniform1f("CHANNEL_4_TO", min(music.syncChannels()[4].getTimeToNext(0).toSeconds(), music.syncChannels()[4].getTimeToNext(1).toSeconds()));
        glState["graveScene"]["gravePost"] << Uniform1f("CHANNEL_4_TOTAL", static_cast<float>(music.syncChannels()[4].getTotalHitsPerNote(0) + music.syncChannels()[4].getTotalHitsPerNote(1)));
        glState["graveScene"]["gravePost"] << Uniform1f("CHANNEL_11_SINCE", music.syncChannels()[11].getTimeSinceLast(0).toSeconds());
        glState["graveScene"]["grave"] << Uniform1f("CHANNEL_11_SINCE", music.syncChannels()[11].getTimeSinceLast(0).toSeconds());
        glState["graveScene"]["grave"] << Uniform1f("CHANNEL_11_TOTAL", static_cast<float>(music.syncChannels()[11].getTotalHits()));
        glState["graveScene"]["grave"] << Uniform1fv("CHANNEL_4_SINCE", { music.syncChannels()[4].getTimeSinceLast(0).toSeconds(), music.syncChannels()[4].getTimeSinceLast(1).toSeconds() });

        glState.render();

        if (!glState.isPaused())
            music.updateSync();

        timer.end();

        auto timeSinceLastPrint = Timepoint::now() - previousPrintTime;
        if (timeSinceLastPrint > Duration::seconds(2)) {
            LOG_INFO("Frame time: " << timer.currentTime());
            previousPrintTime = Timepoint::now();
        }
    }
    return 0;
}
<|endoftext|>


<commit_before>#include <thread>

void ChartTest();

int main()
{
	std::thread t(ChartTest);
	t.join();

	return 0;
}

void ChartTest()
{

}<commit_msg>Implement Demo (Bar Chart)<commit_after>#include <thread>

#include "Chart.h"
#include "Bar.h"

void DrawOnScreen(CppChart::Chart*);
void ChartTest();

int main()
{
	std::thread t(ChartTest);
	t.join();

	return 0;
}

void DrawOnScreen(CppChart::Chart* graph)
{
	sf::ContextSettings settings;
	settings.antialiasingLevel = 8;
	sf::RenderWindow window(sf::VideoMode(800, 600), "Graph Plotting", sf::Style::Default, settings);

	graph->m_chartOffsets.x = 2;
	graph->m_chartOffsets.y = 2;
	graph->SetDimensions(700, 500);
	graph->m_screenMargins.top = 25;
	graph->m_screenMargins.bottom = 25;
	graph->m_screenMargins.left = 25;
	graph->m_screenMargins.right = 25;
	graph->SetDefaultLegendMetrics();

	window.clear(sf::Color(255, 255, 255));
	graph->DrawToScreen(&window);
	window.display();

	while (window.isOpen())
	{
		sf::Event event;

		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
			{
				window.close();
			}
			else if (event.type == sf::Event::KeyPressed)
			{
				if (event.key.code == sf::Keyboard::Escape ||
					event.key.code == sf::Keyboard::Return)
				{
					window.close();
				}
			}
		}

		std::this_thread::sleep_for(std::chrono::milliseconds(50));
	}
}

void ChartTest()
{
	char option;
	CppChart::Chart* graph = nullptr;

	do
	{
		std::cout << "Which graph do you want to see ?\n";
		std::cout << "1. Bar Graph\n";
		std::cout << "Enter your option [1-1] : ";
		std::cin >> option;

		switch (option)
		{
		case '1':
			graph = new CppChart::BarChart(std::vector<CppChart::DataElement>
			{
				CppChart::DataElement{ "AAA", sf::Color(255, 105, 97), 23 },
				CppChart::DataElement{ "BBB", sf::Color(255, 179, 71), 14 },
				CppChart::DataElement{ "CCC", sf::Color(119, 190, 119), 33 },
				CppChart::DataElement{ "DDD", sf::Color(150, 111, 214), 12 }
			}, false);
			break;

		default:
			return;
		}

		DrawOnScreen(graph);
		std::cin.get();
		std::cin.get();

		delete graph;
		graph = nullptr;

		// Clear Screen
		for (int i = 0; i < 1000; ++i)
		{
			std::cout << "\n";
		}
	} while (true);
}<|endoftext|>