<commit_before>#include "stdafx.h"
#include "ipc.h"
#include <afxwin.h>

namespace myodd {
namespace os {
class IpcWnd : public CWnd
{
public:
  IpcWnd(const wchar_t* pszClassName )
  {
    auto hInstance = GetModuleHandle( nullptr );
    WNDCLASS wndcls;
    if (!GetClassInfo(hInstance, pszClassName, &wndcls))
    {
      wndcls.style = 0;
      wndcls.lpfnWndProc = IpcWnd::WindowProc;
      wndcls.cbClsExtra = wndcls.cbWndExtra = 0;
      wndcls.hInstance = hInstance;
      wndcls.hIcon = nullptr;
      wndcls.hCursor = LoadCursor(nullptr, IDC_ARROW);
      wndcls.hbrBackground = GetSysColorBrush(COLOR_WINDOW);
      wndcls.lpszMenuName = nullptr;
      wndcls.lpszClassName = pszClassName;
      if (!RegisterClass(&wndcls))
      {
        TRACE(traceAppMsg, 0, _T("Can't register window class named %Ts\n"), wndcls.lpszClassName);
      }
    }

    // one way or another the class was created.
    // so we can create our listener accordingly.
    if (!this->CWnd::CreateEx(0, pszClassName, L"", 0, 0, 0, 0, 0, HWND_MESSAGE, nullptr))
    {
      TRACE(traceAppMsg, 0, _T("Can't create window class named %Ts\n"), wndcls.lpszClassName);
    }
  }

  static LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
  {
    return ::DefWindowProc(hwnd, uMsg, wParam, lParam);
  }
};

Ipc::Ipc(const wchar_t* serverName) : _pServer( nullptr )
{
  // create the server
  CreateServer(serverName);
}

Ipc::~Ipc()
{
  // remove the server.
  delete static_cast<IpcWnd*>(_pServer);
}

/**
 * Create the server window that will be listening to messages.
 */
void Ipc::CreateServer(const wchar_t* serverName)
{
  _pServer = new IpcWnd( serverName );
}

}
}
<commit_msg>Some code cleanup, throwing in case of errors.<commit_after>#include "stdafx.h"
#include "ipc.h"
#include <afxwin.h>

namespace myodd {
namespace os {
class IpcWnd : public CWnd
{
public:
  explicit IpcWnd(const wchar_t* pszClassName )
  {
    auto hInstance = GetModuleHandle( nullptr );
    WNDCLASS wndcls;
    if (GetClassInfo(hInstance, pszClassName, &wndcls))
    {
      throw "The server already exists.";
    }

    wndcls.style = 0;
    wndcls.lpfnWndProc = IpcWnd::WindowProc;
    wndcls.cbClsExtra = wndcls.cbWndExtra = 0;
    wndcls.hInstance = hInstance;
    wndcls.hIcon = nullptr;
    wndcls.hCursor = LoadCursor(nullptr, IDC_ARROW);
    wndcls.hbrBackground = GetSysColorBrush(COLOR_WINDOW);
    wndcls.lpszMenuName = nullptr;
    wndcls.lpszClassName = pszClassName;
    if (!RegisterClass(&wndcls))
    {
      throw "Can't register IPC window class.";
    }

    // one way or another the class was created.
    // so we can create our listener accordingly.
    if (!this->CWnd::CreateEx(0, pszClassName, L"", 0, 0, 0, 0, 0, HWND_MESSAGE, nullptr))
    {
      throw "Can't create IPC window.";
    }
  }

  static LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
  {
    return ::DefWindowProc(hwnd, uMsg, wParam, lParam);
  }
};

Ipc::Ipc(const wchar_t* serverName) : _pServer( nullptr )
{
  // create the server
  CreateServer(serverName);
}

Ipc::~Ipc()
{
  // remove the server.
  delete static_cast<IpcWnd*>(_pServer);
}

/**
 * Create the server window that will be listening to messages.
 * @param const wchar_t* serverName the server name we wish to use.
 * @return none
 */
void Ipc::CreateServer(const wchar_t* serverName)
{
  _pServer = new IpcWnd( serverName );
}

}
}
<|endoftext|>


<commit_before>// biopore_matrix.C --- Static vertical biopores with a capacity.
//
// Copyright 2008 Per Abrahamsen and KU.
//
// This file is part of Daisy.
//
// Daisy is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// Daisy 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 Public License for more details.
//
// You should have received a copy of the GNU Lesser Public License
// along with Daisy; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

#define BUILD_DLL

#include "biopore.h"
#include "imvec.h"
#include "block.h"
#include "vcheck.h"
#include "librarian.h"
#include "submodeler.h"
#include "geometry.h"
#include "soil.h"
#include "soil_water.h"
#include "secondary.h"
#include "volume_box.h"
#include "log.h"
#include "check.h"
#include <sstream>

// The 'matrix' model.

struct BioporeMatrix : public Biopore
{
  // Parameters.
  /* const */ std::vector<double> xplus; // [cm]
  const double diameter;        // [cm]
  const double R_primary;       // [h/cm]
  const double R_secondary;     // [h/cm]

  // State.
  std::vector<double> h_bottom; // [cm]
  std::auto_ptr<IMvec> solute;  // [g/cm^3]

  // Utilities.
  /* const */ double dy;                    // [cm]
  std::vector<size_t> column;
  std::vector<double> added_water; // [cm^3]
  std::vector<double> density_column; // [cm^-2]

  // Simulation.
  bool to_drain () const
  { return false; }
  double air_bottom (const size_t c) const // Lowest point with air [cm]
  {
    daisy_assert (c < column.size ());
    const size_t col = column[c];
    daisy_assert (col < h_bottom.size ());
    return height_end + h_bottom[col];
  }
  void add_water (size_t c, double amount /* [cm^3] */)
  {
    daisy_assert (c < column.size ());
    const size_t col = column[c];
    daisy_assert (col < added_water.size ());
    added_water[col] += amount;
  }
  void extract_water (const size_t c, const double volume /* [cm^3] */ ,
                      const double Theta /* [cm^3/cm^3] */,
                      const double dt /* [h] */,
                      std::vector<double>& S_drain /* [cm^3/cm^3/h] */,
                      std::vector<double>& S_matrix, Treelog&);
  void release_water (const Geometry& geo, const Soil& soil,
                      const SoilWater& soil_water,
                      const double dt /* [h] */,
                      std::vector<double>& S_matrix, Treelog&);
  void update_water ();
  void output (Log&) const;

  // Create and Destroy.
  bool initialize (const Geometry& geo, const Scope& scope, double,
                   Treelog& msg);
  bool check (const Geometry& geo, Treelog& msg) const
  { return check_base (geo, msg); }
  BioporeMatrix (Block& al);
};

void
BioporeMatrix::extract_water (const size_t c, const double volume /* [cm^3] */ ,
                              const double Theta /* [cm^3/cm^3] */,
                              const double dt /* [h] */,
                              std::vector<double>& /* [cm^3/cm^3/h] */,
                              std::vector<double>& S_matrix, Treelog& msg)
{
  std::ostringstream tmp;
  tmp << "Extracting " << Theta << " [] water over " << dt
      << " hours from cell " << c;
  msg.message (tmp.str ());

  daisy_assert (c < S_matrix.size ());
  S_matrix[c] += Theta / dt;
  daisy_assert (c < column.size ());
  const size_t col = column[c];
  daisy_assert (col < h_bottom.size ());
  added_water[col] += Theta * volume;
}

void
BioporeMatrix::release_water (const Geometry& geo, const Soil& soil,
                              const SoilWater& soil_water,
                              const double dt /* [h] */,
                              std::vector<double>& S_matrix, Treelog&)
{
  const double circumference = M_PI * diameter; // [cm]

  const size_t cell_size = geo.cell_size ();
  for (size_t c = 0; c < cell_size; c++)
    {
      const double dens = density (c); // [cm^-2]
      if (dens < 1e-42)
        // No biopores of this class in this cell.
        continue;

      const double cell_z = geo.cell_z (c); // [cm]
      if (cell_z > height_start || cell_z < height_end)
        // Outside interval.
        continue;

      const double h_matrix = soil_water.h (c); // [cm]
      const double h_biopore =  air_bottom (c) - cell_z; // [cm]
      if (h_biopore < h_matrix + 1e-5)
        // Pressure in biopore not significantly above pressure in matrix.
        continue;
      const double dh = h_biopore - h_matrix; // [cm]
      daisy_assert (dh > 0.0);

      // Find resistance.
      const Secondary& secondary = soil.secondary_domain (c);
      const bool use_primary = secondary.none ();
      const double R = use_primary ? R_primary : R_secondary; // [h]

      // Find sink
      const double wall_per_area = circumference * dens; // [cm^-1]

      const double S = dh * wall_per_area / R; // [h^-1]

      std::ostringstream tmp;
      tmp << "Releasing " << S * dt << " [] water over " << dt
          << " hours in cell " << c;

      S_matrix[c] -= S;
      const double volume = geo.cell_volume (c); // [cm^3]
      added_water[column[c]] -= S * volume * dt; // [cm^3]
    }
}

void
BioporeMatrix::update_water ()
{
  const size_t column_size = xplus.size ();
  daisy_assert (added_water.size () == xplus.size ());
  double xminus = 0.0;
  for (size_t i = 0; i < column_size; i++)
    {
      const double density = density_column[i]; // [cm^-2]
      const double radius = diameter * 0.5;     // [cm]
      const double area = M_PI * radius * radius;  // [cm^2]
      const double soil_fraction = density * area; // []
      const double water_volume = added_water[i];  // [cm^3]
      const double soil_volume = water_volume / soil_fraction; // [cm^3]
      const double dx = xplus[i] - xminus;                     // [cm]
      const double dz = soil_volume / (dx * dy);               // [cm]
      h_bottom[i] += dz;                                          // [cm]
      added_water[i] = 0.0;                                    // [cm^3]
      xminus = xplus[i];                                       // [cm]
    }
}

void
BioporeMatrix::output (Log& log) const
{
  output_variable (h_bottom, log);
  output_submodule (*solute, "solute", log);
}

bool
BioporeMatrix::initialize (const Geometry& geo, const Scope& scope, double,
                           Treelog& msg)
{
  bool ok = true;

  // base.
  if (!initialize_base (geo, scope, msg))
    ok = false;

  // xplus.
  if (xplus.size () == 0)
    geo.fill_xplus (xplus);
  const size_t column_size = xplus.size ();
  daisy_assert (column_size > 0);

  // h_bottom.
  if (h_bottom.size () == 0)
    h_bottom.insert (h_bottom.end (), column_size, 0.0);

  if (h_bottom.size () != column_size)
    {
      msg.error ("Number of elements in 'h_bottom' does not match 'xplus'");
      ok = false;
    }

  // dy.
  dy = geo.back () - geo.front ();

  // column.
  daisy_assert (column.size () == 0);
  const size_t cell_size = geo.cell_size ();
  for (size_t c = 0; c < cell_size; c++)
    {
      const double x = geo.cell_x (c);
      for (size_t i = 0; i < column_size; i++)
        if (x < xplus[i])
          {
            column.push_back (i);
            goto found;
          }
      column.push_back (0U);
      {
        std::ostringstream tmp;
        tmp << "cell[" << c << "].x = " << x << ", > xplus[" << column_size - 1
            << "] = " << xplus[column_size-1];
        msg.error (tmp.str ());
      }
      ok = false;
    found:
      ;
    }
  daisy_assert (column.size () == cell_size);

  // added_water.
  added_water.insert (added_water.end (), column_size, 0.0);
  daisy_assert (added_water.size () == column_size);

  // density_column.
  if (density_cell.size () != cell_size)
    return false;

  double xminus = 0;
  for (size_t i = 0; i < column_size; i++)
    {
      VolumeBox square ("square", height_end, height_start, xminus, xplus[i]);
      const double volume = square.volume ();
      daisy_assert (volume > 0.0);
      const double content = geo.total_soil (density_cell, square);
      static const double m2_per_cm2 = 0.01 * 0.01;
      const double density = m2_per_cm2 * content / volume;
      density_column.push_back (density);
      xminus = xplus[i];
    }

  return ok;
}
BioporeMatrix::BioporeMatrix (Block& al)
  : Biopore (al),
    xplus (al.check ("xplus")
           ? al.number_sequence ("xplus")
           : std::vector<double> ()),
    diameter (al.number ("diameter")),
    R_primary (al.number ("R_primary")),
    R_secondary (al.number ("R_secondary", R_primary)),
    h_bottom (al.check ("h_bottom")
              ? al.number_sequence ("h_bottom")
              : std::vector<double> ()),
    solute (al.check ("solute")
            ? new IMvec (al, "solute")
            : NULL)
{ }

static struct BioporeMatrixSyntax
{
  static Model& make (Block& al)
  { return *new BioporeMatrix (al); }

  BioporeMatrixSyntax ()
  {
    Syntax& syntax = *new Syntax ();
    AttributeList& alist = *new AttributeList ();
    alist.add ("description", "Biopores that ends in the matrix.");
    Biopore::load_base (syntax, alist);

    syntax.add ("xplus", "cm", Check::positive (),
                Syntax::OptionalConst, Syntax::Sequence,
		"Right side of each biopore interval.\n\
Water and chemical content is tracked individually for each interval.\n\
By default, use intervals as specified by the geometry.");
    syntax.add_check ("xplus", VCheck::increasing ());
    syntax.add ("diameter", "cm", Check::positive (),
                Syntax::Const, "Biopore diameter.");
    syntax.add ("R_primary", "h", Check::positive (), Syntax::Const, "\
Resistance for water moving from biopore through wall to primary domain.");
    syntax.add ("R_secondary", "h", Check::positive (),
                Syntax::OptionalConst, "\
Resistance for water moving from biopore through wall to secondary domain.\n\
If not specified, this will be identical to 'R_primary'.");
    syntax.add ("h_bottom", "cm", Syntax::OptionalState, Syntax::Sequence,
		"Pressure at the bottom of the biopores in each interval.");

    static const symbol C_unit ("g/cm^3");
    IMvec::add_syntax (syntax, alist, Syntax::OptionalState, "solute", C_unit,
                       "Chemical concentration in biopore intervals.");

    Librarian::add_type (Biopore::component, "matrix", alist, syntax, &make);
  }
} BioporeMatrix_syntax;

// biopore_matrix.C ends here.
<commit_msg>make<commit_after>// biopore_matrix.C --- Static vertical biopores with a capacity.
//
// Copyright 2008 Per Abrahamsen and KU.
//
// This file is part of Daisy.
//
// Daisy is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// Daisy 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 Public License for more details.
//
// You should have received a copy of the GNU Lesser Public License
// along with Daisy; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

#define BUILD_DLL

#include "biopore.h"
#include "imvec.h"
#include "block.h"
#include "vcheck.h"
#include "librarian.h"
#include "submodeler.h"
#include "geometry.h"
#include "soil.h"
#include "soil_water.h"
#include "secondary.h"
#include "volume_box.h"
#include "log.h"
#include "check.h"
#include <sstream>

// The 'matrix' model.

struct BioporeMatrix : public Biopore
{
  // Parameters.
  /* const */ std::vector<double> xplus; // [cm]
  const double diameter;        // [cm]
  const double R_primary;       // [h/cm]
  const double R_secondary;     // [h/cm]

  // State.
  std::vector<double> h_bottom; // [cm]
  std::auto_ptr<IMvec> solute;  // [g/cm^3]

  // Utilities.
  /* const */ double dy;                    // [cm]
  std::vector<size_t> column;
  std::vector<double> added_water; // [cm^3]
  std::vector<double> density_column; // [cm^-2]

  // Simulation.
  bool to_drain () const
  { return false; }
  double air_bottom (const size_t c) const // Lowest point with air [cm]
  {
    daisy_assert (c < column.size ());
    const size_t col = column[c];
    daisy_assert (col < h_bottom.size ());
    return height_end + h_bottom[col];
  }
  void add_water (size_t c, double amount /* [cm^3] */)
  {
    daisy_assert (c < column.size ());
    const size_t col = column[c];
    daisy_assert (col < added_water.size ());
    added_water[col] += amount;
  }
  void extract_water (const size_t c, const double volume /* [cm^3] */ ,
                      const double Theta /* [cm^3/cm^3] */,
                      const double dt /* [h] */,
                      std::vector<double>& S_drain /* [cm^3/cm^3/h] */,
                      std::vector<double>& S_matrix, Treelog&);
  void release_water (const Geometry& geo, const Soil& soil,
                      const SoilWater& soil_water,
                      const double dt /* [h] */,
                      std::vector<double>& S_matrix, Treelog&);
  void update_water ();
  void output (Log&) const;

  // Create and Destroy.
  bool initialize (const Geometry& geo, const Scope& scope, double,
                   Treelog& msg);
  bool check (const Geometry& geo, Treelog& msg) const
  { return check_base (geo, msg); }
  BioporeMatrix (Block& al);
};

void
BioporeMatrix::extract_water (const size_t c, const double volume /* [cm^3] */ ,
                              const double Theta /* [cm^3/cm^3] */,
                              const double dt /* [h] */,
                              std::vector<double>& /* [cm^3/cm^3/h] */,
                              std::vector<double>& S_matrix, Treelog& msg)
{
  std::ostringstream tmp;
  tmp << "Extracting " << Theta << " [] water over " << dt
      << " hours from cell " << c;
  msg.message (tmp.str ());

  daisy_assert (c < S_matrix.size ());
  S_matrix[c] += Theta / dt;
  daisy_assert (c < column.size ());
  const size_t col = column[c];
  daisy_assert (col < h_bottom.size ());
  added_water[col] += Theta * volume;
}

void
BioporeMatrix::release_water (const Geometry& geo, const Soil& soil,
                              const SoilWater& soil_water,
                              const double dt /* [h] */,
                              std::vector<double>& S_matrix, Treelog& msg)
{
  const double circumference = M_PI * diameter; // [cm]

  const size_t cell_size = geo.cell_size ();
  for (size_t c = 0; c < cell_size; c++)
    {
      const double dens = density (c); // [cm^-2]
      if (dens < 1e-42)
        // No biopores of this class in this cell.
        continue;

      const double cell_z = geo.cell_z (c); // [cm]
      if (cell_z > height_start || cell_z < height_end)
        // Outside interval.
        continue;

      const double h_biopore =  air_bottom (c) - cell_z; // [cm]
      if (h_biopore < 1e-1)
        // No water significant water in biopore.
        continue;
      const double h_matrix = soil_water.h (c); // [cm]
      if (h_biopore < h_matrix + 1e-5)
        // Pressure in biopore not significantly above pressure in matrix.
        continue;
      const double dh = h_biopore - h_matrix; // [cm]
      daisy_assert (dh > 0.0);

      // Find resistance.
      const Secondary& secondary = soil.secondary_domain (c);
      const bool use_primary = secondary.none ();
      const double R = use_primary ? R_primary : R_secondary; // [h]

      // Find sink
      const double wall_per_area = circumference * dens; // [cm^-1]

      const double S = dh * wall_per_area / R; // [h^-1]

      std::ostringstream tmp;
      tmp << "Releasing " << S * dt << " [] water over " << dt
          << " hours in cell " << c
          << "\nz = " << cell_z << ", h_matrix = " << h_matrix
          << ", h_biopore = " << h_biopore << ", dh = " << dh
          << "\ncircumference = " << circumference << ", dens = " << dens
          << ", wall/area = " << wall_per_area << ", R = " << R;
      msg.message (tmp.str ());

      S_matrix[c] -= S;
      const double volume = geo.cell_volume (c); // [cm^3]
      added_water[column[c]] -= S * volume * dt; // [cm^3]
    }
}

void
BioporeMatrix::update_water ()
{
  const size_t column_size = xplus.size ();
  daisy_assert (added_water.size () == xplus.size ());
  double xminus = 0.0;
  for (size_t i = 0; i < column_size; i++)
    {
      const double density = density_column[i]; // [cm^-2]
      const double radius = diameter * 0.5;     // [cm]
      const double area = M_PI * radius * radius;  // [cm^2]
      const double soil_fraction = density * area; // []
      const double water_volume = added_water[i];  // [cm^3]
      const double soil_volume = water_volume / soil_fraction; // [cm^3]
      const double dx = xplus[i] - xminus;                     // [cm]
      const double dz = soil_volume / (dx * dy);               // [cm]
      h_bottom[i] += dz;                                          // [cm]
      added_water[i] = 0.0;                                    // [cm^3]
      xminus = xplus[i];                                       // [cm]
    }
}

void
BioporeMatrix::output (Log& log) const
{
  output_variable (h_bottom, log);
  output_submodule (*solute, "solute", log);
}

bool
BioporeMatrix::initialize (const Geometry& geo, const Scope& scope, double,
                           Treelog& msg)
{
  bool ok = true;

  // base.
  if (!initialize_base (geo, scope, msg))
    ok = false;

  // xplus.
  if (xplus.size () == 0)
    geo.fill_xplus (xplus);
  const size_t column_size = xplus.size ();
  daisy_assert (column_size > 0);

  // h_bottom.
  if (h_bottom.size () == 0)
    h_bottom.insert (h_bottom.end (), column_size, 0.0);

  if (h_bottom.size () != column_size)
    {
      msg.error ("Number of elements in 'h_bottom' does not match 'xplus'");
      ok = false;
    }

  // dy.
  dy = geo.back () - geo.front ();

  // column.
  daisy_assert (column.size () == 0);
  const size_t cell_size = geo.cell_size ();
  for (size_t c = 0; c < cell_size; c++)
    {
      const double x = geo.cell_x (c);
      for (size_t i = 0; i < column_size; i++)
        if (x < xplus[i])
          {
            column.push_back (i);
            goto found;
          }
      column.push_back (0U);
      {
        std::ostringstream tmp;
        tmp << "cell[" << c << "].x = " << x << ", > xplus[" << column_size - 1
            << "] = " << xplus[column_size-1];
        msg.error (tmp.str ());
      }
      ok = false;
    found:
      ;
    }
  daisy_assert (column.size () == cell_size);

  // added_water.
  added_water.insert (added_water.end (), column_size, 0.0);
  daisy_assert (added_water.size () == column_size);

  // density_column.
  if (density_cell.size () != cell_size)
    return false;

  double xminus = 0;
  for (size_t i = 0; i < column_size; i++)
    {
      VolumeBox square ("square", height_end, height_start, xminus, xplus[i]);
      const double volume = square.volume ();
      daisy_assert (volume > 0.0);
      const double content = geo.total_soil (density_cell, square);
      static const double m2_per_cm2 = 0.01 * 0.01;
      const double density = m2_per_cm2 * content / volume;
      density_column.push_back (density);
      xminus = xplus[i];
    }

  return ok;
}
BioporeMatrix::BioporeMatrix (Block& al)
  : Biopore (al),
    xplus (al.check ("xplus")
           ? al.number_sequence ("xplus")
           : std::vector<double> ()),
    diameter (al.number ("diameter")),
    R_primary (al.number ("R_primary")),
    R_secondary (al.number ("R_secondary", R_primary)),
    h_bottom (al.check ("h_bottom")
              ? al.number_sequence ("h_bottom")
              : std::vector<double> ()),
    solute (al.check ("solute")
            ? new IMvec (al, "solute")
            : NULL)
{ }

static struct BioporeMatrixSyntax
{
  static Model& make (Block& al)
  { return *new BioporeMatrix (al); }

  BioporeMatrixSyntax ()
  {
    Syntax& syntax = *new Syntax ();
    AttributeList& alist = *new AttributeList ();
    alist.add ("description", "Biopores that ends in the matrix.");
    Biopore::load_base (syntax, alist);

    syntax.add ("xplus", "cm", Check::positive (),
                Syntax::OptionalConst, Syntax::Sequence,
		"Right side of each biopore interval.\n\
Water and chemical content is tracked individually for each interval.\n\
By default, use intervals as specified by the geometry.");
    syntax.add_check ("xplus", VCheck::increasing ());
    syntax.add ("diameter", "cm", Check::positive (),
                Syntax::Const, "Biopore diameter.");
    syntax.add ("R_primary", "h", Check::positive (), Syntax::Const, "\
Resistance for water moving from biopore through wall to primary domain.");
    syntax.add ("R_secondary", "h", Check::positive (),
                Syntax::OptionalConst, "\
Resistance for water moving from biopore through wall to secondary domain.\n\
If not specified, this will be identical to 'R_primary'.");
    syntax.add ("h_bottom", "cm", Syntax::OptionalState, Syntax::Sequence,
		"Pressure at the bottom of the biopores in each interval.");

    static const symbol C_unit ("g/cm^3");
    IMvec::add_syntax (syntax, alist, Syntax::OptionalState, "solute", C_unit,
                       "Chemical concentration in biopore intervals.");

    Librarian::add_type (Biopore::component, "matrix", alist, syntax, &make);
  }
} BioporeMatrix_syntax;

// biopore_matrix.C ends here.
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright 2012 Electric Theatre Collective Limited. 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 Image Engine Design nor the names of any
//	   other contributors to this software 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 <unistd.h>

#include <iostream>

#include <UT/UT_WorkArgs.h>
#include <UT/UT_String.h>
#include <GU/GU_Detail.h>

#include "IECore/MessageHandler.h"
#include "IECore/Group.h"
#include "IECore/Reader.h"

#include "IECoreHoudini/Convert.h"
#include "IECoreMantra/Renderer.h"
#include "IECoreMantra/ProceduralPrimitive.h"

#include "boost/format.hpp"

using namespace IECore;
using namespace IECoreMantra;
using namespace std;
using namespace boost;

class VRAY_ieWorld : public ProceduralPrimitive {
public:
	VRAY_ieWorld();
	virtual ~VRAY_ieWorld();

#if UT_MAJOR_VERSION_INT >= 14

	virtual const char *className() const;

#else

	virtual const char  *getClassName();

#endif

	virtual int	  initialize(const UT_BoundingBox *);
	virtual void	 getBoundingBox(UT_BoundingBox &box);
	virtual void	 render();
#if UT_MAJOR_VERSION_INT >= 16
	UT_StringHolder m_worldFileName;
#else
	UT_String m_worldFileName;
#endif
	int m_remove;
};

static VRAY_ProceduralArg theArgs[] = {
};

VRAY_Procedural *
allocProcedural(const char *)
{
   return new VRAY_ieWorld();
}

const VRAY_ProceduralArg *
getProceduralArgs(const char *)
{
	return theArgs;
}

VRAY_ieWorld::VRAY_ieWorld()
{
	m_remove = 0;
}

VRAY_ieWorld::~VRAY_ieWorld()
{
	if ( m_remove == 1 )
	{
		if( access( m_worldFileName.buffer(), R_OK|F_OK ) != -1 )
		{
			if ( remove( m_worldFileName.buffer() ) != 0 )
			{
				msg( Msg::Warning, "VRAY_ieWorld", boost::format("Failed to remove ieworld cache file: %s") % m_worldFileName.buffer() );
			}
		}
	}
}

#if UT_MAJOR_VERSION_INT >= 14

const char *VRAY_ieWorld::className() const
{
	return "VRAY_ieWorld";
}

#else

const char *VRAY_ieWorld::getClassName()
{
	return "VRAY_ieWorld";
}

#endif

// The initialize method is called when the procedural is created.
// Returning zero (failure) will abort the rendering of this procedural.
// The bounding box passed in is the user defined bounding box.
// If the user didn't specify a bounding box, then the box will be NULL
int
VRAY_ieWorld::initialize(const UT_BoundingBox *box)
{
	if ( box )
    {
		m_bound = convert<Imath::Box3f> ( *box );
	}
	import( "ieworldfile", m_worldFileName);
	import( "ieworldremove", &m_remove, 1);
	if( access( m_worldFileName.buffer(), R_OK|F_OK ) == -1 )
	{
		msg( Msg::Warning, "VRAY_ieWorld", boost::format("Failed to find ieworld cache file: %s") % m_worldFileName.buffer() );
		return 0;
	}
	return 1;
}

void
VRAY_ieWorld::getBoundingBox(UT_BoundingBox &box)
{
	box = convert<UT_BoundingBox>( m_bound );
}

// When mantra determines that the bounding box needs to be rendered, the
// render method is called. At this point, the procedural can either
// generate geometry (VRAY_Procedural::openGeometryObject()) or it can
// generate further procedurals (VRAY_Procedural::openProceduralObject()).
void
VRAY_ieWorld::render()
{
	ConstVisibleRenderablePtr renderable = 0;
	try
	{
		ReaderPtr reader = Reader::create( m_worldFileName.buffer() );
		renderable = runTimeCast<VisibleRenderable>( reader->read() );
	}
	catch ( IECore::Exception e )
	{
		msg( Msg::Warning, "VRAY_ieWorld", boost::format("Failed to load ieworld cache file: %s") % m_worldFileName.buffer() );
	}
	if ( !renderable )
	{
		msg( Msg::Warning, "VRAY_ieWorld", boost::format("Failed to read ieworld cache file: %s") % m_worldFileName.buffer() );
	}
	IECoreMantra::RendererPtr renderer = new IECoreMantra::Renderer( this );
	renderable->render( renderer.get() );
}

<commit_msg>change int64 to int for World procedural<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright 2012 Electric Theatre Collective Limited. 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 Image Engine Design nor the names of any
//	   other contributors to this software 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 <unistd.h>

#include <iostream>

#include <UT/UT_WorkArgs.h>
#include <UT/UT_String.h>
#include <GU/GU_Detail.h>

#include "IECore/MessageHandler.h"
#include "IECore/Group.h"
#include "IECore/Reader.h"

#include "IECoreHoudini/Convert.h"
#include "IECoreMantra/Renderer.h"
#include "IECoreMantra/ProceduralPrimitive.h"

#include "boost/format.hpp"

using namespace IECore;
using namespace IECoreMantra;
using namespace std;
using namespace boost;

class VRAY_ieWorld : public ProceduralPrimitive {
public:
	VRAY_ieWorld();
	virtual ~VRAY_ieWorld();

#if UT_MAJOR_VERSION_INT >= 14

	virtual const char *className() const;

#else

	virtual const char  *getClassName();

#endif

	virtual int	  initialize(const UT_BoundingBox *);
	virtual void	 getBoundingBox(UT_BoundingBox &box);
	virtual void	 render();
#if UT_MAJOR_VERSION_INT >= 16
	UT_StringHolder m_worldFileName;
	int32 m_remove;
#else
	UT_String m_worldFileName;
	int m_remove;
#endif

};

static VRAY_ProceduralArg theArgs[] = {
};

VRAY_Procedural *
allocProcedural(const char *)
{
   return new VRAY_ieWorld();
}

const VRAY_ProceduralArg *
getProceduralArgs(const char *)
{
	return theArgs;
}

VRAY_ieWorld::VRAY_ieWorld()
{
	m_remove = 0;
}

VRAY_ieWorld::~VRAY_ieWorld()
{
	if ( m_remove == 1 )
	{
		if( access( m_worldFileName.buffer(), R_OK|F_OK ) != -1 )
		{
			if ( remove( m_worldFileName.buffer() ) != 0 )
			{
				msg( Msg::Warning, "VRAY_ieWorld", boost::format("Failed to remove ieworld cache file: %s") % m_worldFileName.buffer() );
			}
		}
	}
}

#if UT_MAJOR_VERSION_INT >= 14

const char *VRAY_ieWorld::className() const
{
	return "VRAY_ieWorld";
}

#else

const char *VRAY_ieWorld::getClassName()
{
	return "VRAY_ieWorld";
}

#endif

// The initialize method is called when the procedural is created.
// Returning zero (failure) will abort the rendering of this procedural.
// The bounding box passed in is the user defined bounding box.
// If the user didn't specify a bounding box, then the box will be NULL
int
VRAY_ieWorld::initialize(const UT_BoundingBox *box)
{
	if ( box )
    {
		m_bound = convert<Imath::Box3f> ( *box );
	}
	import( "ieworldfile", m_worldFileName);
	import( "ieworldremove", &m_remove, 1);
	if( access( m_worldFileName.buffer(), R_OK|F_OK ) == -1 )
	{
		msg( Msg::Warning, "VRAY_ieWorld", boost::format("Failed to find ieworld cache file: %s") % m_worldFileName.buffer() );
		return 0;
	}
	return 1;
}

void
VRAY_ieWorld::getBoundingBox(UT_BoundingBox &box)
{
	box = convert<UT_BoundingBox>( m_bound );
}

// When mantra determines that the bounding box needs to be rendered, the
// render method is called. At this point, the procedural can either
// generate geometry (VRAY_Procedural::openGeometryObject()) or it can
// generate further procedurals (VRAY_Procedural::openProceduralObject()).
void
VRAY_ieWorld::render()
{
	ConstVisibleRenderablePtr renderable = 0;
	try
	{
		ReaderPtr reader = Reader::create( m_worldFileName.buffer() );
		renderable = runTimeCast<VisibleRenderable>( reader->read() );
	}
	catch ( IECore::Exception e )
	{
		msg( Msg::Warning, "VRAY_ieWorld", boost::format("Failed to load ieworld cache file: %s") % m_worldFileName.buffer() );
	}
	if ( !renderable )
	{
		msg( Msg::Warning, "VRAY_ieWorld", boost::format("Failed to read ieworld cache file: %s") % m_worldFileName.buffer() );
	}
	IECoreMantra::RendererPtr renderer = new IECoreMantra::Renderer( this );
	renderable->render( renderer.get() );
}

<|endoftext|>


<commit_before>//
// Created by agondek on 12/12/15.
//

#include "ChessGameState.h"

namespace Mcts
{
    namespace GameStates
    {
        ChessGameState::ChessGameState(unsigned short int lastActivePlayer,
                                       std::unordered_map<std::string, std::string> chessBoard)
        {
            this->setLastActivePlayer(lastActivePlayer);
            this->setChessBoard(chessBoard);
        }

        ChessGameState ChessGameState::clone(void)
        {
            ChessGameState deepClone(this->getLastActivePlayer(), this->_chessBoard);
        }

        void ChessGameState::setChessBoard(std::unordered_map<std::string, std::string> chessBoard)
        {
            this->_chessBoard = chessBoard;
        }

        unsigned long int ChessGameState::getStateValue(unsigned short int playerId)
        {
            if(playerId == MCTS_PLAYER_ONE_ID)
            {
                return this->_playerTwoKingDown == true ? 1 : 0;
            }
            else if(playerId == MCTS_PLAYER_TWO_ID)
            {
                return this->_playerOneKingDown == true ? 1 : 0;
            }

            return 0;
        }

        void ChessGameState::performAction(std::string action)
        {
            // Because of format '{playerId}>{fromPostion}>{toPostion}'
            // i.e. 1>1A>1B
            std::string pieceFromPosition = action.substr(2,2);
            std::string pieceToPosition = action.substr(5,2);
            bool toPostionIsEmpty = IsBoardFieldEmpty(pieceToPosition);

            if(!toPostionIsEmpty)
            {
                // TODO: Later this shoud not take place
                // But for now game ends when king is dead
                std::string pieceToData = this->_chessBoard[pieceToData];
                if (pieceToData.substr(2, 1) == MCTS_CHESS_GAME_PIECE_KING)
                {
                    // Taken down king will belong to lastActivePlayer, since current
                    // turn is not his.
                    if (this->_lastActivePlayer == MCTS_PLAYER_ONE_ID)
                    {
                        this->_playerOneKingDown = true;
                    }
                    else if (this->_lastActivePlayer == MCTS_PLAYER_TWO_ID)
                    {
                        this->_playerTwoKingDown = true;
                    }
                }
            }

            // Move piece to pointed location
            this->_chessBoard[pieceToPosition] = this->_chessBoard[pieceFromPosition];

            if(!toPostionIsEmpty)
            {
                // Remove piece from previous location
                this->_chessBoard.erase(pieceFromPosition);
            }
        }

        // This function has many uses and should be splitted into multiple
        // However for nows this should do.
        // And again: for now, we are not checking for checks - whatever happens, happens
        std::vector<std::string> ChessGameState::getAvailableActions(void)
        {
            // If king is down, game is over, no further moves are permitted
            if(this->_playerOneKingDown || this->_playerTwoKingDown)
            {
                return std::vector<std::string>();
            }

            // Calculate all actions for given player
            for (std::unordered_map<std::string, std::string>::iterator it = this->_chessBoard.begin();
                 it != this->_chessBoard.end(); ++it)
            {
                std::vector<std::string> newActions = this->getAvailableActions(it->first, it->second);
                this->_availableActions.insert(
                        this->_availableActions.end(),
                        newActions.begin(),
                        newActions.end()
                );
            }

            return std::vector<std::string>();
        }

        std::vector<std::string> ChessGameState::getAvailableActions(std::string piecePosition,
                                                                     std::string pieceData)
        {
            std::string pieceType = pieceData.substr(2,1);
            if(MCTS_CHESS_GAME_PIECE_PAWN == pieceType)
            {
                return this->GetPawnPossibleMoves(piecePosition, pieceData);
            }
            else if(MCTS_CHESS_GAME_PIECE_KNIGHT == pieceType)
            {
                return std::vector<std::string>();
            }
            else if(MCTS_CHESS_GAME_PIECE_BISHOP == pieceType)
            {
                return std::vector<std::string>();
            }
            else if(MCTS_CHESS_GAME_PIECE_ROOK == pieceType)
            {
                return std::vector<std::string>();
            }
            else if(MCTS_CHESS_GAME_PIECE_QUEEN == pieceType)
            {
                return std::vector<std::string>();
            }
            else if(MCTS_CHESS_GAME_PIECE_KING == pieceType)
            {
                return this->GetKingPossibleMoves(piecePosition, pieceData);
            }

            return std::vector<std::string>();
        }

        std::vector<std::string> ChessGameState::GetKingPossibleMoves(std::string kingPosition,
                                                                      std::string kingData)
        {
            std::vector<std::string> moves;
            // Because pawnPostion '1A'
            char posLetter = kingPosition[1];
            int posIndex = atoi(&kingPosition[0]);
            // Because pawnData '1:R'
            int controlingPlayer = atoi(&kingData[0]);

            // make sure that numberIndex is above 0
            int numberIndex = (posIndex - 1) > 0 ? posIndex - 1 : posIndex;
            int numberIndexMax = (posIndex + 1) <= 8 ? posIndex + 1 : posIndex;
            // make sure that letterIndex is not smaller than 'A'
            char letterIndex = (posLetter - 1) >= 'A' ? posLetter - 1 : posLetter;
            char letterIndexMax = (posLetter + 1) <= 'Z' ? posLetter + 1 : posLetter;

            // Check 1x1 square around king for possible moves
            while(numberIndex <= numberIndexMax)
            {
                while(letterIndex <= letterIndexMax)
                {
                    std::string newPosition = std::to_string(numberIndex);
                    newPosition += letterIndex;

                    // If place is empty
                    if(this->IsBoardFieldEmpty(newPosition))
                    {
                        std::string action = std::to_string(controlingPlayer);
                        action += ">";
                        action += kingPosition;
                        action += ">";
                        action += newPosition;
                        moves.push_back(action);
                    }
                    // If place is occupied
                    else
                    {
                        std::string pieceToBeTaken = this->_chessBoard[newPosition];
                        unsigned short int pieceToBeTakenOwnerId = (unsigned short int)
                                std::strtoul(pieceToBeTaken.substr(0,1).c_str(), 0, 10);

                        // If occupied place is not owned by same player
                        if(pieceToBeTakenOwnerId != controlingPlayer)
                        {
                            std::string action = std::to_string(controlingPlayer);
                            action += ">";
                            action += kingPosition;
                            action += ">";
                            action += newPosition;
                            moves.push_back(action);
                        }
                    }
                    letterIndex += 1;
                }
                numberIndex++;
            }

            return moves;
        }

        std::vector<std::string> ChessGameState::GetPawnPossibleMoves(std::string pawnPosition,
                                                                      std::string pawnData)
        {
            std::vector<std::string> moves;
            // Because pawnPostion '1A'
            char posLetter = pawnPosition[1];
            char newPosLetter = pawnPosition[1];
            int newPosIndex = atoi(&pawnPosition[0]);
            // Because pawnData '1:R'
            int controlingPlayer = atoi(&pawnData[0]);

            // Pawns of player 1 move from index 1st towards 8th index,
            // pawns of player 2 move from index 8th towards 1st index
            if(controlingPlayer == MCTS_PLAYER_ONE_ID)
            {
                // If field ahead exists
                newPosIndex++;
                if(newPosIndex <= 8)
                {
                    std::string newPosition = std::to_string(newPosIndex);
                    newPosition += newPosLetter;
                    // If field ahead is empty
                    if(this->IsBoardFieldEmpty(newPosition))
                    {
                        std::string action = std::to_string(controlingPlayer);
                        action += ">";
                        action += pawnPosition;
                        action += ">";
                        action += newPosition;

                        moves.push_back(action);
                    }

                    // If can takeout other piece
                    newPosition = std::to_string(newPosIndex);
                    newPosLetter += 1;
                    newPosition += newPosLetter;
                    if(newPosLetter <= 'H')
                    {
                        // If field is not empty (cannot take down nothing)
                        if(!this->IsBoardFieldEmpty(newPosition))
                        {
                            std::string pieceToBeTaken = this->_chessBoard[newPosition];
                            unsigned short int pieceToBeTakenOwnerId = (unsigned short int)
                                    std::strtoul(pieceToBeTaken.substr(0,1).c_str(), 0, 10);

                            if(pieceToBeTakenOwnerId != MCTS_PLAYER_ONE_ID)
                            {
                                std::string action = std::to_string(controlingPlayer);
                                action += ">";
                                action += pawnPosition;
                                action += ">";
                                action += newPosition;

                                moves.push_back(action);
                            }
                        }
                    }

                    newPosition = std::to_string(newPosIndex);
                    newPosLetter = posLetter;
                    newPosLetter -= 1;
                    newPosition += newPosLetter;
                    if(newPosLetter >= 'A')
                    {
                        // If field is not empty (cannot take down nothing)
                        if(!this->IsBoardFieldEmpty(newPosition))
                        {
                            // If field is not empty (cannot take down nothing)
                            if(!this->IsBoardFieldEmpty(newPosition))
                            {
                                std::string pieceToBeTaken = this->_chessBoard[newPosition];
                                unsigned short int pieceToBeTakenOwnerId = (unsigned short int)
                                        std::strtoul(pieceToBeTaken.substr(0,1).c_str(), 0, 10);

                                if(pieceToBeTakenOwnerId != MCTS_PLAYER_ONE_ID)
                                {
                                    std::string action = std::to_string(controlingPlayer);
                                    action += ">";
                                    action += pawnPosition;
                                    action += ">";
                                    action += newPosition;

                                    moves.push_back(action);
                                }
                            }
                        }
                    }
                }
            }
            else if(controlingPlayer == MCTS_PLAYER_TWO_ID)
            {
                // If field ahead exists
                newPosIndex--;
                if(newPosIndex > 0)
                {
                    std::string newPosition = std::to_string(newPosIndex);
                    newPosition += newPosLetter;
                    // If field ahead is empty
                    if(this->IsBoardFieldEmpty(newPosition))
                    {
                        std::string action = std::to_string(controlingPlayer);
                        action += ">";
                        action += pawnPosition;
                        action += ">";
                        action += newPosition;

                        moves.push_back(action);
                    }

                    // If can takeout other piece
                    newPosition = std::to_string(newPosIndex);
                    newPosLetter += 1;
                    newPosition += newPosLetter;
                    if(newPosLetter <= 'H')
                    {
                        // If field is not empty (cannot take down nothing)
                        if(!this->IsBoardFieldEmpty(newPosition))
                        {
                            std::string pieceToBeTaken = this->_chessBoard[newPosition];
                            unsigned short int pieceToBeTakenOwnerId = (unsigned short int)
                                    std::strtoul(pieceToBeTaken.substr(0,1).c_str(), 0, 10);

                            if(pieceToBeTakenOwnerId != MCTS_PLAYER_ONE_ID)
                            {
                                std::string action = std::to_string(controlingPlayer);
                                action += ">";
                                action += pawnPosition;
                                action += ">";
                                action += newPosition;

                                moves.push_back(action);
                            }
                        }
                    }

                    newPosition = std::to_string(newPosIndex);
                    newPosLetter = posLetter;
                    newPosLetter -= 1;
                    newPosition += newPosLetter;
                    if(newPosLetter >= 'A')
                    {
                        // If field is not empty (cannot take down nothing)
                        if(!this->IsBoardFieldEmpty(newPosition))
                        {
                            // If field is not empty (cannot take down nothing)
                            if(!this->IsBoardFieldEmpty(newPosition))
                            {
                                std::string pieceToBeTaken = this->_chessBoard[newPosition];
                                unsigned short int pieceToBeTakenOwnerId = (unsigned short int)
                                        std::strtoul(pieceToBeTaken.substr(0,1).c_str(), 0, 10);

                                if(pieceToBeTakenOwnerId != MCTS_PLAYER_ONE_ID)
                                {
                                    std::string action = std::to_string(controlingPlayer);
                                    action += ">";
                                    action += pawnPosition;
                                    action += ">";
                                    action += newPosition;

                                    moves.push_back(action);
                                }
                            }
                        }
                    }

                }
            }

            return moves;
        }

        std::string ChessGameState::GetPieceTypeFromBoardValue(std::string value)
        {
            // This nighmarish if chain is needed to make sure that we
            // are not returning invalid piece type if something goes
            // wrong. Then we can just return unknown type.

            std::string pieceType = value.substr(2,1);
            if(MCTS_CHESS_GAME_PIECE_PAWN == pieceType)
            {
                return MCTS_CHESS_GAME_PIECE_PAWN;
            }
            else if(MCTS_CHESS_GAME_PIECE_KNIGHT == pieceType)
            {
                return MCTS_CHESS_GAME_PIECE_KNIGHT;
            }
            else if(MCTS_CHESS_GAME_PIECE_BISHOP == pieceType)
            {
                return MCTS_CHESS_GAME_PIECE_BISHOP;
            }
            else if(MCTS_CHESS_GAME_PIECE_ROOK == pieceType)
            {
                return MCTS_CHESS_GAME_PIECE_ROOK;
            }
            else if(MCTS_CHESS_GAME_PIECE_QUEEN == pieceType)
            {
                return MCTS_CHESS_GAME_PIECE_QUEEN;
            }
            else if(MCTS_CHESS_GAME_PIECE_KING == pieceType)
            {
                return MCTS_CHESS_GAME_PIECE_KING;
            }

            return MCTS_CHESS_GAME_PIECE_UNKNOWN;
        }

        bool ChessGameState::IsBoardFieldEmpty(std::string position)
        {
            return this->_chessBoard.find(position) == this->_chessBoard.end();
        }

        // Getters and setters
        unsigned short int ChessGameState::getLastActivePlayer(void)
        {
            return this->_lastActivePlayer;
        }

        void ChessGameState::setLastActivePlayer(unsigned short int playerId)
        {
            this->_lastActivePlayer = playerId;
        }
    }
}<commit_msg>Compiles<commit_after>//
// Created by agondek on 12/12/15.
//

#include "ChessGameState.h"

namespace Mcts
{
    namespace GameStates
    {
        ChessGameState::ChessGameState(unsigned short int lastActivePlayer,
                                       std::unordered_map<std::string, std::string> chessBoard)
        {
            this->setLastActivePlayer(lastActivePlayer);
            this->setChessBoard(chessBoard);
        }

        ChessGameState ChessGameState::clone(void)
        {
            ChessGameState deepClone(this->getLastActivePlayer(), this->_chessBoard);
        }

        void ChessGameState::setChessBoard(std::unordered_map<std::string, std::string> chessBoard)
        {
            this->_chessBoard = chessBoard;
        }

        unsigned long int ChessGameState::getStateValue(unsigned short int playerId)
        {
            if(playerId == MCTS_PLAYER_ONE_ID)
            {
                return this->_playerTwoKingDown ? 1 : 0;
            }
            else if(playerId == MCTS_PLAYER_TWO_ID)
            {
                return this->_playerOneKingDown ? 1 : 0;
            }

            return 0;
        }

        void ChessGameState::performAction(std::string action)
        {
            // Because of format '{playerId}>{fromPostion}>{toPostion}'
            // i.e. 1>1A>1B
            std::string pieceFromPosition = action.substr(2,2);
            std::string pieceToPosition = action.substr(5,2);
            bool toPostionIsEmpty = IsBoardFieldEmpty(pieceToPosition);

            if(!toPostionIsEmpty)
            {
                // TODO: Later this shoud not take place
                // But for now game ends when king is dead
                std::string pieceToData = this->_chessBoard[pieceToData];
                if (pieceToData.substr(2, 1) == MCTS_CHESS_GAME_PIECE_KING)
                {
                    // Taken down king will belong to lastActivePlayer, since current
                    // turn is not his.
                    if (this->_lastActivePlayer == MCTS_PLAYER_ONE_ID)
                    {
                        this->_playerOneKingDown = true;
                    }
                    else if (this->_lastActivePlayer == MCTS_PLAYER_TWO_ID)
                    {
                        this->_playerTwoKingDown = true;
                    }
                }
            }

            // Move piece to pointed location
            this->_chessBoard[pieceToPosition] = this->_chessBoard[pieceFromPosition];

            if(!toPostionIsEmpty)
            {
                // Remove piece from previous location
                this->_chessBoard.erase(pieceFromPosition);
            }
        }

        // This function has many uses and should be splitted into multiple
        // However for nows this should do.
        // And again: for now, we are not checking for checks - whatever happens, happens
        std::vector<std::string> ChessGameState::getAvailableActions(void)
        {
            // If king is down, game is over, no further moves are permitted
            if(this->_playerOneKingDown || this->_playerTwoKingDown)
            {
                return std::vector<std::string>();
            }

            // Calculate all actions for given player
            for (std::unordered_map<std::string, std::string>::iterator it = this->_chessBoard.begin();
                 it != this->_chessBoard.end(); ++it)
            {
                std::vector<std::string> newActions = this->getAvailableActions(it->first, it->second);
                this->_availableActions.insert(
                        this->_availableActions.end(),
                        newActions.begin(),
                        newActions.end()
                );
            }

            return std::vector<std::string>();
        }

        std::vector<std::string> ChessGameState::getAvailableActions(std::string piecePosition,
                                                                     std::string pieceData)
        {
            std::string pieceType = pieceData.substr(2,1);
            if(MCTS_CHESS_GAME_PIECE_PAWN == pieceType)
            {
                return this->GetPawnPossibleMoves(piecePosition, pieceData);
            }
            else if(MCTS_CHESS_GAME_PIECE_KNIGHT == pieceType)
            {
                return std::vector<std::string>();
            }
            else if(MCTS_CHESS_GAME_PIECE_BISHOP == pieceType)
            {
                return std::vector<std::string>();
            }
            else if(MCTS_CHESS_GAME_PIECE_ROOK == pieceType)
            {
                return std::vector<std::string>();
            }
            else if(MCTS_CHESS_GAME_PIECE_QUEEN == pieceType)
            {
                return std::vector<std::string>();
            }
            else if(MCTS_CHESS_GAME_PIECE_KING == pieceType)
            {
                return this->GetKingPossibleMoves(piecePosition, pieceData);
            }

            return std::vector<std::string>();
        }

        std::vector<std::string> ChessGameState::GetKingPossibleMoves(std::string kingPosition,
                                                                      std::string kingData)
        {
            std::vector<std::string> moves;
            // Because pawnPostion '1A'
            char posLetter = kingPosition[1];
            int posIndex = atoi(&kingPosition[0]);
            // Because pawnData '1:R'
            int controlingPlayer = atoi(&kingData[0]);

            // make sure that numberIndex is above 0
            int numberIndex = (posIndex - 1) > 0 ? posIndex - 1 : posIndex;
            int numberIndexMax = (posIndex + 1) <= 8 ? posIndex + 1 : posIndex;
            // make sure that letterIndex is not smaller than 'A'
            char letterIndex = (posLetter - 1) >= 'A' ? posLetter - 1 : posLetter;
            char letterIndexMax = (posLetter + 1) <= 'Z' ? posLetter + 1 : posLetter;

            // Check 1x1 square around king for possible moves
            while(numberIndex <= numberIndexMax)
            {
                while(letterIndex <= letterIndexMax)
                {
                    std::string newPosition = std::to_string(numberIndex);
                    newPosition += letterIndex;

                    // If place is empty
                    if(this->IsBoardFieldEmpty(newPosition))
                    {
                        std::string action = std::to_string(controlingPlayer);
                        action += ">";
                        action += kingPosition;
                        action += ">";
                        action += newPosition;
                        moves.push_back(action);
                    }
                    // If place is occupied
                    else
                    {
                        std::string pieceToBeTaken = this->_chessBoard[newPosition];
                        unsigned short int pieceToBeTakenOwnerId = (unsigned short int)
                                std::strtoul(pieceToBeTaken.substr(0,1).c_str(), 0, 10);

                        // If occupied place is not owned by same player
                        if(pieceToBeTakenOwnerId != controlingPlayer)
                        {
                            std::string action = std::to_string(controlingPlayer);
                            action += ">";
                            action += kingPosition;
                            action += ">";
                            action += newPosition;
                            moves.push_back(action);
                        }
                    }
                    letterIndex += 1;
                }
                numberIndex++;
            }

            return moves;
        }

        std::vector<std::string> ChessGameState::GetPawnPossibleMoves(std::string pawnPosition,
                                                                      std::string pawnData)
        {
            std::vector<std::string> moves;
            // Because pawnPostion '1A'
            char posLetter = pawnPosition[1];
            char newPosLetter = pawnPosition[1];
            int newPosIndex = atoi(&pawnPosition[0]);
            // Because pawnData '1:R'
            int controlingPlayer = atoi(&pawnData[0]);

            // Pawns of player 1 move from index 1st towards 8th index,
            // pawns of player 2 move from index 8th towards 1st index
            if(controlingPlayer == MCTS_PLAYER_ONE_ID)
            {
                // If field ahead exists
                newPosIndex++;
                if(newPosIndex <= 8)
                {
                    std::string newPosition = std::to_string(newPosIndex);
                    newPosition += newPosLetter;
                    // If field ahead is empty
                    if(this->IsBoardFieldEmpty(newPosition))
                    {
                        std::string action = std::to_string(controlingPlayer);
                        action += ">";
                        action += pawnPosition;
                        action += ">";
                        action += newPosition;

                        moves.push_back(action);
                    }

                    // If can takeout other piece
                    newPosition = std::to_string(newPosIndex);
                    newPosLetter += 1;
                    newPosition += newPosLetter;
                    if(newPosLetter <= 'H')
                    {
                        // If field is not empty (cannot take down nothing)
                        if(!this->IsBoardFieldEmpty(newPosition))
                        {
                            std::string pieceToBeTaken = this->_chessBoard[newPosition];
                            unsigned short int pieceToBeTakenOwnerId = (unsigned short int)
                                    std::strtoul(pieceToBeTaken.substr(0,1).c_str(), 0, 10);

                            if(pieceToBeTakenOwnerId != MCTS_PLAYER_ONE_ID)
                            {
                                std::string action = std::to_string(controlingPlayer);
                                action += ">";
                                action += pawnPosition;
                                action += ">";
                                action += newPosition;

                                moves.push_back(action);
                            }
                        }
                    }

                    newPosition = std::to_string(newPosIndex);
                    newPosLetter = posLetter;
                    newPosLetter -= 1;
                    newPosition += newPosLetter;
                    if(newPosLetter >= 'A')
                    {
                        // If field is not empty (cannot take down nothing)
                        if(!this->IsBoardFieldEmpty(newPosition))
                        {
                            // If field is not empty (cannot take down nothing)
                            if(!this->IsBoardFieldEmpty(newPosition))
                            {
                                std::string pieceToBeTaken = this->_chessBoard[newPosition];
                                unsigned short int pieceToBeTakenOwnerId = (unsigned short int)
                                        std::strtoul(pieceToBeTaken.substr(0,1).c_str(), 0, 10);

                                if(pieceToBeTakenOwnerId != MCTS_PLAYER_ONE_ID)
                                {
                                    std::string action = std::to_string(controlingPlayer);
                                    action += ">";
                                    action += pawnPosition;
                                    action += ">";
                                    action += newPosition;

                                    moves.push_back(action);
                                }
                            }
                        }
                    }
                }
            }
            else if(controlingPlayer == MCTS_PLAYER_TWO_ID)
            {
                // If field ahead exists
                newPosIndex--;
                if(newPosIndex > 0)
                {
                    std::string newPosition = std::to_string(newPosIndex);
                    newPosition += newPosLetter;
                    // If field ahead is empty
                    if(this->IsBoardFieldEmpty(newPosition))
                    {
                        std::string action = std::to_string(controlingPlayer);
                        action += ">";
                        action += pawnPosition;
                        action += ">";
                        action += newPosition;

                        moves.push_back(action);
                    }

                    // If can takeout other piece
                    newPosition = std::to_string(newPosIndex);
                    newPosLetter += 1;
                    newPosition += newPosLetter;
                    if(newPosLetter <= 'H')
                    {
                        // If field is not empty (cannot take down nothing)
                        if(!this->IsBoardFieldEmpty(newPosition))
                        {
                            std::string pieceToBeTaken = this->_chessBoard[newPosition];
                            unsigned short int pieceToBeTakenOwnerId = (unsigned short int)
                                    std::strtoul(pieceToBeTaken.substr(0,1).c_str(), 0, 10);

                            if(pieceToBeTakenOwnerId != MCTS_PLAYER_ONE_ID)
                            {
                                std::string action = std::to_string(controlingPlayer);
                                action += ">";
                                action += pawnPosition;
                                action += ">";
                                action += newPosition;

                                moves.push_back(action);
                            }
                        }
                    }

                    newPosition = std::to_string(newPosIndex);
                    newPosLetter = posLetter;
                    newPosLetter -= 1;
                    newPosition += newPosLetter;
                    if(newPosLetter >= 'A')
                    {
                        // If field is not empty (cannot take down nothing)
                        if(!this->IsBoardFieldEmpty(newPosition))
                        {
                            // If field is not empty (cannot take down nothing)
                            if(!this->IsBoardFieldEmpty(newPosition))
                            {
                                std::string pieceToBeTaken = this->_chessBoard[newPosition];
                                unsigned short int pieceToBeTakenOwnerId = (unsigned short int)
                                        std::strtoul(pieceToBeTaken.substr(0,1).c_str(), 0, 10);

                                if(pieceToBeTakenOwnerId != MCTS_PLAYER_ONE_ID)
                                {
                                    std::string action = std::to_string(controlingPlayer);
                                    action += ">";
                                    action += pawnPosition;
                                    action += ">";
                                    action += newPosition;

                                    moves.push_back(action);
                                }
                            }
                        }
                    }

                }
            }

            return moves;
        }

        std::string ChessGameState::GetPieceTypeFromBoardValue(std::string value)
        {
            // This nighmarish if chain is needed to make sure that we
            // are not returning invalid piece type if something goes
            // wrong. Then we can just return unknown type.

            std::string pieceType = value.substr(2,1);
            if(MCTS_CHESS_GAME_PIECE_PAWN == pieceType)
            {
                return MCTS_CHESS_GAME_PIECE_PAWN;
            }
            else if(MCTS_CHESS_GAME_PIECE_KNIGHT == pieceType)
            {
                return MCTS_CHESS_GAME_PIECE_KNIGHT;
            }
            else if(MCTS_CHESS_GAME_PIECE_BISHOP == pieceType)
            {
                return MCTS_CHESS_GAME_PIECE_BISHOP;
            }
            else if(MCTS_CHESS_GAME_PIECE_ROOK == pieceType)
            {
                return MCTS_CHESS_GAME_PIECE_ROOK;
            }
            else if(MCTS_CHESS_GAME_PIECE_QUEEN == pieceType)
            {
                return MCTS_CHESS_GAME_PIECE_QUEEN;
            }
            else if(MCTS_CHESS_GAME_PIECE_KING == pieceType)
            {
                return MCTS_CHESS_GAME_PIECE_KING;
            }

            return MCTS_CHESS_GAME_PIECE_UNKNOWN;
        }

        bool ChessGameState::IsBoardFieldEmpty(std::string position)
        {
            return this->_chessBoard.find(position) == this->_chessBoard.end();
        }

        // Getters and setters
        unsigned short int ChessGameState::getLastActivePlayer(void)
        {
            return this->_lastActivePlayer;
        }

        void ChessGameState::setLastActivePlayer(unsigned short int playerId)
        {
            this->_lastActivePlayer = playerId;
        }
    }
}<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: debug.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-03-30 07:34:33 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#if ! defined(INCLUDED_CANVAS_DEBUG_HXX)
#define INCLUDED_CANVAS_DEBUG_HXX

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif

#include <boost/current_function.hpp>

// Class invariants
// ----------------
#if OSL_DEBUG_LEVEL > 0

/** This macro asserts the given condition, and throws an
    IllegalArgumentException afterwards.

    In production code, no assertion appears, but the
    IllegalArgumentException is thrown nevertheless (although without
    the given error string, to conserve space).
 */
#define CHECK_AND_THROW(c, m)   if( !(c) ) { \
                                     OSL_ENSURE(false, m); \
                                     throw ::com::sun::star::lang::IllegalArgumentException( \
                                     ::rtl::OUString::createFromAscii(BOOST_CURRENT_FUNCTION) + \
                                     ::rtl::OUString::createFromAscii(",\n"m), \
                                     ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >(), \
                                     0 ); }

/** This macro asserts the given condition, and throws an
    RuntimeException afterwards.

    In production code, no assertion appears, but the
    RuntimeException is thrown nevertheless (although without
    the given error string, to conserve space).
 */
#define ENSURE_AND_THROW(c, m)   if( !(c) ) { \
                                     OSL_ENSURE(false, m); \
                                     throw ::com::sun::star::uno::RuntimeException( \
                                     ::rtl::OUString::createFromAscii(BOOST_CURRENT_FUNCTION) + \
                                     ::rtl::OUString::createFromAscii(",\n"m), \
                                     ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >() ); }

/** This macro asserts the given condition, and returns false
    afterwards.

    In production code, no assertion appears, but the return is issued
    nevertheless.
 */
#define ENSURE_AND_RETURN(c, m)  if( !(c) ) { \
                                     OSL_ENSURE(false, m); \
                                     return false; }

#else // ! (OSL_DEBUG_LEVEL > 0)

#define CHECK_AND_THROW(c, m)   if( !(c) )                                                  \
                                     throw ::com::sun::star::lang::IllegalArgumentException( \
                                     ::rtl::OUString::createFromAscii(BOOST_CURRENT_FUNCTION) + \
                                     ::rtl::OUString::createFromAscii(",\n"m), \
                                     ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >(), \
                                     0 )

#define ENSURE_AND_THROW(c, m)   if( !(c) )                                                     \
                                     throw ::com::sun::star::uno::RuntimeException( \
                                     ::rtl::OUString::createFromAscii(BOOST_CURRENT_FUNCTION) + \
                                     ::rtl::OUString::createFromAscii(",\n"m), \
                                     ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >() )

#define ENSURE_AND_RETURN(c, m)  if( !(c) )                                                     \
                                     return false

#endif

// shared_ptr debugging
// --------------------

#ifdef BOOST_SP_ENABLE_DEBUG_HOOKS

#include <boost/shared_ptr.hpp>

::std::size_t find_unreachable_objects( bool );

#ifdef VERBOSE
#define SHARED_PTR_LEFTOVERS(a) OSL_TRACE( "%s\n%s: Unreachable objects still use %d bytes", \
                                           BOOST_CURRENT_FUNCTION, a, \
                                           find_unreachable_objects(true) )
#else
/** This macro shows how much memory is still used by shared_ptrs

    Use this macro at places in the code where normally all shared_ptr
    objects should have been deleted. You'll get the number of bytes
    still contained in those objects, which quite possibly are prevented
    from deletion by circular references.
 */
#define SHARED_PTR_LEFTOVERS(a) OSL_TRACE( "%s\n%s: Unreachable objects still use %d bytes", \
                                           BOOST_CURRENT_FUNCTION, a, \
                                           find_unreachable_objects(false) )
#endif

#else

#define SHARED_PTR_LEFTOVERS(a) ((void)0)

#endif

#endif // ! defined(INCLUDED_CANVAS_DEBUG_HXX)
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.20); FILE MERGED 2005/09/05 17:26:53 rt 1.4.20.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: debug.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 23:04:39 $
 *
 *  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
 *
 ************************************************************************/

#if ! defined(INCLUDED_CANVAS_DEBUG_HXX)
#define INCLUDED_CANVAS_DEBUG_HXX

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif

#include <boost/current_function.hpp>

// Class invariants
// ----------------
#if OSL_DEBUG_LEVEL > 0

/** This macro asserts the given condition, and throws an
    IllegalArgumentException afterwards.

    In production code, no assertion appears, but the
    IllegalArgumentException is thrown nevertheless (although without
    the given error string, to conserve space).
 */
#define CHECK_AND_THROW(c, m)   if( !(c) ) { \
                                     OSL_ENSURE(false, m); \
                                     throw ::com::sun::star::lang::IllegalArgumentException( \
                                     ::rtl::OUString::createFromAscii(BOOST_CURRENT_FUNCTION) + \
                                     ::rtl::OUString::createFromAscii(",\n"m), \
                                     ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >(), \
                                     0 ); }

/** This macro asserts the given condition, and throws an
    RuntimeException afterwards.

    In production code, no assertion appears, but the
    RuntimeException is thrown nevertheless (although without
    the given error string, to conserve space).
 */
#define ENSURE_AND_THROW(c, m)   if( !(c) ) { \
                                     OSL_ENSURE(false, m); \
                                     throw ::com::sun::star::uno::RuntimeException( \
                                     ::rtl::OUString::createFromAscii(BOOST_CURRENT_FUNCTION) + \
                                     ::rtl::OUString::createFromAscii(",\n"m), \
                                     ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >() ); }

/** This macro asserts the given condition, and returns false
    afterwards.

    In production code, no assertion appears, but the return is issued
    nevertheless.
 */
#define ENSURE_AND_RETURN(c, m)  if( !(c) ) { \
                                     OSL_ENSURE(false, m); \
                                     return false; }

#else // ! (OSL_DEBUG_LEVEL > 0)

#define CHECK_AND_THROW(c, m)   if( !(c) )                                                  \
                                     throw ::com::sun::star::lang::IllegalArgumentException( \
                                     ::rtl::OUString::createFromAscii(BOOST_CURRENT_FUNCTION) + \
                                     ::rtl::OUString::createFromAscii(",\n"m), \
                                     ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >(), \
                                     0 )

#define ENSURE_AND_THROW(c, m)   if( !(c) )                                                     \
                                     throw ::com::sun::star::uno::RuntimeException( \
                                     ::rtl::OUString::createFromAscii(BOOST_CURRENT_FUNCTION) + \
                                     ::rtl::OUString::createFromAscii(",\n"m), \
                                     ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >() )

#define ENSURE_AND_RETURN(c, m)  if( !(c) )                                                     \
                                     return false

#endif

// shared_ptr debugging
// --------------------

#ifdef BOOST_SP_ENABLE_DEBUG_HOOKS

#include <boost/shared_ptr.hpp>

::std::size_t find_unreachable_objects( bool );

#ifdef VERBOSE
#define SHARED_PTR_LEFTOVERS(a) OSL_TRACE( "%s\n%s: Unreachable objects still use %d bytes", \
                                           BOOST_CURRENT_FUNCTION, a, \
                                           find_unreachable_objects(true) )
#else
/** This macro shows how much memory is still used by shared_ptrs

    Use this macro at places in the code where normally all shared_ptr
    objects should have been deleted. You'll get the number of bytes
    still contained in those objects, which quite possibly are prevented
    from deletion by circular references.
 */
#define SHARED_PTR_LEFTOVERS(a) OSL_TRACE( "%s\n%s: Unreachable objects still use %d bytes", \
                                           BOOST_CURRENT_FUNCTION, a, \
                                           find_unreachable_objects(false) )
#endif

#else

#define SHARED_PTR_LEFTOVERS(a) ((void)0)

#endif

#endif // ! defined(INCLUDED_CANVAS_DEBUG_HXX)
<|endoftext|>


<commit_before>/*
** Author(s):
**  - Cedric GESTES <gestes@aldebaran-robotics.com>
**
** Copyright (C) 2010, 2012 Aldebaran Robotics
*/

#include <iostream>
#include <string>
#include <map>

#include <qi/os.hpp>
#include <qi/application.hpp>
#include <qimessaging/session.hpp>

#include <boost/program_options.hpp>

namespace po = boost::program_options;

void call(const std::string &addr)
{
  qi::Session session;
  session.connect(addr);

#if 0
  std::vector<qi::ServiceInfo> servs = session.services();
  std::cout << "available services:" << std::endl;
  for (unsigned int i = 0; i < servs.size(); ++i)
    std::cout << "* " << servs[i].name() << std::endl;
  std::cout << std::endl;
#endif

  qi::Future<qi::ObjectPtr> fut = session.service("serviceTest");
  fut.wait();
  if (fut.hasError())
  {
      std::cerr << "Error returned:" << fut.error() << std::endl;
      return;
  }

  qi::ObjectPtr obj = fut.value();
#if 0
  int i = 0;
  while (true) {
    std::string result = obj->call<std::string>("reply", "plaf");
    if (!( i % 1000))
      std::cout << "answer(" << i << "):" << result << std::endl;
    ++i;
  }
#endif
  std::string result = obj->call<std::string>("reply", "plaf");
  std::cout << "result:" << result << std::endl;

  session.close();
}

int main(int argc, char *argv[])
{
  qi::Application a(argc, argv);

  // declare the program options
  po::options_description desc("Usage:\n  qi-client masterAddress [options]\nOptions");
  desc.add_options()
      ("help", "Print this help.")
      ("master-address",
       po::value<std::string>()->default_value(std::string("tcp://127.0.0.1:5555")),
       "The master address");

  // allow master address to be specified as the first arg
  po::positional_options_description pos;
  pos.add("master-address", 1);

  // parse and store
  po::variables_map vm;
  try
  {
    po::store(po::command_line_parser(argc, argv).
              options(desc).positional(pos).run(), vm);
    po::notify(vm);

    if (vm.count("help"))
    {
      std::cout << desc << std::endl;
      return 0;
    }

    if (vm.count("master-address") == 1)
    {
      std::string masteraddr = vm["master-address"].as<std::string>();
      call(masteraddr);
    }
    else
    {
      std::cout << desc << std::endl;
    }
  } catch (const boost::program_options::error&) {
    std::cout << desc << std::endl;
  }

  return 0;
}
<commit_msg>qi-client: support --loop <count><commit_after>/*
** Author(s):
**  - Cedric GESTES <gestes@aldebaran-robotics.com>
**
** Copyright (C) 2010, 2012 Aldebaran Robotics
*/

#include <iostream>
#include <string>
#include <map>

#include <qi/os.hpp>
#include <qi/application.hpp>
#include <qimessaging/session.hpp>

#include <boost/program_options.hpp>

namespace po = boost::program_options;

void call(int count, const std::string &addr)
{
  qi::Session session;
  session.connect(addr);

#if 0
  std::vector<qi::ServiceInfo> servs = session.services();
  std::cout << "available services:" << std::endl;
  for (unsigned int i = 0; i < servs.size(); ++i)
    std::cout << "* " << servs[i].name() << std::endl;
  std::cout << std::endl;
#endif

  qi::Future<qi::ObjectPtr> fut = session.service("serviceTest");
  fut.wait();
  if (fut.hasError())
  {
    std::cerr << "Error returned:" << fut.error() << std::endl;
    return;
  }

  qi::ObjectPtr obj = fut.value();
#if 0
  int i = 0;
  while (true) {
    std::string result = obj->call<std::string>("reply", "plaf");
    if (!( i % 1000))
      std::cout << "answer(" << i << "):" << result << std::endl;
    ++i;
  }
#endif
  for (int i = 0; i < count; ++i) {
    std::string result = obj->call<std::string>("reply", "plaf");
    std::cout << "result" << i << ":" << result << std::endl;
  }
  session.close();
}

int main(int argc, char *argv[])
{
  qi::Application a(argc, argv);

  // declare the program options
  po::options_description desc("Usage:\n  qi-client masterAddress [options]\nOptions");
  desc.add_options()
      ("help", "Print this help.")
      ("master-address",
       po::value<std::string>()->default_value(std::string("tcp://127.0.0.1:5555")),
       "The master address")
      ("loop", po::value<int>()->default_value(1), "loop count");

  // allow master address to be specified as the first arg
  po::positional_options_description pos;
  pos.add("master-address", 1);

  // parse and store
  po::variables_map vm;
  try
  {
    po::store(po::command_line_parser(argc, argv).
              options(desc).positional(pos).run(), vm);
    po::notify(vm);

    if (vm.count("help"))
    {
      std::cout << desc << std::endl;
      return 0;
    }

    if (vm.count("master-address") == 1)
    {
      std::string masteraddr = vm["master-address"].as<std::string>();

      call(vm["loop"].as<int>(), masteraddr);
    }
    else
    {
      std::cout << desc << std::endl;
    }
  } catch (const boost::program_options::error&) {
    std::cout << desc << std::endl;
  }

  return 0;
}
<|endoftext|>