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

#include <tntdb/postgresql/impl/statement.h>
#include <tntdb/postgresql/impl/connection.h>
#include <tntdb/postgresql/impl/result.h>
#include <tntdb/postgresql/impl/cursor.h>
#include <tntdb/postgresql/error.h>
#include <tntdb/bits/result.h>
#include <tntdb/bits/row.h>
#include <tntdb/bits/value.h>
#include <tntdb/stmtparser.h>
#include <sstream>
#include <cxxtools/dynbuffer.h>
#include <cxxtools/log.h>
#include "config.h"

log_define("tntdb.postgresql.statement")

#ifdef HAVE_PQPREPARE
#  define SET_TYPE(pos, type)
#else
#  define SET_TYPE(pos, type)  setType(pos, type)
#endif

namespace tntdb
{
  namespace postgresql
  {
    typedef std::map<std::string, unsigned> hostvarMapType;

    namespace
    {
      class SE : public StmtEvent
      {
          hostvarMapType& hostvarMap;
          unsigned idx;

        public:
          SE(hostvarMapType& hm)
            : hostvarMap(hm),
              idx(0)
            { }
          std::string onHostVar(const std::string& name);
          unsigned getMaxIdx() const  { return idx; }
      };

      std::string SE::onHostVar(const std::string& name)
      {
        unsigned n;

        hostvarMapType::const_iterator it = hostvarMap.find(name);
        if (it == hostvarMap.end())
        {
          n = idx++;
          hostvarMap[name] = n;
        }
        else
          n = it->second;

        log_debug("hostvar :" << name << " => $" << (n + 1));

        std::ostringstream r;
        r << '$' << (n + 1);
        return r.str();
      }
    }

    Statement::Statement(Connection* conn_, const std::string& query_)
      : conn(conn_)
    {
      // parse hostvars
      StmtParser parser;
      SE se(hostvarMap);
      parser.parse(query_, se);

      values.resize(se.getMaxIdx());

      query = parser.getSql();

      paramValues.reserve(se.getMaxIdx());
      paramLengths.reserve(se.getMaxIdx());
      paramFormats.reserve(se.getMaxIdx());
    }

    Statement::~Statement()
    {
      if (!stmtName.empty())
      {
        std::string sql = "DEALLOCATE " + stmtName;

        log_debug("PQexec(" << getPGConn() << ", \"" << sql << "\")");
        PGresult* result = PQexec(getPGConn(), sql.c_str());

        if (isError(result))
          log_error("error deallocating statement: " << PQresultErrorMessage(result));

        log_debug("PQclear(" << result << ')');
        PQclear(result);
      }
    }

    void Statement::doPrepare()
    {
      // create statementname
      std::ostringstream s;
      s << "tntdbstmt" << this;

      // prepare statement
#ifdef HAVE_PQPREPARE
      log_debug("PQprepare(" << getPGConn() << ", \"" << s.str()
        << "\", \"" << query << "\", 0, 0)");
      PGresult* result = PQprepare(getPGConn(),
        s.str().c_str(), query.c_str(), 0, 0);

      if (isError(result))
      {
        log_error(PQresultErrorMessage(result));
        throw PgSqlError(query, "PQprepare", result, true);
      }
#else
      std::ostringstream sql;
      sql << "PREPARE " << s.str();
      for (valuesType::const_iterator it = values.begin(); it != values.end(); ++it)
        sql << (it == values.begin() ? " (" : ", " ) << it->getType();
      if (!values.empty())
        sql << ')';
      sql << " AS " << query;

      log_debug("PQexec(" << getPGConn() << ", \"" << sql.str() << "\")");
      PGresult* result = PQexec(getPGConn(), sql.str().c_str());

      if (isError(result))
      {
        log_error(PQresultErrorMessage(result));
        throw PgSqlError(sql.str(), "PQexec", result, true);
      }
#endif

      stmtName = s.str();

      log_debug("PQclear(" << result << ')');
      PQclear(result);
    }

    PGresult* Statement::execPrepared()
    {
      if (stmtName.empty())
        doPrepare();

      log_debug("PQexecPrepared(" << getPGConn() << ", \"" << stmtName
        << "\", " << values.size() << ", paramValues, paramLengths, paramFormats, 0)");
      PGresult* result = PQexecPrepared(getPGConn(), stmtName.c_str(),
        getNParams(), getParamValues(), getParamLengths(), getParamFormats(), 0);

      if (isError(result))
      {
        log_error(PQresultErrorMessage(result));
        throw PgSqlError(query, "PQexecPrepared", result, true);
      }

      return result;
    }

    template <typename T>
    void Statement::setValue(const std::string& col, T data)
    {
      hostvarMapType::const_iterator it = hostvarMap.find(col);
      if (it == hostvarMap.end())
        log_warn("hostvariable :" << col << " not found");
      else
      {
        std::ostringstream v;
        v << data;
        values[it->second].setValue(v.str());
        paramFormats[it->second] = 0;
      }
    }

    template <>
    void Statement::setValue(const std::string& col, float data)
    {
      hostvarMapType::const_iterator it = hostvarMap.find(col);
      if (it == hostvarMap.end())
        log_warn("hostvariable :" << col << " not found");
      else
      {
        std::ostringstream v;
        v.precision(24);
        v << data;
        values[it->second].setValue(v.str());
        paramFormats[it->second] = 0;
      }
    }

    template <>
    void Statement::setValue(const std::string& col, double data)
    {
      hostvarMapType::const_iterator it = hostvarMap.find(col);
      if (it == hostvarMap.end())
        log_warn("hostvariable :" << col << " not found");
      else
      {
        std::ostringstream v;
        v.precision(24);
        v << data;
        values[it->second].setValue(v.str());
        paramFormats[it->second] = 0;
      }
    }

    template <>
    void Statement::setValue(const std::string& col, Decimal data)
    {
      hostvarMapType::const_iterator it = hostvarMap.find(col);
      if (it == hostvarMap.end())
        log_warn("hostvariable :" << col << " not found");
      else
      {
        std::ostringstream v;
        v.precision(24);
        v << data;
        values[it->second].setValue(v.str());
        paramFormats[it->second] = 0;
      }
    }

    template <typename T>
    void Statement::setStringValue(const std::string& col, T data, bool binary)
    {
      hostvarMapType::const_iterator it = hostvarMap.find(col);
      if (it == hostvarMap.end())
        log_warn("hostvariable :" << col << " not found");
      else
      {
        values[it->second].setValue(data);
        paramFormats[it->second] = binary;
      }
    }

    template <typename T>
    void Statement::setIsoValue(const std::string& col, T data)
    {
      hostvarMapType::const_iterator it = hostvarMap.find(col);
      if (it == hostvarMap.end())
        log_warn("hostvariable :" << col << " not found");
      else
      {
        values[it->second].setValue(data.getIso());
        paramFormats[it->second] = 0;
      }
    }

#ifndef HAVE_PQPREPARE
    void Statement::setType(const std::string& col, const std::string& type)
    {
      hostvarMapType::const_iterator it = hostvarMap.find(col);
      if (it != hostvarMap.end())
        values[it->second].setType(type);
    }
#endif

    void Statement::clear()
    {
      log_debug("clear()");
      for (valuesType::iterator it = values.begin(); it != values.end(); ++it)
        it->setNull();
    }

    void Statement::setNull(const std::string& col)
    {
      log_debug("setNull(\"" << col << "\")");

      hostvarMapType::const_iterator it = hostvarMap.find(col);
      if (it == hostvarMap.end())
        log_warn("hostvariable :" << col << " not found");
      else
        values[it->second].setNull();
    }

    void Statement::setBool(const std::string& col, bool data)
    {
      log_debug("setBool(\"" << col << "\", " << data << ')');

      hostvarMapType::const_iterator it = hostvarMap.find(col);
      if (it == hostvarMap.end())
        log_warn("hostvariable :" << col << " not found");
      else
        values[it->second].setValue(data ? "T" : "F");

      SET_TYPE(col, "bool");
    }

    void Statement::setInt(const std::string& col, int data)
    {
      log_debug("setInt(\"" << col << "\", " << data << ')');
      setValue(col, data);
      SET_TYPE(col, "int");
    }

    void Statement::setUnsigned(const std::string& col, unsigned data)
    {
      log_debug("setUnsigned(\"" << col << "\", " << data << ')');
      setValue(col, data);
      SET_TYPE(col, "int");
    }

    void Statement::setInt32(const std::string& col, int32_t data)
    {
      log_debug("setInt32(\"" << col << "\", " << data << ')');
      setValue(col, data);
      SET_TYPE(col, "int");
    }

    void Statement::setUnsigned32(const std::string& col, uint32_t data)
    {
      log_debug("setUnsigned32(\"" << col << "\", " << data << ')');
      setValue(col, data);
      SET_TYPE(col, "int");
    }

    void Statement::setInt64(const std::string& col, int64_t data)
    {
      log_debug("setInt64(\"" << col << "\", " << data << ')');
      setValue(col, data);
      SET_TYPE(col, "bigint");
    }

    void Statement::setUnsigned64(const std::string& col, uint64_t data)
    {
      log_debug("setUnsigned64(\"" << col << "\", " << data << ')');
      setValue(col, data);
      SET_TYPE(col, "bigint");
    }

    void Statement::setDecimal(const std::string& col, const Decimal& data)
    {
      log_debug("setDecimal(\"" << col << "\", " << data << ')');
      setValue(col, data);
      SET_TYPE(col, "numeric");
    }

    void Statement::setFloat(const std::string& col, float data)
    {
      log_debug("setFloat(\"" << col << "\", " << data << ')');
      setValue(col, data);
      SET_TYPE(col, "numeric");
    }

    void Statement::setDouble(const std::string& col, double data)
    {
      log_debug("setDouble(\"" << col << "\", " << data << ')');
      setValue(col, data);
      SET_TYPE(col, "numeric");
    }

    void Statement::setChar(const std::string& col, char data)
    {
      log_debug("setChar(\"" << col << "\", '" << data << "')");
      setStringValue(col, std::string(1, data));
      SET_TYPE(col, "text");
    }

    void Statement::setString(const std::string& col, const std::string& data)
    {
      log_debug("setString(\"" << col << "\", \"" << data << "\")");
      setStringValue(col, data);
      SET_TYPE(col, "text");
    }

    void Statement::setBlob(const std::string& col, const Blob& data)
    {
      log_debug("setBlob(\"" << col << "\", Blob)");
      setStringValue(col, std::string(data.data(), data.size()), true);
      SET_TYPE(col, "blob");
    }

    void Statement::setDate(const std::string& col, const Date& data)
    {
      log_debug("setDate(\"" << col << "\", " << data.getIso() << ')');
      setIsoValue(col, data);
      SET_TYPE(col, "date");
    }

    void Statement::setTime(const std::string& col, const Time& data)
    {
      log_debug("setTime(\"" << col << "\", " << data.getIso() << ')');
      setIsoValue(col, data);
      SET_TYPE(col, "time");
    }

    void Statement::setDatetime(const std::string& col, const Datetime& data)
    {
      log_debug("setDatetime(\"" << col << "\", " << data.getIso() << ')');
      setIsoValue(col, data);
      SET_TYPE(col, "datetime");
    }

    Statement::size_type Statement::execute()
    {
      log_debug("execute()");

      PGresult* result = execPrepared();

      std::istringstream tuples(PQcmdTuples(result));
      unsigned ret = 0;
      tuples >> ret;

      log_debug("PQclear(" << result << ')');
      PQclear(result);

      return ret;
    }

    tntdb::Result Statement::select()
    {
      log_debug("select()");
      PGresult* result = execPrepared();
      return tntdb::Result(new Result(tntdb::Connection(conn), result));
    }

    tntdb::Row Statement::selectRow()
    {
      tntdb::Result result = select();

      if (result.size() <= 0)
        throw NotFound();

      return result[0];
    }

    tntdb::Value Statement::selectValue()
    {
      tntdb::Result result = select();

      if (result.size() <= 0)
        throw NotFound();

      return result[0][0];
    }

    ICursor* Statement::createCursor(unsigned fetchsize)
    {
      return new Cursor(this, fetchsize);
    }

    const char* const* Statement::getParamValues()
    {
      for (unsigned n = 0; n < values.size(); ++n)
        paramValues[n] = values[n].getValue();
      return paramValues.data();
    }

    const int* Statement::getParamLengths()
    {
      for (unsigned n = 0; n < values.size(); ++n)
        paramLengths[n] = values[n].getLength();
      return paramLengths.data();
    }

    PGconn* Statement::getPGConn()
    {
      return conn->getPGConn();
    }
  }
}
<commit_msg>fix Statement::setBool in postgresql driver<commit_after>/*
 * Copyright (C) 2005 Tommi Maekitalo
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <tntdb/postgresql/impl/statement.h>
#include <tntdb/postgresql/impl/connection.h>
#include <tntdb/postgresql/impl/result.h>
#include <tntdb/postgresql/impl/cursor.h>
#include <tntdb/postgresql/error.h>
#include <tntdb/bits/result.h>
#include <tntdb/bits/row.h>
#include <tntdb/bits/value.h>
#include <tntdb/stmtparser.h>
#include <sstream>
#include <cxxtools/dynbuffer.h>
#include <cxxtools/log.h>
#include "config.h"

log_define("tntdb.postgresql.statement")

#ifdef HAVE_PQPREPARE
#  define SET_TYPE(pos, type)
#else
#  define SET_TYPE(pos, type)  setType(pos, type)
#endif

namespace tntdb
{
  namespace postgresql
  {
    typedef std::map<std::string, unsigned> hostvarMapType;

    namespace
    {
      class SE : public StmtEvent
      {
          hostvarMapType& hostvarMap;
          unsigned idx;

        public:
          SE(hostvarMapType& hm)
            : hostvarMap(hm),
              idx(0)
            { }
          std::string onHostVar(const std::string& name);
          unsigned getMaxIdx() const  { return idx; }
      };

      std::string SE::onHostVar(const std::string& name)
      {
        unsigned n;

        hostvarMapType::const_iterator it = hostvarMap.find(name);
        if (it == hostvarMap.end())
        {
          n = idx++;
          hostvarMap[name] = n;
        }
        else
          n = it->second;

        log_debug("hostvar :" << name << " => $" << (n + 1));

        std::ostringstream r;
        r << '$' << (n + 1);
        return r.str();
      }
    }

    Statement::Statement(Connection* conn_, const std::string& query_)
      : conn(conn_)
    {
      // parse hostvars
      StmtParser parser;
      SE se(hostvarMap);
      parser.parse(query_, se);

      values.resize(se.getMaxIdx());

      query = parser.getSql();

      paramValues.reserve(se.getMaxIdx());
      paramLengths.reserve(se.getMaxIdx());
      paramFormats.reserve(se.getMaxIdx());
    }

    Statement::~Statement()
    {
      if (!stmtName.empty())
      {
        std::string sql = "DEALLOCATE " + stmtName;

        log_debug("PQexec(" << getPGConn() << ", \"" << sql << "\")");
        PGresult* result = PQexec(getPGConn(), sql.c_str());

        if (isError(result))
          log_error("error deallocating statement: " << PQresultErrorMessage(result));

        log_debug("PQclear(" << result << ')');
        PQclear(result);
      }
    }

    void Statement::doPrepare()
    {
      // create statementname
      std::ostringstream s;
      s << "tntdbstmt" << this;

      // prepare statement
#ifdef HAVE_PQPREPARE
      log_debug("PQprepare(" << getPGConn() << ", \"" << s.str()
        << "\", \"" << query << "\", 0, 0)");
      PGresult* result = PQprepare(getPGConn(),
        s.str().c_str(), query.c_str(), 0, 0);

      if (isError(result))
      {
        log_error(PQresultErrorMessage(result));
        throw PgSqlError(query, "PQprepare", result, true);
      }
#else
      std::ostringstream sql;
      sql << "PREPARE " << s.str();
      for (valuesType::const_iterator it = values.begin(); it != values.end(); ++it)
        sql << (it == values.begin() ? " (" : ", " ) << it->getType();
      if (!values.empty())
        sql << ')';
      sql << " AS " << query;

      log_debug("PQexec(" << getPGConn() << ", \"" << sql.str() << "\")");
      PGresult* result = PQexec(getPGConn(), sql.str().c_str());

      if (isError(result))
      {
        log_error(PQresultErrorMessage(result));
        throw PgSqlError(sql.str(), "PQexec", result, true);
      }
#endif

      stmtName = s.str();

      log_debug("PQclear(" << result << ')');
      PQclear(result);
    }

    PGresult* Statement::execPrepared()
    {
      if (stmtName.empty())
        doPrepare();

      log_debug("PQexecPrepared(" << getPGConn() << ", \"" << stmtName
        << "\", " << values.size() << ", paramValues, paramLengths, paramFormats, 0)");
      PGresult* result = PQexecPrepared(getPGConn(), stmtName.c_str(),
        getNParams(), getParamValues(), getParamLengths(), getParamFormats(), 0);

      if (isError(result))
      {
        log_error(PQresultErrorMessage(result));
        throw PgSqlError(query, "PQexecPrepared", result, true);
      }

      return result;
    }

    template <typename T>
    void Statement::setValue(const std::string& col, T data)
    {
      hostvarMapType::const_iterator it = hostvarMap.find(col);
      if (it == hostvarMap.end())
        log_warn("hostvariable :" << col << " not found");
      else
      {
        std::ostringstream v;
        v << data;
        values[it->second].setValue(v.str());
        paramFormats[it->second] = 0;
      }
    }

    template <>
    void Statement::setValue(const std::string& col, float data)
    {
      hostvarMapType::const_iterator it = hostvarMap.find(col);
      if (it == hostvarMap.end())
        log_warn("hostvariable :" << col << " not found");
      else
      {
        std::ostringstream v;
        v.precision(24);
        v << data;
        values[it->second].setValue(v.str());
        paramFormats[it->second] = 0;
      }
    }

    template <>
    void Statement::setValue(const std::string& col, double data)
    {
      hostvarMapType::const_iterator it = hostvarMap.find(col);
      if (it == hostvarMap.end())
        log_warn("hostvariable :" << col << " not found");
      else
      {
        std::ostringstream v;
        v.precision(24);
        v << data;
        values[it->second].setValue(v.str());
        paramFormats[it->second] = 0;
      }
    }

    template <>
    void Statement::setValue(const std::string& col, Decimal data)
    {
      hostvarMapType::const_iterator it = hostvarMap.find(col);
      if (it == hostvarMap.end())
        log_warn("hostvariable :" << col << " not found");
      else
      {
        std::ostringstream v;
        v.precision(24);
        v << data;
        values[it->second].setValue(v.str());
        paramFormats[it->second] = 0;
      }
    }

    template <typename T>
    void Statement::setStringValue(const std::string& col, T data, bool binary)
    {
      hostvarMapType::const_iterator it = hostvarMap.find(col);
      if (it == hostvarMap.end())
        log_warn("hostvariable :" << col << " not found");
      else
      {
        values[it->second].setValue(data);
        paramFormats[it->second] = binary;
      }
    }

    template <typename T>
    void Statement::setIsoValue(const std::string& col, T data)
    {
      hostvarMapType::const_iterator it = hostvarMap.find(col);
      if (it == hostvarMap.end())
        log_warn("hostvariable :" << col << " not found");
      else
      {
        values[it->second].setValue(data.getIso());
        paramFormats[it->second] = 0;
      }
    }

#ifndef HAVE_PQPREPARE
    void Statement::setType(const std::string& col, const std::string& type)
    {
      hostvarMapType::const_iterator it = hostvarMap.find(col);
      if (it != hostvarMap.end())
        values[it->second].setType(type);
    }
#endif

    void Statement::clear()
    {
      log_debug("clear()");
      for (valuesType::iterator it = values.begin(); it != values.end(); ++it)
        it->setNull();
    }

    void Statement::setNull(const std::string& col)
    {
      log_debug("setNull(\"" << col << "\")");

      hostvarMapType::const_iterator it = hostvarMap.find(col);
      if (it == hostvarMap.end())
        log_warn("hostvariable :" << col << " not found");
      else
      {
        values[it->second].setNull();
        paramFormats[it->second] = 0;
      }
    }

    void Statement::setBool(const std::string& col, bool data)
    {
      log_debug("setBool(\"" << col << "\", " << data << ')');

      hostvarMapType::const_iterator it = hostvarMap.find(col);
      if (it == hostvarMap.end())
        log_warn("hostvariable :" << col << " not found");
      else
      {
        values[it->second].setValue(data ? "T" : "F");
        paramFormats[it->second] = 0;
      }

      SET_TYPE(col, "bool");
    }

    void Statement::setInt(const std::string& col, int data)
    {
      log_debug("setInt(\"" << col << "\", " << data << ')');
      setValue(col, data);
      SET_TYPE(col, "int");
    }

    void Statement::setUnsigned(const std::string& col, unsigned data)
    {
      log_debug("setUnsigned(\"" << col << "\", " << data << ')');
      setValue(col, data);
      SET_TYPE(col, "int");
    }

    void Statement::setInt32(const std::string& col, int32_t data)
    {
      log_debug("setInt32(\"" << col << "\", " << data << ')');
      setValue(col, data);
      SET_TYPE(col, "int");
    }

    void Statement::setUnsigned32(const std::string& col, uint32_t data)
    {
      log_debug("setUnsigned32(\"" << col << "\", " << data << ')');
      setValue(col, data);
      SET_TYPE(col, "int");
    }

    void Statement::setInt64(const std::string& col, int64_t data)
    {
      log_debug("setInt64(\"" << col << "\", " << data << ')');
      setValue(col, data);
      SET_TYPE(col, "bigint");
    }

    void Statement::setUnsigned64(const std::string& col, uint64_t data)
    {
      log_debug("setUnsigned64(\"" << col << "\", " << data << ')');
      setValue(col, data);
      SET_TYPE(col, "bigint");
    }

    void Statement::setDecimal(const std::string& col, const Decimal& data)
    {
      log_debug("setDecimal(\"" << col << "\", " << data << ')');
      setValue(col, data);
      SET_TYPE(col, "numeric");
    }

    void Statement::setFloat(const std::string& col, float data)
    {
      log_debug("setFloat(\"" << col << "\", " << data << ')');
      setValue(col, data);
      SET_TYPE(col, "numeric");
    }

    void Statement::setDouble(const std::string& col, double data)
    {
      log_debug("setDouble(\"" << col << "\", " << data << ')');
      setValue(col, data);
      SET_TYPE(col, "numeric");
    }

    void Statement::setChar(const std::string& col, char data)
    {
      log_debug("setChar(\"" << col << "\", '" << data << "')");
      setStringValue(col, std::string(1, data));
      SET_TYPE(col, "text");
    }

    void Statement::setString(const std::string& col, const std::string& data)
    {
      log_debug("setString(\"" << col << "\", \"" << data << "\")");
      setStringValue(col, data);
      SET_TYPE(col, "text");
    }

    void Statement::setBlob(const std::string& col, const Blob& data)
    {
      log_debug("setBlob(\"" << col << "\", Blob)");
      setStringValue(col, std::string(data.data(), data.size()), true);
      SET_TYPE(col, "blob");
    }

    void Statement::setDate(const std::string& col, const Date& data)
    {
      log_debug("setDate(\"" << col << "\", " << data.getIso() << ')');
      setIsoValue(col, data);
      SET_TYPE(col, "date");
    }

    void Statement::setTime(const std::string& col, const Time& data)
    {
      log_debug("setTime(\"" << col << "\", " << data.getIso() << ')');
      setIsoValue(col, data);
      SET_TYPE(col, "time");
    }

    void Statement::setDatetime(const std::string& col, const Datetime& data)
    {
      log_debug("setDatetime(\"" << col << "\", " << data.getIso() << ')');
      setIsoValue(col, data);
      SET_TYPE(col, "datetime");
    }

    Statement::size_type Statement::execute()
    {
      log_debug("execute()");

      PGresult* result = execPrepared();

      std::istringstream tuples(PQcmdTuples(result));
      unsigned ret = 0;
      tuples >> ret;

      log_debug("PQclear(" << result << ')');
      PQclear(result);

      return ret;
    }

    tntdb::Result Statement::select()
    {
      log_debug("select()");
      PGresult* result = execPrepared();
      return tntdb::Result(new Result(tntdb::Connection(conn), result));
    }

    tntdb::Row Statement::selectRow()
    {
      tntdb::Result result = select();

      if (result.size() <= 0)
        throw NotFound();

      return result[0];
    }

    tntdb::Value Statement::selectValue()
    {
      tntdb::Result result = select();

      if (result.size() <= 0)
        throw NotFound();

      return result[0][0];
    }

    ICursor* Statement::createCursor(unsigned fetchsize)
    {
      return new Cursor(this, fetchsize);
    }

    const char* const* Statement::getParamValues()
    {
      for (unsigned n = 0; n < values.size(); ++n)
        paramValues[n] = values[n].getValue();
      return paramValues.data();
    }

    const int* Statement::getParamLengths()
    {
      for (unsigned n = 0; n < values.size(); ++n)
        paramLengths[n] = values[n].getLength();
      return paramLengths.data();
    }

    PGconn* Statement::getPGConn()
    {
      return conn->getPGConn();
    }
  }
}
<|endoftext|>


<commit_before>//script drawing a detector geometry (here ALICE)
//by default the geometry is drawn using the GL viewer
//Using the TBrowser, you can select other components
//if the file containing the geometry is not found in the local
//directory, it is automatically read from the ROOT web site.
// Author: Rene Brun

void geomAlice() {
{
   if (!gSystem->AccessPathName("alice.root")) {
      TGeoManager::Import("alice.root");
   } else {
      printf("accessing geometry file from http://root.cern.ch/files\n");
      TGeoManager::Import("http://root.cern.ch/files/alice.root");
   }
   //gGeoManager->DefaultColors();
   gGeoManager->GetVolume("HUFL")->InvisibleAll();
   gGeoManager->GetVolume("HUWA")->InvisibleAll();
   gGeoManager->GetVolume("ITSV")->InvisibleAll();
   gGeoManager->GetVolume("ZDC")->InvisibleAll();
   gGeoManager->GetVolume("ZEM")->InvisibleAll();
   gGeoManager->GetVolume("XEN1")->InvisibleAll();
   gGeoManager->GetVolume("HBW1")->InvisibleAll();
   gGeoManager->GetVolume("HHW1")->InvisibleAll();
   gGeoManager->GetVolume("HHW3")->InvisibleAll();
   gGeoManager->GetVolume("HHW2")->InvisibleAll();
   gGeoManager->GetVolume("HHF1")->InvisibleAll();
   gGeoManager->GetVolume("HHF2")->InvisibleAll();
   gGeoManager->GetVolume("HPIL")->InvisibleAll();
   gGeoManager->GetVolume("HMBS")->InvisibleAll();
   gGeoManager->GetVolume("HHC1")->InvisibleAll();
   gGeoManager->GetVolume("L3MO")->InvisibleAll();
   gGeoManager->GetVolume("DY1")->SetTransparency(90);
   gGeoManager->GetVolume("DY2")->SetTransparency(90);
   gGeoManager->GetVolume("DY11")->SetTransparency(70);
   gGeoManager->GetVolume("DY22")->SetTransparency(70);
   gGeoManager->GetVolume("L3IR")->SetTransparency(100);
   gGeoManager->GetVolume("ALIC")->Draw("ogl");
   new TBrowser;
}
<commit_msg>Fix typo<commit_after>//script drawing a detector geometry (here ALICE)
//by default the geometry is drawn using the GL viewer
//Using the TBrowser, you can select other components
//if the file containing the geometry is not found in the local
//directory, it is automatically read from the ROOT web site.
// Author: Rene Brun

void geomAlice()
{
   if (!gSystem->AccessPathName("alice.root")) {
      TGeoManager::Import("alice.root");
   } else {
      printf("accessing geometry file from http://root.cern.ch/files\n");
      TGeoManager::Import("http://root.cern.ch/files/alice.root");
   }
   //gGeoManager->DefaultColors();
   gGeoManager->GetVolume("HUFL")->InvisibleAll();
   gGeoManager->GetVolume("HUWA")->InvisibleAll();
   gGeoManager->GetVolume("ITSV")->InvisibleAll();
   gGeoManager->GetVolume("ZDC")->InvisibleAll();
   gGeoManager->GetVolume("ZEM")->InvisibleAll();
   gGeoManager->GetVolume("XEN1")->InvisibleAll();
   gGeoManager->GetVolume("HBW1")->InvisibleAll();
   gGeoManager->GetVolume("HHW1")->InvisibleAll();
   gGeoManager->GetVolume("HHW3")->InvisibleAll();
   gGeoManager->GetVolume("HHW2")->InvisibleAll();
   gGeoManager->GetVolume("HHF1")->InvisibleAll();
   gGeoManager->GetVolume("HHF2")->InvisibleAll();
   gGeoManager->GetVolume("HPIL")->InvisibleAll();
   gGeoManager->GetVolume("HMBS")->InvisibleAll();
   gGeoManager->GetVolume("HHC1")->InvisibleAll();
   gGeoManager->GetVolume("L3MO")->InvisibleAll();
   gGeoManager->GetVolume("DY1")->SetTransparency(90);
   gGeoManager->GetVolume("DY2")->SetTransparency(90);
   gGeoManager->GetVolume("DY11")->SetTransparency(70);
   gGeoManager->GetVolume("DY22")->SetTransparency(70);
   gGeoManager->GetVolume("ALIC")->Draw("ogl");
   new TBrowser;
}
<|endoftext|>


<commit_before>#include <ros/ros.h>
#include <move_base_msgs/MoveBaseActionGoal.h>
#include <stdlib.h>
#include <tf/transform_listener.h>
#include <tf2_msgs/TFMessage.h>
#include <geometry_msgs/PointStamped.h>
#include <geometry_msgs/PoseStamped.h>

#include <string>

class OrneSay{
public:
    OrneSay(){
		tf_sub = nh.subscribe("/tf",1,&OrneSay::TfCallback,this);
		nh.param("robto_frame", robot_frame, std::string("/base_link"));
		nh.param("world_frame", world_frame, std::string("/map"));
		nh.param("arrived_rad", arrived_rad, 1.0);
		sound_flag = false;
    }
    void goalCallback(const move_base_msgs::MoveBaseActionGoal::ConstPtr& msg);
    void TfCallback(const tf2_msgs::TFMessage &tf);
private:
    ros::NodeHandle nh;
    ros::Subscriber wp_sub = nh.subscribe("/move_base/goal", 1, &OrneSay::goalCallback, this);

	std::string world_frame_;
	ros::Subscriber tf_sub;
	geometry_msgs::PoseStamped pose_t;
	geometry_msgs::PoseStamped goal position;

	tf::TransformListener tf_listener;
	std::string world_frame;
	std::string robot_frame;

	double arrived_rad;
	bool sound_flag;
};

void OrneSay::goalCallback(const move_base_msgs::MoveBaseActionGoal::ConstPtr& msg){
	goal_position.pose.position.x = msg->goal.target_pose.pose.position.x;
	goal_position.pose.position.y = msg->goal.target_pose.pose.position.y ;
	goal_position.pose.position.z = 0;

	sound_flag = true;
}

void OrneSay::TfCallback(const tf2_msgs::TFMessage &tf){
	tf::StampedTransform robot_gl;
	try{
		tf_listener.lookupTransform(world_frame, robot_frame, ros::Time(0.0), robot_gl);

		pose_t.pose.position.x = robot_gl.getOrigin().x();
		pose_t.pose.position.y = robot_gl.getOrigin().y();
		pose_t.pose.position.z = 0;

		double dis =sqrt((pose_t.pose.position.x - goal_position.pose.position.x) * (pose_t.pose.position.x - goal_position.pose.position.x)
 						+(pose_t.pose.position.y - goal_position.pose.position.y) * (pose_t.pose.position.y - goal_position.pose.position.y));
		//ROS_INFO("%lf\t %lf\t %lf \t %lf",pose_t.pose.position.x, pose_t.pose.position.y, goal_position.pose.position.x, goal_position.pose.position.y);

		if(dis < arrived_rad && sound_flag){
			char *command = "aplay ~/catkin_ws/src/orne_navigation/orne_say/sound/pekowave1.wav";
			int system_res = system(command);
			ROS_INFO("arrived way point");
			sound_flag = false;
		}

	}catch(tf::TransformException &e){
		ROS_WARN_STREAM(e.what());
	}
}

int main(int argc, char *argv[]){
    ros::init(argc, argv, ROS_PACKAGE_NAME);
    OrneSay orne_say;
    while(ros::ok()){
        ros::spin();
    }
	return 0;
}
<commit_msg>インデント直し2<commit_after>#include <ros/ros.h>
#include <move_base_msgs/MoveBaseActionGoal.h>
#include <stdlib.h>
#include <tf/transform_listener.h>
#include <tf2_msgs/TFMessage.h>
#include <geometry_msgs/PointStamped.h>
#include <geometry_msgs/PoseStamped.h>

#include <string>

class OrneSay{
public:
	OrneSay(){
		tf_sub = nh.subscribe("/tf",1,&OrneSay::TfCallback,this);
		nh.param("robto_frame", robot_frame, std::string("/base_link"));
		nh.param("world_frame", world_frame, std::string("/map"));
		nh.param("arrived_rad", arrived_rad, 1.0);
		sound_flag = false;
	}
	void goalCallback(const move_base_msgs::MoveBaseActionGoal::ConstPtr& msg);
	void TfCallback(const tf2_msgs::TFMessage &tf);
private:
    ros::NodeHandle nh;
    ros::Subscriber wp_sub = nh.subscribe("/move_base/goal", 1, &OrneSay::goalCallback, this);

	std::string world_frame_;
	ros::Subscriber tf_sub;
	geometry_msgs::PoseStamped pose_t;
	geometry_msgs::PoseStamped goal position;

	tf::TransformListener tf_listener;
	std::string world_frame;
	std::string robot_frame;

	double arrived_rad;
	bool sound_flag;
};

void OrneSay::goalCallback(const move_base_msgs::MoveBaseActionGoal::ConstPtr& msg){
	goal_position.pose.position.x = msg->goal.target_pose.pose.position.x;
	goal_position.pose.position.y = msg->goal.target_pose.pose.position.y ;
	goal_position.pose.position.z = 0;

	sound_flag = true;
}

void OrneSay::TfCallback(const tf2_msgs::TFMessage &tf){
	tf::StampedTransform robot_gl;
	try{
		tf_listener.lookupTransform(world_frame, robot_frame, ros::Time(0.0), robot_gl);

		pose_t.pose.position.x = robot_gl.getOrigin().x();
		pose_t.pose.position.y = robot_gl.getOrigin().y();
		pose_t.pose.position.z = 0;

		double dis =sqrt((pose_t.pose.position.x - goal_position.pose.position.x) * (pose_t.pose.position.x - goal_position.pose.position.x)
 						+(pose_t.pose.position.y - goal_position.pose.position.y) * (pose_t.pose.position.y - goal_position.pose.position.y));
		//ROS_INFO("%lf\t %lf\t %lf \t %lf",pose_t.pose.position.x, pose_t.pose.position.y, goal_position.pose.position.x, goal_position.pose.position.y);

		if(dis < arrived_rad && sound_flag){
			char *command = "aplay ~/catkin_ws/src/orne_navigation/orne_say/sound/pekowave1.wav";
			int system_res = system(command);
			ROS_INFO("arrived way point");
			sound_flag = false;
		}

	}catch(tf::TransformException &e){
		ROS_WARN_STREAM(e.what());
	}
}

int main(int argc, char *argv[]){
    ros::init(argc, argv, ROS_PACKAGE_NAME);
    OrneSay orne_say;
    while(ros::ok()){
        ros::spin();
    }
	return 0;
}
<|endoftext|>


<commit_before>/* Copyright (c) 2013, AOYAMA Kazuharu
 * All rights reserved.
 *
 * This software may be used and distributed according to the terms of
 * the New BSD License, which is incorporated herein by reference.
 */

#include "mongoobjgenerator.h"
#include "global.h"
#include "projectfilegenerator.h"
#include "filewriter.h"
#include <QPair>
#include <QRegExp>
#include <unistd.h>

#define MONGOOBJECT_HEADER_TEMPLATE                                     \
    "#ifndef %1OBJECT_H\n"                                              \
    "#define %1OBJECT_H\n"                                              \
    "\n"                                                                \
    "#include <TMongoObject>\n"                                         \
    "#include <QSharedData>\n"                                          \
    "\n\n"                                                              \
    "class T_MODEL_EXPORT %2Object : public TMongoObject, public QSharedData\n" \
    "{\n"                                                               \
    "public:\n"                                                         \
    "%3"                                                                \
    "\n"                                                                \
    "    enum PropertyIndex {\n"                                        \
    "%4"                                                                \
    "    };\n"                                                          \
    "\n"                                                                \
    "    virtual QString collectionName() const { return \"%5\"; }\n"   \
    "    virtual QString objectId() const { return _id; }\n"            \
    "    virtual QString &objectId() { return _id; }\n"                 \
    "\n"                                                                \
    "private:\n"                                                        \
    "    Q_OBJECT\n"                                                    \
    "%6"                                                                \
    "};\n"                                                              \
    " \n"                                                               \
    "#endif // %1OBJECT_H"

#define MONGOOBJECT_HEADER_UPDATE_TEMPLATE                              \
    "%3\n"                                                              \
    "%4"                                                                \
    "\n"                                                                \
    "    enum PropertyIndex {\n"                                        \
    "%5"                                                                \
    "    };\n"                                                          \
    "\n"                                                                \
    "    virtual QString collectionName() const { return \"%2\"; }\n"   \
    "    virtual QString objectId() const { return _id; }\n"            \
    "    virtual QString &objectId() { return _id; }\n"                 \
    "\n"                                                                \
    "private:\n"                                                        \
    "    Q_OBJECT\n"                                                    \
    "%6"                                                                \
    "};\n"                                                              \
    " \n"                                                               \
    "#endif // %1OBJECT_H"

#define MONGOOBJECT_PROPERTY_TEMPLATE                \
    "    Q_PROPERTY(%1 %2 READ get%2 WRITE set%2)\n" \
    "    T_DEFINE_PROPERTY(%1, %2)\n"

const QRegExp rxstart("\\{\\s*public\\s*:", Qt::CaseSensitive, QRegExp::RegExp2);

MongoObjGenerator::MongoObjGenerator(const QString &model)
    : modelName(model), fields()
{ }

QString MongoObjGenerator::mongoObjectFilePath(const QString &dstDir) const
{
    return QDir(dstDir + "/mongoobjects").filePath(modelName.toLower() + "object.h");
}

QString MongoObjGenerator::generate(const QString &dstDir)
{
    QString mobjpath = mongoObjectFilePath(dstDir);

    if (QFile(mobjpath).exists()) {
        updateMongoObject(mobjpath);
    } else {
        createMongoObject(mobjpath);
    }

    return QLatin1String("mongoobjects/") + QFileInfo(mobjpath).fileName();
}

static QStringList generateCode(const QList<QPair<QString, QVariant::Type> > &fieldList)
{
    QString params, enums, macros;

    for (QListIterator<QPair<QString, QVariant::Type> > it(fieldList); it.hasNext(); ) {
        const QPair<QString, QVariant::Type> &p = it.next();
        QString typeName = QVariant::typeToName(p.second);
        params += QString("    %1 %2;\n").arg(typeName, p.first);
        macros += QString(MONGOOBJECT_PROPERTY_TEMPLATE).arg(typeName, p.first);
        QString estr = fieldNameToEnumName(p.first);
        enums  += (enums.isEmpty()) ? QString("        %1 = 0,\n").arg(estr) : QString("        %1,\n").arg(estr);
    }

    return QStringList() << params << enums << macros;
}

bool MongoObjGenerator::createMongoObject(const QString &path)
{
    fields << qMakePair(QString("_id"), QVariant::String)
           << qMakePair(QString("createdAt"), QVariant::DateTime)
           << qMakePair(QString("updatedAt"), QVariant::DateTime)
           << qMakePair(QString("lockRevision"), QVariant::Int);

    QStringList code = generateCode(fields);
    QString output = QString(MONGOOBJECT_HEADER_TEMPLATE).arg(modelName.toUpper(), fieldNameToEnumName(modelName), code[0], code[1], modelName, code[2]);
    // Writes to a file
    return FileWriter(path).write(output, false);
}

static QList<QPair<QString, QVariant::Type> > getFieldList(const QString &filePath)
{
    QList<QPair<QString, QVariant::Type> > ret;
    QRegExp rxend("(\\n[\\t\\r ]*\\n|\\senum\\s)", Qt::CaseSensitive, QRegExp::RegExp2);
    QRegExp rx("\\s([a-zA-Z0-9_<>]+)\\s+([a-zA-Z0-9_]+)\\s*;", Qt::CaseSensitive, QRegExp::RegExp2);

    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qCritical("file open error: %s", qPrintable(filePath));
        _exit(1);
    }

    QString src = QString::fromUtf8(file.readAll().data());
    int pos = rxstart.indexIn(src, 0);
    if (pos < 0) {
        qCritical("parse error");
        _exit(1);
    }
    pos += rxstart.matchedLength();

    int end = rxend.indexIn(src, pos);
    while ((pos = rx.indexIn(src, pos)) > 0 && pos < end) {
        QVariant::Type type = QVariant::nameToType(rx.cap(1).toLatin1().data());
        QString var = rx.cap(2);
        if (type != QVariant::Invalid && var.toLower() != "id")
            ret << QPair<QString, QVariant::Type>(var, type);
        pos += rx.matchedLength();
    }
    return ret;
}

bool MongoObjGenerator::updateMongoObject(const QString &path)
{
    QFile file(path);

    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qCritical("file open error: %s", qPrintable(path));
        _exit(1);
    }

    QString src = QString::fromUtf8(file.readAll().data());
    QString headerpart;

    int pos = rxstart.indexIn(src, 0);
    if (pos > 0) {
        pos += rxstart.matchedLength();
        headerpart = src.mid(0, pos);
    }

    fields = getFieldList(path);
    QStringList prop = generateCode(fields);
    QString output = QString(MONGOOBJECT_HEADER_UPDATE_TEMPLATE).arg(modelName.toUpper(), modelName, headerpart, prop[0], prop[1], prop[2]);
    // Writes to a file
    return FileWriter(path).write(output, true);
}

int MongoObjGenerator::primaryKeyIndex() const
{
    if (fields.isEmpty()) {
        qCritical("Mongo file not generated");
        return -1;
    }

    for (int i = 0; i < fields.count(); ++i) {
        if (fields[i].first == "_id")
            return i;
    }
    return -1;
}

int MongoObjGenerator::autoValueIndex() const
{
    return primaryKeyIndex();
}

int MongoObjGenerator::lockRevisionIndex() const
{
    if (fields.isEmpty()) {
        qCritical("Mongo file not generated");
        return -1;
    }

    for (int i = 0; i < fields.count(); ++i) {
        QString var = fieldNameToVariableName(fields[i].first);
        if (var == "lockRevision")
            return i;
    }
    return -1;

}
<commit_msg>When scaffolding, creates a directory if directory does not exist.<commit_after>/* Copyright (c) 2013, AOYAMA Kazuharu
 * All rights reserved.
 *
 * This software may be used and distributed according to the terms of
 * the New BSD License, which is incorporated herein by reference.
 */

#include "mongoobjgenerator.h"
#include "global.h"
#include "projectfilegenerator.h"
#include "filewriter.h"
#include <QPair>
#include <QRegExp>
#include <unistd.h>

#define MONGOOBJECT_HEADER_TEMPLATE                                     \
    "#ifndef %1OBJECT_H\n"                                              \
    "#define %1OBJECT_H\n"                                              \
    "\n"                                                                \
    "#include <TMongoObject>\n"                                         \
    "#include <QSharedData>\n"                                          \
    "\n\n"                                                              \
    "class T_MODEL_EXPORT %2Object : public TMongoObject, public QSharedData\n" \
    "{\n"                                                               \
    "public:\n"                                                         \
    "%3"                                                                \
    "\n"                                                                \
    "    enum PropertyIndex {\n"                                        \
    "%4"                                                                \
    "    };\n"                                                          \
    "\n"                                                                \
    "    virtual QString collectionName() const { return \"%5\"; }\n"   \
    "    virtual QString objectId() const { return _id; }\n"            \
    "    virtual QString &objectId() { return _id; }\n"                 \
    "\n"                                                                \
    "private:\n"                                                        \
    "    Q_OBJECT\n"                                                    \
    "%6"                                                                \
    "};\n"                                                              \
    " \n"                                                               \
    "#endif // %1OBJECT_H"

#define MONGOOBJECT_HEADER_UPDATE_TEMPLATE                              \
    "%3\n"                                                              \
    "%4"                                                                \
    "\n"                                                                \
    "    enum PropertyIndex {\n"                                        \
    "%5"                                                                \
    "    };\n"                                                          \
    "\n"                                                                \
    "    virtual QString collectionName() const { return \"%2\"; }\n"   \
    "    virtual QString objectId() const { return _id; }\n"            \
    "    virtual QString &objectId() { return _id; }\n"                 \
    "\n"                                                                \
    "private:\n"                                                        \
    "    Q_OBJECT\n"                                                    \
    "%6"                                                                \
    "};\n"                                                              \
    " \n"                                                               \
    "#endif // %1OBJECT_H"

#define MONGOOBJECT_PROPERTY_TEMPLATE                \
    "    Q_PROPERTY(%1 %2 READ get%2 WRITE set%2)\n" \
    "    T_DEFINE_PROPERTY(%1, %2)\n"

const QRegExp rxstart("\\{\\s*public\\s*:", Qt::CaseSensitive, QRegExp::RegExp2);

MongoObjGenerator::MongoObjGenerator(const QString &model)
    : modelName(model), fields()
{ }

QString MongoObjGenerator::mongoObjectFilePath(const QString &dstDir) const
{
    return QDir(dstDir + "/mongoobjects").filePath(modelName.toLower() + "object.h");
}

QString MongoObjGenerator::generate(const QString &dstDir)
{
    QString mobjpath = mongoObjectFilePath(dstDir);
    QFileInfo fi(mobjpath);

    if (fi.exists()) {
        updateMongoObject(mobjpath);
    } else {
        QDir dir = fi.dir();
        if (!dir.exists()) {
            dir.mkpath(".");
        }
        createMongoObject(mobjpath);
    }

    return QLatin1String("mongoobjects/") + QFileInfo(mobjpath).fileName();
}

static QStringList generateCode(const QList<QPair<QString, QVariant::Type> > &fieldList)
{
    QString params, enums, macros;

    for (QListIterator<QPair<QString, QVariant::Type> > it(fieldList); it.hasNext(); ) {
        const QPair<QString, QVariant::Type> &p = it.next();
        QString typeName = QVariant::typeToName(p.second);
        params += QString("    %1 %2;\n").arg(typeName, p.first);
        macros += QString(MONGOOBJECT_PROPERTY_TEMPLATE).arg(typeName, p.first);
        QString estr = fieldNameToEnumName(p.first);
        enums  += (enums.isEmpty()) ? QString("        %1 = 0,\n").arg(estr) : QString("        %1,\n").arg(estr);
    }

    return QStringList() << params << enums << macros;
}

bool MongoObjGenerator::createMongoObject(const QString &path)
{
    fields << qMakePair(QString("_id"), QVariant::String)
           << qMakePair(QString("createdAt"), QVariant::DateTime)
           << qMakePair(QString("updatedAt"), QVariant::DateTime)
           << qMakePair(QString("lockRevision"), QVariant::Int);

    QStringList code = generateCode(fields);
    QString output = QString(MONGOOBJECT_HEADER_TEMPLATE).arg(modelName.toUpper(), fieldNameToEnumName(modelName), code[0], code[1], modelName, code[2]);
    // Writes to a file
    return FileWriter(path).write(output, false);
}

static QList<QPair<QString, QVariant::Type> > getFieldList(const QString &filePath)
{
    QList<QPair<QString, QVariant::Type> > ret;
    QRegExp rxend("(\\n[\\t\\r ]*\\n|\\senum\\s)", Qt::CaseSensitive, QRegExp::RegExp2);
    QRegExp rx("\\s([a-zA-Z0-9_<>]+)\\s+([a-zA-Z0-9_]+)\\s*;", Qt::CaseSensitive, QRegExp::RegExp2);

    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qCritical("file open error: %s", qPrintable(filePath));
        _exit(1);
    }

    QString src = QString::fromUtf8(file.readAll().data());
    int pos = rxstart.indexIn(src, 0);
    if (pos < 0) {
        qCritical("parse error");
        _exit(1);
    }
    pos += rxstart.matchedLength();

    int end = rxend.indexIn(src, pos);
    while ((pos = rx.indexIn(src, pos)) > 0 && pos < end) {
        QVariant::Type type = QVariant::nameToType(rx.cap(1).toLatin1().data());
        QString var = rx.cap(2);
        if (type != QVariant::Invalid && var.toLower() != "id")
            ret << QPair<QString, QVariant::Type>(var, type);
        pos += rx.matchedLength();
    }
    return ret;
}

bool MongoObjGenerator::updateMongoObject(const QString &path)
{
    QFile file(path);

    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qCritical("file open error: %s", qPrintable(path));
        _exit(1);
    }

    QString src = QString::fromUtf8(file.readAll().data());
    QString headerpart;

    int pos = rxstart.indexIn(src, 0);
    if (pos > 0) {
        pos += rxstart.matchedLength();
        headerpart = src.mid(0, pos);
    }

    fields = getFieldList(path);
    QStringList prop = generateCode(fields);
    QString output = QString(MONGOOBJECT_HEADER_UPDATE_TEMPLATE).arg(modelName.toUpper(), modelName, headerpart, prop[0], prop[1], prop[2]);
    // Writes to a file
    return FileWriter(path).write(output, true);
}

int MongoObjGenerator::primaryKeyIndex() const
{
    if (fields.isEmpty()) {
        qCritical("Mongo file not generated");
        return -1;
    }

    for (int i = 0; i < fields.count(); ++i) {
        if (fields[i].first == "_id")
            return i;
    }
    return -1;
}

int MongoObjGenerator::autoValueIndex() const
{
    return primaryKeyIndex();
}

int MongoObjGenerator::lockRevisionIndex() const
{
    if (fields.isEmpty()) {
        qCritical("Mongo file not generated");
        return -1;
    }

    for (int i = 0; i < fields.count(); ++i) {
        QString var = fieldNameToVariableName(fields[i].first);
        if (var == "lockRevision")
            return i;
    }
    return -1;

}
<|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2011-2012, Willow Garage, 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 the copyright holder(s) 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.
 *
 * Author : Christian Potthast
 * Email  : potthast@usc.edu
 *
 */

#include <pcl/io/pcd_io.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>

#include <pcl/segmentation/unary_classifier.h>

using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;

double default_feature_threshold = 5.0;
double default_normal_radius_search = 0.01;
double default_fpfh_radius_search = 0.05;

typedef PointXYZRGBA PointT;
typedef PointCloud<PointT> CloudT;
typedef PointCloud<PointXYZRGBL> CloudLT;
typedef PointCloud<FPFHSignature33> FeatureT;

void
printHelp (int, char **argv)
{
  print_error ("Syntax is: %s input.pcd output.pcd <options>\n", argv[0]);
  print_info ("  where options are:\n");
  print_info ("                     -d = trained features directory \n");
  print_info ("                     -threshold X = feature threshold (default: ");
  print_value ("%f", default_feature_threshold); print_info (")\n");
  print_info ("                     -normal-search X = Normal radius search (default: ");
  print_value ("%f", default_normal_radius_search); print_info (")\n");
  print_info ("                     -fpfh-search X = FPFH radius search (default: ");
  print_value ("%f", default_fpfh_radius_search); print_info (")\n");
}

bool
loadTrainedFeatures (std::vector<FeatureT::Ptr> &out,
                     const boost::filesystem::path &base_dir)
{
  if (!boost::filesystem::exists (base_dir) && !boost::filesystem::is_directory (base_dir))
    return false;

  for (boost::filesystem::directory_iterator it (base_dir); it != boost::filesystem::directory_iterator (); ++it)
  {
    if (!boost::filesystem::is_directory (it->status ()) &&
        boost::filesystem::extension (it->path ()) == ".pcd")
    {
      std::stringstream ss;
      ss << it->path ().filename ();

      print_highlight ("Loading %s \n", ss.str ().c_str ());

      FeatureT::Ptr features (new FeatureT);
      loadPCDFile (it->path ().filename ().string(), *features);

      out.push_back (features);
    }
  }
  return true;
}

bool
loadCloud (const std::string &filename, CloudT::Ptr &cloud)
{
  TicToc tt;
  print_highlight ("Loading "); print_value ("%s ", filename.c_str ());

  tt.tic ();
  if (loadPCDFile (filename, *cloud) < 0)
    return (false);
  print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", cloud->width * cloud->height); print_info (" points]\n");

  return (true);
}

void
compute (const CloudT::Ptr &input, std::vector<FeatureT::Ptr> &trained_features,
         CloudLT::Ptr &out,
         float normal_radius_search,
         float fpfh_radius_search,
         float feature_threshold)
{
  TicToc tt;
  tt.tic ();

  print_highlight ("Computing ");

  UnaryClassifier<PointT> classifier;
  classifier.setInputCloud (input);
  classifier.setTrainedFeatures (trained_features);
  classifier.setNormalRadiusSearch (normal_radius_search);
  classifier.setFPFHRadiusSearch (fpfh_radius_search);
  classifier.setFeatureThreshold (feature_threshold);

  classifier.segment (out);

  print_info ("[done, ");
  print_value ("%g", tt.toc ());
  print_info (" ms : "); print_value ("%d", out->width * out->height);
  print_info (" points]\n");

}

void
saveCloud (const std::string &filename, CloudLT::Ptr &output)
{
  TicToc tt;
  tt.tic ();

  print_highlight ("Saving "); print_value ("%s ", filename.c_str ());

  PCDWriter w;
  w.write (filename, *output);

  print_info ("[done, ");
  print_value ("%g", tt.toc ()); print_info (" ms : ");
  print_value ("%d", output->width * output->height); print_info (" points]\n");
}

/* ---[ */
int
main (int argc, char** argv)
{
  print_info ("Train unary classifier using FPFH. For more information, use: %s -h\n", argv[0]);

  if (argc < 4)
  {
    printHelp (argc, argv);
    return (-1);
  }

  // Parse the command line arguments for .pcd files
  std::vector<int> p_file_indices;
  p_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
  if (p_file_indices.size () != 2)
  {
    print_error ("Need one input PCD file and one output PCD file to continue.\n");
    return (-1);
  }

  // Load the input file
  CloudT::Ptr cloud (new CloudT);
  if (!loadCloud (argv[p_file_indices[0]], cloud))
    return (-1);

  // TODO:: make this as an optional argument ??
  std::vector<int> tmp_indices;
  pcl::removeNaNFromPointCloud (*cloud, *cloud, tmp_indices);

  // parse optional input arguments from the command line
  float normal_radius_search = static_cast<float> (default_normal_radius_search);
  float fpfh_radius_search = static_cast<float> (default_fpfh_radius_search);
  float feature_threshold = static_cast<float> (default_feature_threshold);
  std::string dir_name;

  parse_argument (argc, argv, "-d", dir_name);
  parse_argument (argc, argv, "-threshold", feature_threshold);
  parse_argument (argc, argv, "-normal-radius-search", normal_radius_search);
  parse_argument (argc, argv, "-fpfh-radius-search", fpfh_radius_search);

  print_info ("trained feature directory: %s \n", dir_name.c_str ());

  // load the trained features
  std::vector<FeatureT::Ptr> trained_features;
  loadTrainedFeatures (trained_features, dir_name.c_str ());

  print_info ("feature_threshold: %f \n", feature_threshold);
  print_info ("normal-radius-search: %f \n", normal_radius_search);
  print_info ("fpfh-radius-search: %f \n\n", fpfh_radius_search);

  CloudLT::Ptr out (new CloudLT);
  compute (cloud, trained_features, out, normal_radius_search, fpfh_radius_search, feature_threshold);

  saveCloud (argv[p_file_indices[1]], out);
}

<commit_msg>* fixed issue #823: Compilation of unary_classifier_segment.cpp fails on Ubuntu 10.04 (thanks Robert!) <commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2011-2012, Willow Garage, 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 the copyright holder(s) 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.
 *
 * Author : Christian Potthast
 * Email  : potthast@usc.edu
 *
 */

#include <pcl/io/pcd_io.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>

#include <pcl/segmentation/unary_classifier.h>

using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;

double default_feature_threshold = 5.0;
double default_normal_radius_search = 0.01;
double default_fpfh_radius_search = 0.05;

typedef PointXYZRGBA PointT;
typedef PointCloud<PointT> CloudT;
typedef PointCloud<PointXYZRGBL> CloudLT;
typedef PointCloud<FPFHSignature33> FeatureT;

void
printHelp (int, char **argv)
{
  print_error ("Syntax is: %s input.pcd output.pcd <options>\n", argv[0]);
  print_info ("  where options are:\n");
  print_info ("                     -d = trained features directory \n");
  print_info ("                     -threshold X = feature threshold (default: ");
  print_value ("%f", default_feature_threshold); print_info (")\n");
  print_info ("                     -normal-search X = Normal radius search (default: ");
  print_value ("%f", default_normal_radius_search); print_info (")\n");
  print_info ("                     -fpfh-search X = FPFH radius search (default: ");
  print_value ("%f", default_fpfh_radius_search); print_info (")\n");
}

bool
loadTrainedFeatures (std::vector<FeatureT::Ptr> &out,
                     const boost::filesystem::path &base_dir)
{
  if (!boost::filesystem::exists (base_dir) && !boost::filesystem::is_directory (base_dir))
    return false;

  for (boost::filesystem::directory_iterator it (base_dir); it != boost::filesystem::directory_iterator (); ++it)
  {
    if (!boost::filesystem::is_directory (it->status ()) &&
        boost::filesystem::extension (it->path ()) == ".pcd")
    {
      std::stringstream ss;
      ss << it->path ().filename ();

      print_highlight ("Loading %s \n", ss.str ().c_str ());

      FeatureT::Ptr features (new FeatureT);
      loadPCDFile (it->path ().filename ().c_str(), *features);

      out.push_back (features);
    }
  }
  return true;
}

bool
loadCloud (const std::string &filename, CloudT::Ptr &cloud)
{
  TicToc tt;
  print_highlight ("Loading "); print_value ("%s ", filename.c_str ());

  tt.tic ();
  if (loadPCDFile (filename, *cloud) < 0)
    return (false);
  print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", cloud->width * cloud->height); print_info (" points]\n");

  return (true);
}

void
compute (const CloudT::Ptr &input, std::vector<FeatureT::Ptr> &trained_features,
         CloudLT::Ptr &out,
         float normal_radius_search,
         float fpfh_radius_search,
         float feature_threshold)
{
  TicToc tt;
  tt.tic ();

  print_highlight ("Computing ");

  UnaryClassifier<PointT> classifier;
  classifier.setInputCloud (input);
  classifier.setTrainedFeatures (trained_features);
  classifier.setNormalRadiusSearch (normal_radius_search);
  classifier.setFPFHRadiusSearch (fpfh_radius_search);
  classifier.setFeatureThreshold (feature_threshold);

  classifier.segment (out);

  print_info ("[done, ");
  print_value ("%g", tt.toc ());
  print_info (" ms : "); print_value ("%d", out->width * out->height);
  print_info (" points]\n");

}

void
saveCloud (const std::string &filename, CloudLT::Ptr &output)
{
  TicToc tt;
  tt.tic ();

  print_highlight ("Saving "); print_value ("%s ", filename.c_str ());

  PCDWriter w;
  w.write (filename, *output);

  print_info ("[done, ");
  print_value ("%g", tt.toc ()); print_info (" ms : ");
  print_value ("%d", output->width * output->height); print_info (" points]\n");
}

/* ---[ */
int
main (int argc, char** argv)
{
  print_info ("Train unary classifier using FPFH. For more information, use: %s -h\n", argv[0]);

  if (argc < 4)
  {
    printHelp (argc, argv);
    return (-1);
  }

  // Parse the command line arguments for .pcd files
  std::vector<int> p_file_indices;
  p_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
  if (p_file_indices.size () != 2)
  {
    print_error ("Need one input PCD file and one output PCD file to continue.\n");
    return (-1);
  }

  // Load the input file
  CloudT::Ptr cloud (new CloudT);
  if (!loadCloud (argv[p_file_indices[0]], cloud))
    return (-1);

  // TODO:: make this as an optional argument ??
  std::vector<int> tmp_indices;
  pcl::removeNaNFromPointCloud (*cloud, *cloud, tmp_indices);

  // parse optional input arguments from the command line
  float normal_radius_search = static_cast<float> (default_normal_radius_search);
  float fpfh_radius_search = static_cast<float> (default_fpfh_radius_search);
  float feature_threshold = static_cast<float> (default_feature_threshold);
  std::string dir_name;

  parse_argument (argc, argv, "-d", dir_name);
  parse_argument (argc, argv, "-threshold", feature_threshold);
  parse_argument (argc, argv, "-normal-radius-search", normal_radius_search);
  parse_argument (argc, argv, "-fpfh-radius-search", fpfh_radius_search);

  print_info ("trained feature directory: %s \n", dir_name.c_str ());

  // load the trained features
  std::vector<FeatureT::Ptr> trained_features;
  loadTrainedFeatures (trained_features, dir_name.c_str ());

  print_info ("feature_threshold: %f \n", feature_threshold);
  print_info ("normal-radius-search: %f \n", normal_radius_search);
  print_info ("fpfh-radius-search: %f \n\n", fpfh_radius_search);

  CloudLT::Ptr out (new CloudLT);
  compute (cloud, trained_features, out, normal_radius_search, fpfh_radius_search, feature_threshold);

  saveCloud (argv[p_file_indices[1]], out);
}

<|endoftext|>


<commit_before>// Copyright (C) 2015 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "RenderTargetOGL.h"
#include "TextureOGL.h"

namespace ouzel
{
    RenderTargetOGL::RenderTargetOGL()
    {

    }

    RenderTargetOGL::~RenderTargetOGL()
    {
        clean();
    }

    void RenderTargetOGL::clean()
    {
        if (_depthBufferId) glDeleteRenderbuffers(1, &_depthBufferId);
        if (_framebufferId) glDeleteFramebuffers(1, &_framebufferId);
    }

    bool RenderTargetOGL::init(Size2 const& size, bool depthBuffer)
    {
        if (RenderTarget::init(size, depthBuffer))
        {
            return false;
        }

        clean();

        glGenFramebuffers(1, &_framebufferId);
        glBindFramebuffer(GL_FRAMEBUFFER, _framebufferId);

        std::shared_ptr<TextureOGL> textureOGL(new TextureOGL());

        if (!textureOGL->init(false))
        {
            return false;
        }

        _texture = textureOGL;

        glBindTexture(GL_TEXTURE_2D, textureOGL->getTextureId());

        glTexImage2D(GL_TEXTURE_2D, 0,GL_RGB,
                     static_cast<GLsizei>(_size.width),
                     static_cast<GLsizei>(_size.height),
                     0, GL_RGB, GL_UNSIGNED_BYTE, 0);

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

        if (depthBuffer)
        {
            glGenRenderbuffers(1, &_depthBufferId);
            glBindRenderbuffer(GL_RENDERBUFFER, _depthBufferId);
            glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT,
                                  static_cast<GLsizei>(_size.width),
                                  static_cast<GLsizei>(_size.height));
            glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _depthBufferId);
        }

        glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, textureOGL->getTextureId(), 0);
        GLenum drawBuffers[1] = { GL_COLOR_ATTACHMENT0 };
        glDrawBuffers(1, drawBuffers);

        if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
        {
            return false;
        }

        glBindFramebuffer(GL_FRAMEBUFFER, 0);

        return true;
    }
}
<commit_msg>Add missing space<commit_after>// Copyright (C) 2015 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "RenderTargetOGL.h"
#include "TextureOGL.h"

namespace ouzel
{
    RenderTargetOGL::RenderTargetOGL()
    {

    }

    RenderTargetOGL::~RenderTargetOGL()
    {
        clean();
    }

    void RenderTargetOGL::clean()
    {
        if (_depthBufferId) glDeleteRenderbuffers(1, &_depthBufferId);
        if (_framebufferId) glDeleteFramebuffers(1, &_framebufferId);
    }

    bool RenderTargetOGL::init(Size2 const& size, bool depthBuffer)
    {
        if (RenderTarget::init(size, depthBuffer))
        {
            return false;
        }

        clean();

        glGenFramebuffers(1, &_framebufferId);
        glBindFramebuffer(GL_FRAMEBUFFER, _framebufferId);

        std::shared_ptr<TextureOGL> textureOGL(new TextureOGL());

        if (!textureOGL->init(false))
        {
            return false;
        }

        _texture = textureOGL;

        glBindTexture(GL_TEXTURE_2D, textureOGL->getTextureId());

        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
                     static_cast<GLsizei>(_size.width),
                     static_cast<GLsizei>(_size.height),
                     0, GL_RGB, GL_UNSIGNED_BYTE, 0);

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

        if (depthBuffer)
        {
            glGenRenderbuffers(1, &_depthBufferId);
            glBindRenderbuffer(GL_RENDERBUFFER, _depthBufferId);
            glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT,
                                  static_cast<GLsizei>(_size.width),
                                  static_cast<GLsizei>(_size.height));
            glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _depthBufferId);
        }

        glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, textureOGL->getTextureId(), 0);
        GLenum drawBuffers[1] = { GL_COLOR_ATTACHMENT0 };
        glDrawBuffers(1, drawBuffers);

        if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
        {
            return false;
        }

        glBindFramebuffer(GL_FRAMEBUFFER, 0);

        return true;
    }
}
<|endoftext|>


<commit_before>#include "mitkAngleCorrectByPointFilter.h"
#include "mitkImageTimeSelector.h"
#include "mitkProperties.h"

mitk::AngleCorrectByPointFilter::AngleCorrectByPointFilter() : m_PreferTransducerPositionFromProperty(true)
{
  m_Center.Fill(0);
  m_TransducerPosition.Fill(0);
}

mitk::AngleCorrectByPointFilter::~AngleCorrectByPointFilter()
{

}

void mitk::AngleCorrectByPointFilter::GenerateOutputInformation()
{
  mitk::Image::ConstPointer input = this->GetInput();
  mitk::Image::Pointer output = this->GetOutput();

  if ((output->IsInitialized()) && (this->GetMTime() <= m_TimeOfHeaderInitialization.GetMTime()))
    return;

  itkDebugMacro(<<"GenerateOutputInformation()");

  unsigned int i;
  unsigned int *tmpDimensions = new unsigned int[input->GetDimension()];

  for(i=0;i<input->GetDimension();++i)
    tmpDimensions[i]=input->GetDimension(i);

  //@todo maybe we should shift the following somehow in ImageToImageFilter
  output->Initialize(PixelType(typeid(ScalarType)),
    input->GetDimension(),
    tmpDimensions,
    input->GetNumberOfChannels());

  output->GetSlicedGeometry()->SetSpacing(input->GetSlicedGeometry()->GetSpacing());

  output->GetSlicedGeometry()->SetGeometry2D(mitk::Image::BuildStandardPlaneGeometry2D(output->GetSlicedGeometry(), tmpDimensions).GetPointer(), 0);
  output->GetSlicedGeometry()->SetEvenlySpaced();
  //set the timebounds - after SetGeometry2D, so that the already created PlaneGeometry will also receive this timebounds.
  //@fixme!!! will not work for not evenly timed data!
  output->GetSlicedGeometry()->SetTimeBoundsInMS(input->GetSlicedGeometry()->GetTimeBoundsInMS());

  //@fixme!!! for 4D-data: calculate the timebounds of the TimeSlicedGeometry: (calling GetTimeBoundsInMS() really does that!)
  output->GetGeometry()->GetTimeBoundsInMS();

  output->SetPropertyList(input->GetPropertyList()->Clone());

  delete [] tmpDimensions;

  m_TimeOfHeaderInitialization.Modified();
}

void mitk::AngleCorrectByPointFilter::GenerateData()
{
  mitk::Image::ConstPointer input = this->GetInput();
  mitk::Image::Pointer output = this->GetOutput();

  if(m_PreferTransducerPositionFromProperty)
  {
    mitk::Point3iProperty::Pointer pointProp;
    pointProp = dynamic_cast<mitk::Point3iProperty*>(input->GetProperty("ORIGIN").GetPointer());
    if (pointProp.IsNotNull() )
    {
      Point3<int> tp = pointProp->GetValue();
      vm2itk(tp, m_TransducerPosition);
    }
  }

  itkDebugMacro( << "compute angle corrected image .... " );
  itkDebugMacro( << "  Center[0]=" << m_Center[0] << " Center[1]=" << m_Center[1] << " Center[2]=" << m_Center[2] );
  itkDebugMacro( << "  TransducerPosition[0]=" << m_TransducerPosition[0] << " TransducerPosition[1]=" << m_TransducerPosition[1] << " TransducerPosition[2]=" << m_TransducerPosition[2] );

  const float *spacing = input->GetSlicedGeometry()->GetSpacing();
  //	std::cout << "   in: xres=" << spacing[0] << " yres=" << spacing[1] << " zres=" << spacing[2] << std::endl;

  if((spacing[0]!=spacing[1]) || (spacing[0]!=spacing[2]))
  {
    itkExceptionMacro("filter does not work for uninsotropic data: spacing: ("<< spacing[0] << "," << spacing[1] << "," << spacing[2] << ")");
  }

  ITKVector3D p;
  ITKVector3D tx_direction;
  ITKVector3D tx_position = m_TransducerPosition.GetVectorFromOrigin();
  ITKVector3D center = m_Center.GetVectorFromOrigin();
  ITKVector3D assumed_direction;
  ScalarType &x(p[0]),&y(p[1]),&z(p[2]);
  ITKVector3D down;
  FillITKVector3D(down,0.0,0.0,1.0);

  int xDim = input->GetDimension(0);
  int yDim = input->GetDimension(1);
  int zDim = input->GetDimension(2);

  ipPicDescriptor* pic_out;
  pic_out = ipPicNew();
  pic_out->dim = 3;
  pic_out->bpe  = output->GetPixelType().GetBpe();
  pic_out->type = output->GetPixelType().GetType();
  pic_out->n[0] = xDim;
  pic_out->n[1] = yDim;
  pic_out->n[2] = zDim;
  pic_out->data = malloc(_ipPicSize(pic_out));

  //go!
  mitk::ImageTimeSelector::Pointer timeSelector=mitk::ImageTimeSelector::New();
  timeSelector->SetInput(input);

  int nstart, nmax;
  int tstart, tmax;

  tstart=output->GetRequestedRegion().GetIndex(3);
  nstart=output->GetRequestedRegion().GetIndex(4);

  tmax=tstart+output->GetRequestedRegion().GetSize(3);
  nmax=nstart+output->GetRequestedRegion().GetSize(4);

  int n,t;
  for(n=nstart;n<nmax;++n)//output->GetNumberOfChannels();++n)
  {
    timeSelector->SetChannelNr(n);

    for(t=tstart;t<tmax;++t)
    {
      timeSelector->SetTimeNr(t);

      timeSelector->Update();

      typedef unsigned char InputImagePixelType;
      typedef ScalarType OutputImagePixelType;

      if(*input->GetPixelType().GetTypeId()!=typeid(InputImagePixelType))
      {
        itkExceptionMacro("only implemented for " << typeid(PixelType).name() );
      }

      InputImagePixelType *in;
      OutputImagePixelType *out;

      in  = (InputImagePixelType *)timeSelector->GetOutput()->GetData();
      out = (OutputImagePixelType*)pic_out->data;

      for (z=0 ; z<zDim ; ++z)
      {
        for (y=0; y<yDim; ++y)
        {
          for (x=0; x<xDim; ++x, ++in, ++out)
          {
            tx_direction = p-tx_position;
            tx_direction.Normalize();

            //are we within the acquisition cone?
            if(tx_direction*down>vnl_math::pi_over_4)
            {
              assumed_direction = center-p;
              assumed_direction.Normalize();
              ScalarType cos_factor = -tx_direction*assumed_direction;

              if(fabs(cos_factor)>eps)
                *out=((ScalarType)(*in)-128.0)/cos_factor;
              else
                *out=0;
            }
            else
              *out=0;
          }
        }
      }
      output->SetPicVolume(pic_out, t, n);
    }
  }
}

void mitk::AngleCorrectByPointFilter::GenerateInputRequestedRegion()
{
  Superclass::GenerateInputRequestedRegion();

  mitk::ImageToImageFilter::InputImagePointer input =
    const_cast< mitk::ImageToImageFilter::InputImageType * > ( this->GetInput() );
  mitk::Image::Pointer output = this->GetOutput();

  Image::RegionType requestedRegion;
  requestedRegion = output->GetRequestedRegion();
  requestedRegion.SetIndex(0, 0);
  requestedRegion.SetIndex(1, 0);
  requestedRegion.SetIndex(2, 0);
  //requestedRegion.SetIndex(3, 0);
  //requestedRegion.SetIndex(4, 0);
  requestedRegion.SetSize(0, input->GetDimension(0));
  requestedRegion.SetSize(1, input->GetDimension(1));
  requestedRegion.SetSize(2, input->GetDimension(2));
  //requestedRegion.SetSize(3, output->GetDimension(3));
  //requestedRegion.SetSize(4, output->GetNumberOfChannels());

  input->SetRequestedRegion( & requestedRegion );
}
<commit_msg>changed overflow behavior<commit_after>#include "mitkAngleCorrectByPointFilter.h"
#include "mitkImageTimeSelector.h"
#include "mitkProperties.h"

mitk::AngleCorrectByPointFilter::AngleCorrectByPointFilter() : m_PreferTransducerPositionFromProperty(true)
{
  m_Center.Fill(0);
  m_TransducerPosition.Fill(0);
}

mitk::AngleCorrectByPointFilter::~AngleCorrectByPointFilter()
{

}

void mitk::AngleCorrectByPointFilter::GenerateOutputInformation()
{
  mitk::Image::ConstPointer input = this->GetInput();
  mitk::Image::Pointer output = this->GetOutput();

  if ((output->IsInitialized()) && (this->GetMTime() <= m_TimeOfHeaderInitialization.GetMTime()))
    return;

  itkDebugMacro(<<"GenerateOutputInformation()");

  unsigned int i;
  unsigned int *tmpDimensions = new unsigned int[input->GetDimension()];

  for(i=0;i<input->GetDimension();++i)
    tmpDimensions[i]=input->GetDimension(i);

  //@todo maybe we should shift the following somehow in ImageToImageFilter
  output->Initialize(PixelType(typeid(ScalarType)),
    input->GetDimension(),
    tmpDimensions,
    input->GetNumberOfChannels());

  output->GetSlicedGeometry()->SetSpacing(input->GetSlicedGeometry()->GetSpacing());

  output->GetSlicedGeometry()->SetGeometry2D(mitk::Image::BuildStandardPlaneGeometry2D(output->GetSlicedGeometry(), tmpDimensions).GetPointer(), 0);
  output->GetSlicedGeometry()->SetEvenlySpaced();
  //set the timebounds - after SetGeometry2D, so that the already created PlaneGeometry will also receive this timebounds.
  //@fixme!!! will not work for not evenly timed data!
  output->GetSlicedGeometry()->SetTimeBoundsInMS(input->GetSlicedGeometry()->GetTimeBoundsInMS());

  //@fixme!!! for 4D-data: calculate the timebounds of the TimeSlicedGeometry: (calling GetTimeBoundsInMS() really does that!)
  output->GetGeometry()->GetTimeBoundsInMS();

  output->SetPropertyList(input->GetPropertyList()->Clone());

  delete [] tmpDimensions;

  m_TimeOfHeaderInitialization.Modified();
}

void mitk::AngleCorrectByPointFilter::GenerateData()
{
  mitk::Image::ConstPointer input = this->GetInput();
  mitk::Image::Pointer output = this->GetOutput();

  if(m_PreferTransducerPositionFromProperty)
  {
    mitk::Point3iProperty::Pointer pointProp;
    pointProp = dynamic_cast<mitk::Point3iProperty*>(input->GetProperty("ORIGIN").GetPointer());
    if (pointProp.IsNotNull() )
    {
      Point3<int> tp = pointProp->GetValue();
      vm2itk(tp, m_TransducerPosition);
    }
  }

  itkDebugMacro( << "compute angle corrected image .... " );
  itkDebugMacro( << "  Center[0]=" << m_Center[0] << " Center[1]=" << m_Center[1] << " Center[2]=" << m_Center[2] );
  itkDebugMacro( << "  TransducerPosition[0]=" << m_TransducerPosition[0] << " TransducerPosition[1]=" << m_TransducerPosition[1] << " TransducerPosition[2]=" << m_TransducerPosition[2] );

  const float *spacing = input->GetSlicedGeometry()->GetSpacing();
  //	std::cout << "   in: xres=" << spacing[0] << " yres=" << spacing[1] << " zres=" << spacing[2] << std::endl;

  if((spacing[0]!=spacing[1]) || (spacing[0]!=spacing[2]))
  {
    itkExceptionMacro("filter does not work for uninsotropic data: spacing: ("<< spacing[0] << "," << spacing[1] << "," << spacing[2] << ")");
  }

  ITKVector3D p;
  ITKVector3D tx_direction;
  ITKVector3D tx_position = m_TransducerPosition.GetVectorFromOrigin();
  ITKVector3D center = m_Center.GetVectorFromOrigin();
  ITKVector3D assumed_direction;
  ScalarType &x(p[0]),&y(p[1]),&z(p[2]);
  ITKVector3D down;
  FillITKVector3D(down,0.0,0.0,1.0);

  int xDim = input->GetDimension(0);
  int yDim = input->GetDimension(1);
  int zDim = input->GetDimension(2);

  ipPicDescriptor* pic_out;
  pic_out = ipPicNew();
  pic_out->dim = 3;
  pic_out->bpe  = output->GetPixelType().GetBpe();
  pic_out->type = output->GetPixelType().GetType();
  pic_out->n[0] = xDim;
  pic_out->n[1] = yDim;
  pic_out->n[2] = zDim;
  pic_out->data = malloc(_ipPicSize(pic_out));

  //go!
  mitk::ImageTimeSelector::Pointer timeSelector=mitk::ImageTimeSelector::New();
  timeSelector->SetInput(input);

  int nstart, nmax;
  int tstart, tmax;

  tstart=output->GetRequestedRegion().GetIndex(3);
  nstart=output->GetRequestedRegion().GetIndex(4);

  tmax=tstart+output->GetRequestedRegion().GetSize(3);
  nmax=nstart+output->GetRequestedRegion().GetSize(4);

  int n,t;
  for(n=nstart;n<nmax;++n)//output->GetNumberOfChannels();++n)
  {
    timeSelector->SetChannelNr(n);

    for(t=tstart;t<tmax;++t)
    {
      timeSelector->SetTimeNr(t);

      timeSelector->Update();

      typedef unsigned char InputImagePixelType;
      typedef ScalarType OutputImagePixelType;

      if(*input->GetPixelType().GetTypeId()!=typeid(InputImagePixelType))
      {
        itkExceptionMacro("only implemented for " << typeid(PixelType).name() );
      }

      InputImagePixelType *in;
      OutputImagePixelType *out;

      in  = (InputImagePixelType *)timeSelector->GetOutput()->GetData();
      out = (OutputImagePixelType*)pic_out->data;

      for (z=0 ; z<zDim ; ++z)
      {
        for (y=0; y<yDim; ++y)
        {
          for (x=0; x<xDim; ++x, ++in, ++out)
          {
            tx_direction = p-tx_position;
            tx_direction.Normalize();

            //are we within the acquisition cone?
            if(tx_direction*down>vnl_math::pi_over_4)
            {
              assumed_direction = center-p;
              assumed_direction.Normalize();
              ScalarType cos_factor = -tx_direction*assumed_direction;

              if(fabs(cos_factor)>eps)
                *out=((ScalarType)(*in)-128.0)/cos_factor;
              else
                *out=((ScalarType)(*in)-128.0)/eps;
            }
            else
              *out=0;
          }
        }
      }
      output->SetPicVolume(pic_out, t, n);
    }
  }
}

void mitk::AngleCorrectByPointFilter::GenerateInputRequestedRegion()
{
  Superclass::GenerateInputRequestedRegion();

  mitk::ImageToImageFilter::InputImagePointer input =
    const_cast< mitk::ImageToImageFilter::InputImageType * > ( this->GetInput() );
  mitk::Image::Pointer output = this->GetOutput();

  Image::RegionType requestedRegion;
  requestedRegion = output->GetRequestedRegion();
  requestedRegion.SetIndex(0, 0);
  requestedRegion.SetIndex(1, 0);
  requestedRegion.SetIndex(2, 0);
  //requestedRegion.SetIndex(3, 0);
  //requestedRegion.SetIndex(4, 0);
  requestedRegion.SetSize(0, input->GetDimension(0));
  requestedRegion.SetSize(1, input->GetDimension(1));
  requestedRegion.SetSize(2, input->GetDimension(2));
  //requestedRegion.SetSize(3, output->GetDimension(3));
  //requestedRegion.SetSize(4, output->GetNumberOfChannels());

  input->SetRequestedRegion( & requestedRegion );
}
<|endoftext|>