<commit_before>#ifndef INC_METTLE_RUNNER_HPP
#define INC_METTLE_RUNNER_HPP

#include <fcntl.h>
#include <poll.h>
#include <sys/wait.h>

#include <chrono>
#include <thread>

#include "optional.hpp"
#include "scoped_pipe.hpp"
#include "suite.hpp"
#include "log/core.hpp"

namespace mettle {

using test_runner = std::function<
  test_result(const test_function &, log::test_output &)
>;

namespace detail {
  template<typename T>
  void run_tests_impl(const T &suites, log::test_logger &logger,
                      const test_runner &runner,
                      std::vector<std::string> &parents) {
    for(const auto &suite : suites) {
      parents.push_back(suite.name());

      logger.start_suite(parents);

      for(const auto &test : suite) {
        const log::test_name name = {parents, test.name, test.id};
        logger.start_test(name);

        if(test.skip) {
          logger.skipped_test(name);
          continue;
        }

        using namespace std::literals::chrono_literals;

        log::test_output output;
        auto result = runner(test.function, output);
        if(result.passed)
          logger.passed_test(name, output);
        else
          logger.failed_test(name, result.message, output);
      }

      logger.end_suite(parents);

      run_tests_impl(suite.subsuites(), logger, runner, parents);
      parents.pop_back();
    }
  }
}

class forked_test_runner {
private:
  using timeout_t = METTLE_OPTIONAL_NS::optional<std::chrono::milliseconds>;
public:
  forked_test_runner(timeout_t timeout = timeout_t()) : timeout_(timeout) {}

  template<class Rep, class Period>
  forked_test_runner(std::chrono::duration<Rep, Period> timeout)
    : timeout_(timeout) {}

  test_result
  operator ()(const test_function &test, log::test_output &output) const {
    scoped_pipe stdout_pipe, stderr_pipe, log_pipe;
    if(stdout_pipe.open() < 0 ||
       stderr_pipe.open() < 0 ||
       log_pipe.open(O_CLOEXEC) < 0)
      goto parent_fail;

    pid_t pid;
    if((pid = fork()) < 0)
      goto parent_fail;

    if(pid == 0) {
      if(timeout_)
        fork_watcher(*timeout_);

      if(stdout_pipe.close_read() < 0 ||
         stderr_pipe.close_read() < 0 ||
         log_pipe.close_read() < 0)
        goto child_fail;

      if(dup2(stdout_pipe.write_fd, STDOUT_FILENO) < 0 ||
         dup2(stderr_pipe.write_fd, STDERR_FILENO) < 0)
        goto child_fail;

      if(stdout_pipe.close_write() < 0 ||
         stderr_pipe.close_write() < 0)
        goto child_fail;

      {
        auto result = test();
        if(write(log_pipe.write_fd, result.message.c_str(),
                 result.message.length()) < 0)
          goto child_fail;
        exit(!result.passed);
      }
    child_fail:
      exit(128);
    }
    else {
      if(stdout_pipe.close_write() < 0 ||
         stderr_pipe.close_write() < 0 ||
         log_pipe.close_write() < 0)
        goto parent_fail;

      ssize_t size;
      char buf[BUFSIZ];

      // Read from the piped stdout and stderr.
      int rv;
      pollfd fds[2] = { {stdout_pipe.read_fd, POLLIN, 0},
                        {stderr_pipe.read_fd, POLLIN, 0} };
      std::string *dests[] = {&output.stdout, &output.stderr};
      int open_fds = 2;
      while(open_fds && (rv = poll(fds, 2, -1)) > 0) {
        for(size_t i = 0; i < 2; i++) {
          if(fds[i].revents & POLLIN) {
            if((size = read(fds[i].fd, buf, sizeof(buf))) < 0)
              goto parent_fail;
            dests[i]->append(buf, size);
          }
          if(fds[i].revents & POLLHUP) {
            fds[i].fd = -fds[i].fd;
            open_fds--;
          }
        }
      }
      if(rv < 0) // poll() failed!
        goto parent_fail;

      // Read from our logging pipe (which sends the message from the test run).
      std::string message;
      while((size = read(log_pipe.read_fd, buf, sizeof(buf))) > 0)
        message.append(buf, size);
      if(size < 0) // read() failed!
        goto parent_fail;

      int status;
      if(waitpid(pid, &status, 0) < 0)
        goto parent_fail;

      if(WIFEXITED(status)) {
        int exit_code = WEXITSTATUS(status);
        if(exit_code == 2) {
          std::stringstream ss;
          ss << "Timed out after " << timeout_->count() << " ms";
          return { false, ss.str() };
        }
        else {
          return { exit_code == 0, message };
        }
      }
      else if(WIFSIGNALED(status)) {
        return { false, strsignal(WTERMSIG(status)) };
      }
      else { // WIFSTOPPED
        return { false, "Stopped" };
      }
    }
  parent_fail:
    char errbuf[256];
    strerror_r(errno, errbuf, sizeof(errbuf));
    return { false, errbuf };
  }
private:
  void fork_watcher(std::chrono::milliseconds timeout) const {
    pid_t watcher_pid;
    if((watcher_pid = fork()) < 0)
      goto fail;
    if(watcher_pid == 0) {
      std::this_thread::sleep_for(timeout);
      exit(2);
    }

    pid_t test_pid;
    if((test_pid = fork()) < 0) {
      kill(watcher_pid, SIGKILL);
      goto fail;
    }
    if(test_pid != 0) {
      // Wait for the first child process (the watcher or the test) to finish,
      // and kill the other one.
      int status;
      pid_t exited_pid = wait(&status);
      kill(exited_pid == test_pid ? watcher_pid : test_pid, SIGKILL);
      wait(nullptr);

      if(WIFEXITED(status))
        exit(WEXITSTATUS(status));
      else if(WIFSIGNALED(status))
        raise(WTERMSIG(status));
      else // WIFSTOPPED
        exit(128); // XXX: not sure what to do here
    }

    return;
  fail:
    exit(128);
  }

  timeout_t timeout_;
};

inline test_result
inline_test_runner(const test_function &test, log::test_output &) {
  return test();
}

template<typename T>
inline void run_tests(const T &suites, log::test_logger &logger,
                      const test_runner &runner) {
  std::vector<std::string> parents;
  logger.start_run();
  detail::run_tests_impl(suites, logger, runner, parents);
  logger.end_run();
}

template<typename T>
inline void run_tests(const T &suites, log::test_logger &&logger,
                      const test_runner &runner) {
  run_tests(suites, logger, runner);
}

} // namespace mettle

#endif
<commit_msg>Remove using decl<commit_after>#ifndef INC_METTLE_RUNNER_HPP
#define INC_METTLE_RUNNER_HPP

#include <fcntl.h>
#include <poll.h>
#include <sys/wait.h>

#include <chrono>
#include <thread>

#include "optional.hpp"
#include "scoped_pipe.hpp"
#include "suite.hpp"
#include "log/core.hpp"

namespace mettle {

using test_runner = std::function<
  test_result(const test_function &, log::test_output &)
>;

namespace detail {
  template<typename T>
  void run_tests_impl(const T &suites, log::test_logger &logger,
                      const test_runner &runner,
                      std::vector<std::string> &parents) {
    for(const auto &suite : suites) {
      parents.push_back(suite.name());

      logger.start_suite(parents);

      for(const auto &test : suite) {
        const log::test_name name = {parents, test.name, test.id};
        logger.start_test(name);

        if(test.skip) {
          logger.skipped_test(name);
          continue;
        }

        log::test_output output;
        auto result = runner(test.function, output);
        if(result.passed)
          logger.passed_test(name, output);
        else
          logger.failed_test(name, result.message, output);
      }

      logger.end_suite(parents);

      run_tests_impl(suite.subsuites(), logger, runner, parents);
      parents.pop_back();
    }
  }
}

class forked_test_runner {
private:
  using timeout_t = METTLE_OPTIONAL_NS::optional<std::chrono::milliseconds>;
public:
  forked_test_runner(timeout_t timeout = timeout_t()) : timeout_(timeout) {}

  template<class Rep, class Period>
  forked_test_runner(std::chrono::duration<Rep, Period> timeout)
    : timeout_(timeout) {}

  test_result
  operator ()(const test_function &test, log::test_output &output) const {
    scoped_pipe stdout_pipe, stderr_pipe, log_pipe;
    if(stdout_pipe.open() < 0 ||
       stderr_pipe.open() < 0 ||
       log_pipe.open(O_CLOEXEC) < 0)
      goto parent_fail;

    pid_t pid;
    if((pid = fork()) < 0)
      goto parent_fail;

    if(pid == 0) {
      if(timeout_)
        fork_watcher(*timeout_);

      if(stdout_pipe.close_read() < 0 ||
         stderr_pipe.close_read() < 0 ||
         log_pipe.close_read() < 0)
        goto child_fail;

      if(dup2(stdout_pipe.write_fd, STDOUT_FILENO) < 0 ||
         dup2(stderr_pipe.write_fd, STDERR_FILENO) < 0)
        goto child_fail;

      if(stdout_pipe.close_write() < 0 ||
         stderr_pipe.close_write() < 0)
        goto child_fail;

      {
        auto result = test();
        if(write(log_pipe.write_fd, result.message.c_str(),
                 result.message.length()) < 0)
          goto child_fail;
        exit(!result.passed);
      }
    child_fail:
      exit(128);
    }
    else {
      if(stdout_pipe.close_write() < 0 ||
         stderr_pipe.close_write() < 0 ||
         log_pipe.close_write() < 0)
        goto parent_fail;

      ssize_t size;
      char buf[BUFSIZ];

      // Read from the piped stdout and stderr.
      int rv;
      pollfd fds[2] = { {stdout_pipe.read_fd, POLLIN, 0},
                        {stderr_pipe.read_fd, POLLIN, 0} };
      std::string *dests[] = {&output.stdout, &output.stderr};
      int open_fds = 2;
      while(open_fds && (rv = poll(fds, 2, -1)) > 0) {
        for(size_t i = 0; i < 2; i++) {
          if(fds[i].revents & POLLIN) {
            if((size = read(fds[i].fd, buf, sizeof(buf))) < 0)
              goto parent_fail;
            dests[i]->append(buf, size);
          }
          if(fds[i].revents & POLLHUP) {
            fds[i].fd = -fds[i].fd;
            open_fds--;
          }
        }
      }
      if(rv < 0) // poll() failed!
        goto parent_fail;

      // Read from our logging pipe (which sends the message from the test run).
      std::string message;
      while((size = read(log_pipe.read_fd, buf, sizeof(buf))) > 0)
        message.append(buf, size);
      if(size < 0) // read() failed!
        goto parent_fail;

      int status;
      if(waitpid(pid, &status, 0) < 0)
        goto parent_fail;

      if(WIFEXITED(status)) {
        int exit_code = WEXITSTATUS(status);
        if(exit_code == 2) {
          std::stringstream ss;
          ss << "Timed out after " << timeout_->count() << " ms";
          return { false, ss.str() };
        }
        else {
          return { exit_code == 0, message };
        }
      }
      else if(WIFSIGNALED(status)) {
        return { false, strsignal(WTERMSIG(status)) };
      }
      else { // WIFSTOPPED
        return { false, "Stopped" };
      }
    }
  parent_fail:
    char errbuf[256];
    strerror_r(errno, errbuf, sizeof(errbuf));
    return { false, errbuf };
  }
private:
  void fork_watcher(std::chrono::milliseconds timeout) const {
    pid_t watcher_pid;
    if((watcher_pid = fork()) < 0)
      goto fail;
    if(watcher_pid == 0) {
      std::this_thread::sleep_for(timeout);
      exit(2);
    }

    pid_t test_pid;
    if((test_pid = fork()) < 0) {
      kill(watcher_pid, SIGKILL);
      goto fail;
    }
    if(test_pid != 0) {
      // Wait for the first child process (the watcher or the test) to finish,
      // and kill the other one.
      int status;
      pid_t exited_pid = wait(&status);
      kill(exited_pid == test_pid ? watcher_pid : test_pid, SIGKILL);
      wait(nullptr);

      if(WIFEXITED(status))
        exit(WEXITSTATUS(status));
      else if(WIFSIGNALED(status))
        raise(WTERMSIG(status));
      else // WIFSTOPPED
        exit(128); // XXX: not sure what to do here
    }

    return;
  fail:
    exit(128);
  }

  timeout_t timeout_;
};

inline test_result
inline_test_runner(const test_function &test, log::test_output &) {
  return test();
}

template<typename T>
inline void run_tests(const T &suites, log::test_logger &logger,
                      const test_runner &runner) {
  std::vector<std::string> parents;
  logger.start_run();
  detail::run_tests_impl(suites, logger, runner, parents);
  logger.end_run();
}

template<typename T>
inline void run_tests(const T &suites, log::test_logger &&logger,
                      const test_runner &runner) {
  run_tests(suites, logger, runner);
}

} // namespace mettle

#endif
<|endoftext|>


<commit_before>#ifndef MOVECOMPONENT_H
#define MOVECOMPONENT_H
#include <glm/glm.hpp>

struct MoveComponent {
    glm::vec2 pos;
    glm::vec2 oldPos;
    glm::vec2 vel;

    //Default dir to something that could be considered undefined
    //this is neccesary because in AnimationSystem different animations
    //are selected if direction is set to anything but 0,0. This used to
    //cause segfault for bloodsplatter because bloodsplatter doesnt have
    //any "north" animation
    glm::vec2 dir {0, 0};
    float maxVelLength;

	MoveComponent(
		const glm::vec2& = {0, 0},
		const glm::vec2& = {0, 0},
		const float maxVelLength = 100.0f);

    template<class Archive>
    void serialize(Archive& ar) {
        ar(pos.x, pos.y, oldPos.x, oldPos.y, vel.x, vel.y);
    }
};

#endif //MOVECOMPONENT_H
<commit_msg>git serialization of movecomponent right this time, I think<commit_after>#ifndef MOVECOMPONENT_H
#define MOVECOMPONENT_H
#include <glm/glm.hpp>

struct MoveComponent {
    glm::vec2 pos;
    glm::vec2 oldPos;
    glm::vec2 vel;

    //Default dir to something that could be considered undefined
    //this is neccesary because in AnimationSystem different animations
    //are selected if direction is set to anything but 0,0. This used to
    //cause segfault for bloodsplatter because bloodsplatter doesnt have
    //any "north" animation
    glm::vec2 dir {0, 0};
    float maxVelLength;

	MoveComponent(
		const glm::vec2& = {0, 0},
		const glm::vec2& = {0, 0},
		const float maxVelLength = 100.0f);

    template<class Archive>
    void serialize(Archive& ar) {
        ar(pos.x, pos.y, oldPos.x, oldPos.y, vel.x, vel.y, dir.x, dir.y, maxVelLength);
    }
};

#endif //MOVECOMPONENT_H
<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkNavigationData.h"

mitk::NavigationData::NavigationData() : itk::DataObject(),
m_Position(), m_Orientation(0.0, 0.0, 0.0, 0.0), m_CovErrorMatrix(),
m_HasPosition(true), m_HasOrientation(true), m_DataValid(false), m_IGTTimeStamp(0.0),
m_Name()
{
  m_Position.Fill(0.0);
  m_CovErrorMatrix.SetIdentity();
}

mitk::NavigationData::~NavigationData()
{
}

void mitk::NavigationData::Graft( const DataObject *data )
{
  // Attempt to cast data to an NavigationData
  const Self* nd;
  try
  {
    nd = dynamic_cast<const Self *>( data );
  }
  catch( ... )
  {
    itkExceptionMacro( << "mitk::NavigationData::Graft cannot cast "
      << typeid(data).name() << " to "
      << typeid(const Self *).name() );
    return;
  }
  if (!nd)
  {
    // pointer could not be cast back down
    itkExceptionMacro( << "mitk::NavigationData::Graft cannot cast "
      << typeid(data).name() << " to "
      << typeid(const Self *).name() );
    return;
  }
  // Now copy anything that is needed
  this->SetPosition(nd->GetPosition());
  this->SetOrientation(nd->GetOrientation());
  this->SetDataValid(nd->IsDataValid());
  this->SetIGTTimeStamp(nd->GetIGTTimeStamp());
  this->SetHasPosition(nd->GetHasPosition());
  this->SetHasOrientation(nd->GetHasOrientation());
  this->SetCovErrorMatrix(nd->GetCovErrorMatrix());
  this->SetName(nd->GetName());
}

bool mitk::NavigationData::IsDataValid() const
{
  return m_DataValid;
}

void mitk::NavigationData::PrintSelf(std::ostream& os, itk::Indent indent) const
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << "data valid: "     << this->IsDataValid() << std::endl;
  os << indent << "Position: "       << this->GetPosition() << std::endl;
  os << indent << "TimeStamp: "      << this->GetIGTTimeStamp() << std::endl;
  os << indent << "HasPosition: "    << this->GetHasPosition() << std::endl;
  os << indent << "HasOrientation: " << this->GetHasOrientation() << std::endl;
  os << indent << "CovErrorMatrix: " << this->GetCovErrorMatrix() << std::endl;
}

void mitk::NavigationData::CopyInformation( const DataObject* data )
{
  this->Superclass::CopyInformation( data );

  const Self * nd = NULL;
  try
  {
    nd = dynamic_cast<const Self*>(data);
  }
  catch( ... )
  {
    // data could not be cast back down
    itkExceptionMacro(<< "mitk::NavigationData::CopyInformation() cannot cast "
      << typeid(data).name() << " to "
      << typeid(Self*).name() );
  }
  if ( !nd )
  {
    // pointer could not be cast back down
    itkExceptionMacro(<< "mitk::NavigationData::CopyInformation() cannot cast "
      << typeid(data).name() << " to "
      << typeid(Self*).name() );
  }
  /* copy all meta data */
}

void mitk::NavigationData::SetPositionAccuracy(mitk::ScalarType error)
{
  for ( int i = 0; i < 3; i++ )
    for ( int j = 0; j < 3; j++ )
    {
      m_CovErrorMatrix[ i ][ j ] = 0;
      // assume independence of position and orientation
      m_CovErrorMatrix[ i + 3 ][ j ] = 0;
      m_CovErrorMatrix[ i ][ j + 3 ] = 0;
    }
  m_CovErrorMatrix[0][0] = m_CovErrorMatrix[1][1] = m_CovErrorMatrix[2][2] = error * error;
}

void mitk::NavigationData::SetOrientationAccuracy(mitk::ScalarType error)
{
  for ( int i = 0; i < 3; i++ )
    for ( int j = 0; j < 3; j++ ) {
      m_CovErrorMatrix[ i + 3 ][ j + 3 ] = 0;
      // assume independence of position and orientation
      m_CovErrorMatrix[ i + 3 ][ j ] = 0;
      m_CovErrorMatrix[ i ][ j + 3 ] = 0;
    }
  m_CovErrorMatrix[3][3] = m_CovErrorMatrix[4][4] = m_CovErrorMatrix[5][5] = error * error;
}

mitk::NavigationData::NavigationData(
    mitk::AffineTransform3D::Pointer affineTransform3D) : itk::DataObject(),
        m_Position(), m_Orientation(0.0, 0.0, 0.0, 0.0), m_CovErrorMatrix(),
        m_HasPosition(true), m_HasOrientation(true), m_DataValid(false), m_IGTTimeStamp(0.0),
        m_Name()
{
}

mitk::AffineTransform3D::Pointer
mitk::NavigationData::GetAffineTransform3D()
{
  return AffineTransform3D::New();
}
<commit_msg>First (probably not yet working) version of conversion methods.<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkNavigationData.h"

mitk::NavigationData::NavigationData() : itk::DataObject(),
m_Position(), m_Orientation(0.0, 0.0, 0.0, 0.0), m_CovErrorMatrix(),
m_HasPosition(true), m_HasOrientation(true), m_DataValid(false), m_IGTTimeStamp(0.0),
m_Name()
{
  m_Position.Fill(0.0);
  m_CovErrorMatrix.SetIdentity();
}

mitk::NavigationData::~NavigationData()
{
}

void mitk::NavigationData::Graft( const DataObject *data )
{
  // Attempt to cast data to an NavigationData
  const Self* nd;
  try
  {
    nd = dynamic_cast<const Self *>( data );
  }
  catch( ... )
  {
    itkExceptionMacro( << "mitk::NavigationData::Graft cannot cast "
      << typeid(data).name() << " to "
      << typeid(const Self *).name() );
    return;
  }
  if (!nd)
  {
    // pointer could not be cast back down
    itkExceptionMacro( << "mitk::NavigationData::Graft cannot cast "
      << typeid(data).name() << " to "
      << typeid(const Self *).name() );
    return;
  }
  // Now copy anything that is needed
  this->SetPosition(nd->GetPosition());
  this->SetOrientation(nd->GetOrientation());
  this->SetDataValid(nd->IsDataValid());
  this->SetIGTTimeStamp(nd->GetIGTTimeStamp());
  this->SetHasPosition(nd->GetHasPosition());
  this->SetHasOrientation(nd->GetHasOrientation());
  this->SetCovErrorMatrix(nd->GetCovErrorMatrix());
  this->SetName(nd->GetName());
}

bool mitk::NavigationData::IsDataValid() const
{
  return m_DataValid;
}

void mitk::NavigationData::PrintSelf(std::ostream& os, itk::Indent indent) const
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << "data valid: "     << this->IsDataValid() << std::endl;
  os << indent << "Position: "       << this->GetPosition() << std::endl;
  os << indent << "TimeStamp: "      << this->GetIGTTimeStamp() << std::endl;
  os << indent << "HasPosition: "    << this->GetHasPosition() << std::endl;
  os << indent << "HasOrientation: " << this->GetHasOrientation() << std::endl;
  os << indent << "CovErrorMatrix: " << this->GetCovErrorMatrix() << std::endl;
}

void mitk::NavigationData::CopyInformation( const DataObject* data )
{
  this->Superclass::CopyInformation( data );

  const Self * nd = NULL;
  try
  {
    nd = dynamic_cast<const Self*>(data);
  }
  catch( ... )
  {
    // data could not be cast back down
    itkExceptionMacro(<< "mitk::NavigationData::CopyInformation() cannot cast "
      << typeid(data).name() << " to "
      << typeid(Self*).name() );
  }
  if ( !nd )
  {
    // pointer could not be cast back down
    itkExceptionMacro(<< "mitk::NavigationData::CopyInformation() cannot cast "
      << typeid(data).name() << " to "
      << typeid(Self*).name() );
  }
  /* copy all meta data */
}

void mitk::NavigationData::SetPositionAccuracy(mitk::ScalarType error)
{
  for ( int i = 0; i < 3; i++ )
    for ( int j = 0; j < 3; j++ )
    {
      m_CovErrorMatrix[ i ][ j ] = 0;
      // assume independence of position and orientation
      m_CovErrorMatrix[ i + 3 ][ j ] = 0;
      m_CovErrorMatrix[ i ][ j + 3 ] = 0;
    }
  m_CovErrorMatrix[0][0] = m_CovErrorMatrix[1][1] = m_CovErrorMatrix[2][2] = error * error;
}

void mitk::NavigationData::SetOrientationAccuracy(mitk::ScalarType error)
{
  for ( int i = 0; i < 3; i++ )
    for ( int j = 0; j < 3; j++ ) {
      m_CovErrorMatrix[ i + 3 ][ j + 3 ] = 0;
      // assume independence of position and orientation
      m_CovErrorMatrix[ i + 3 ][ j ] = 0;
      m_CovErrorMatrix[ i ][ j + 3 ] = 0;
    }
  m_CovErrorMatrix[3][3] = m_CovErrorMatrix[4][4] = m_CovErrorMatrix[5][5] = error * error;
}

mitk::NavigationData::NavigationData(
    mitk::AffineTransform3D::Pointer affineTransform3D) : itk::DataObject(),
        m_Position(), m_Orientation(affineTransform3D->GetMatrix().GetVnlMatrix()),
        m_CovErrorMatrix(), m_HasPosition(true), m_HasOrientation(true), m_DataValid(true), m_IGTTimeStamp(0.0),
        m_Name()
{
  mitk::Vector3D offset = affineTransform3D->GetOffset();

  m_Position[0] = offset[0];
  m_Position[1] = offset[1];
  m_Position[2] = offset[2];
}

mitk::AffineTransform3D::Pointer
mitk::NavigationData::GetAffineTransform3D()
{
  AffineTransform3D::Pointer affineTransform3D = AffineTransform3D::New();

  // first set rotation
  vnl_matrix_fixed<ScalarType,3,3> vnl_rotation = m_Orientation.rotation_matrix_transpose().transpose();
  Matrix3D mitkRotation;

  for (int i = 0; i < 3; ++i) {
    for (int j = 0; j < 3; ++j) {
      mitkRotation[i][j] = vnl_rotation[i][j];
    }
  }

  affineTransform3D->SetMatrix(mitkRotation);

  // now set offset
  Vector3D vector3D;

  for (int i = 0; i < 3; ++i) {
    vector3D[i] = m_Position[i];
  }
  affineTransform3D->SetOffset(vector3D);

  return affineTransform3D;
}
<|endoftext|>


<commit_before>#ifndef LIBTEN_TASK_QUTEX_HH
#define LIBTEN_TASK_QUTEX_HH

#include "ten/task.hh"

namespace ten {

template <typename Lock>
class safe_lock {
    private:
        Lock &_lock;
    public:
        safe_lock(Lock &lock) noexcept : _lock(lock) {
            _lock.safe_lock();
        }

        ~safe_lock() noexcept {
            _lock.unlock();
        }
};

//! task aware mutex
class qutex {
private:
    std::timed_mutex _m;
    tasklist _waiting;
    task *_owner;

    void unlock_or_giveup(std::unique_lock<std::timed_mutex> &lk);
public:
    qutex() : _owner(nullptr) {
        // a simple memory barrier would be sufficient here
        std::unique_lock<std::timed_mutex> lk(_m);
    }
    qutex(const qutex &) = delete;
    qutex &operator =(const qutex &) = delete;

    ~qutex() {}

    void safe_lock() noexcept;
    void lock();
    void unlock();
    bool try_lock();
    template<typename Rep,typename Period>
        bool try_lock_for(
                std::chrono::duration<Rep,Period> const&
                relative_time);
    template<typename Clock,typename Duration>
        bool try_lock_until(
                std::chrono::time_point<Clock,Duration> const&
                absolute_time);
};

} // namespace

#endif // LIBTEN_TASK_QUTEX_HH
<commit_msg>clarify safe_lock<> a bit; forbid copying it<commit_after>#ifndef LIBTEN_TASK_QUTEX_HH
#define LIBTEN_TASK_QUTEX_HH

#include "ten/task.hh"

namespace ten {

// almost surely, Mutex = qutex
template <typename Mutex>
class safe_lock {
    Mutex &_mut;

public:
    safe_lock(Mutex &mut) noexcept : _mut(mut) {
        _mut.safe_lock();
    }
    ~safe_lock() noexcept {
        _mut.unlock();
    }

    //! no copy (and no move)
    safe_lock(const safe_lock &) = delete;
    safe_lock & operator = (const safe_lock &) = delete;
};

//! task aware mutex
class qutex {
private:
    std::timed_mutex _m;
    tasklist _waiting;
    task *_owner;

    void unlock_or_giveup(std::unique_lock<std::timed_mutex> &lk);
public:
    qutex() : _owner(nullptr) {
        // a simple memory barrier would be sufficient here
        std::unique_lock<std::timed_mutex> lk(_m);
    }
    qutex(const qutex &) = delete;
    qutex &operator =(const qutex &) = delete;

    ~qutex() {}

    void safe_lock() noexcept;
    void lock();
    void unlock();
    bool try_lock();
    template<typename Rep,typename Period>
        bool try_lock_for(
                std::chrono::duration<Rep,Period> const&
                relative_time);
    template<typename Clock,typename Duration>
        bool try_lock_until(
                std::chrono::time_point<Clock,Duration> const&
                absolute_time);
};

} // namespace

#endif // LIBTEN_TASK_QUTEX_HH
<|endoftext|>


<commit_before>#include "SolidWall.h"
#include "Simulation.h"
#include "FEProblem.h"
#include "Pipe.h"
#include "Factory.h"

template<>
InputParameters validParams<SolidWall>()
{
  InputParameters params = validParams<BoundaryBase>();
  params.addRequiredParam<std::string>("input", "Pipe name");

  params.addRequiredParam<UserObjectName>("eos", "The name of equation of state object to use.");
  return params;
}

SolidWall::SolidWall(const std::string & name, InputParameters params) :
    BoundaryBase(name, params),
    _input(getParam<std::string>("input"))
{
}

SolidWall::~SolidWall()
{
}

void
SolidWall::buildMesh()
{
  // NOTE: we are not building any mesh here, we just extract some mesh related info

  // extract boundary id so we can set up our BCs
  std::string comp_name;
  RELAP7::EEndType end_type;
  RELAP7::getConnectionInfo(_input, comp_name, end_type);

  Component * comp = _sim.getComponentByName(comp_name);
  if (dynamic_cast<GeometricalComponent *>(comp) != NULL)
  {
    GeometricalComponent * gc = dynamic_cast<GeometricalComponent *>(comp);
    _boundary_id = gc->getBoundaryId(end_type);
  }
  else
  {
    mooseError("Component " << comp->name() << " is not of a pipe type");
  }
}

void
SolidWall::addVariables()
{
}

void
SolidWall::addMooseObjects()
{
  // coupling "vectors"
  std::vector<std::string> cv_p(1, Model::PRESSURE);
  std::vector<std::string> cv_rho(1, Model::RHO);
  std::vector<std::string> cv_rhoE(1, Model::RHOE);
  // boundary id
  std::vector<unsigned int> bnd_id(1, _boundary_id);
  {
    InputParameters params = Factory::instance()->getValidParams("OneDMassSolidWallBC");
    params.set<NonlinearVariableName>("variable") = Model::RHO;
    params.set<std::vector<unsigned int> >("boundary") = bnd_id;
    _sim.addBoundaryCondition("OneDMassSolidWallBC", genName("bc", _id, "rho"), params);
  }
  {
    InputParameters params = Factory::instance()->getValidParams("OneDMomentumSolidWallBC");
    params.set<NonlinearVariableName>("variable") = Model::RHOU;
    params.set<std::vector<unsigned int> >("boundary") = bnd_id;
    params.set<UserObjectName>("eos") = getParam<UserObjectName>("eos");

    // coupling
    params.set<std::vector<std::string> >("p") = cv_p;
    params.set<std::vector<std::string> >("rho") = cv_rho;
    if (_model_type == Model::EQ_MODEL_3)
      params.set<std::vector<std::string> >("rhoE") = cv_rhoE;
    _sim.addBoundaryCondition("OneDMomentumSolidWallBC", genName("bc", _id, "rhou"), params);
  }

  if (_model_type == Model::EQ_MODEL_3)
  {
    InputParameters params = Factory::instance()->getValidParams("OneDEnergySolidWallBC");
    params.set<NonlinearVariableName>("variable") = Model::RHOE;
    params.set<std::vector<unsigned int> >("boundary") = bnd_id;
    params.set<UserObjectName>("eos") = getParam<UserObjectName>("eos");

    // There is no coupling for the energy equation solid wall BC.
    // It simply returns zero...

    _sim.addBoundaryCondition("OneDEnergySolidWallBC", genName("bc", _id, "rhoE"), params);
  }
}
<commit_msg>initial attempt at removing global factories ref idaholab/relap-7#1713<commit_after>#include "SolidWall.h"
#include "Simulation.h"
#include "FEProblem.h"
#include "Pipe.h"
#include "Factory.h"

template<>
InputParameters validParams<SolidWall>()
{
  InputParameters params = validParams<BoundaryBase>();
  params.addRequiredParam<std::string>("input", "Pipe name");

  params.addRequiredParam<UserObjectName>("eos", "The name of equation of state object to use.");
  return params;
}

SolidWall::SolidWall(const std::string & name, InputParameters params) :
    BoundaryBase(name, params),
    _input(getParam<std::string>("input"))
{
}

SolidWall::~SolidWall()
{
}

void
SolidWall::buildMesh()
{
  // NOTE: we are not building any mesh here, we just extract some mesh related info

  // extract boundary id so we can set up our BCs
  std::string comp_name;
  RELAP7::EEndType end_type;
  RELAP7::getConnectionInfo(_input, comp_name, end_type);

  Component * comp = _sim.getComponentByName(comp_name);
  if (dynamic_cast<GeometricalComponent *>(comp) != NULL)
  {
    GeometricalComponent * gc = dynamic_cast<GeometricalComponent *>(comp);
    _boundary_id = gc->getBoundaryId(end_type);
  }
  else
  {
    mooseError("Component " << comp->name() << " is not of a pipe type");
  }
}

void
SolidWall::addVariables()
{
}

void
SolidWall::addMooseObjects()
{
  // coupling "vectors"
  std::vector<std::string> cv_p(1, Model::PRESSURE);
  std::vector<std::string> cv_rho(1, Model::RHO);
  std::vector<std::string> cv_rhoE(1, Model::RHOE);
  // boundary id
  std::vector<unsigned int> bnd_id(1, _boundary_id);
  {
    InputParameters params = _factory.getValidParams("OneDMassSolidWallBC");
    params.set<NonlinearVariableName>("variable") = Model::RHO;
    params.set<std::vector<unsigned int> >("boundary") = bnd_id;
    _sim.addBoundaryCondition("OneDMassSolidWallBC", genName("bc", _id, "rho"), params);
  }
  {
    InputParameters params = _factory.getValidParams("OneDMomentumSolidWallBC");
    params.set<NonlinearVariableName>("variable") = Model::RHOU;
    params.set<std::vector<unsigned int> >("boundary") = bnd_id;
    params.set<UserObjectName>("eos") = getParam<UserObjectName>("eos");

    // coupling
    params.set<std::vector<std::string> >("p") = cv_p;
    params.set<std::vector<std::string> >("rho") = cv_rho;
    if (_model_type == Model::EQ_MODEL_3)
      params.set<std::vector<std::string> >("rhoE") = cv_rhoE;
    _sim.addBoundaryCondition("OneDMomentumSolidWallBC", genName("bc", _id, "rhou"), params);
  }

  if (_model_type == Model::EQ_MODEL_3)
  {
    InputParameters params = _factory.getValidParams("OneDEnergySolidWallBC");
    params.set<NonlinearVariableName>("variable") = Model::RHOE;
    params.set<std::vector<unsigned int> >("boundary") = bnd_id;
    params.set<UserObjectName>("eos") = getParam<UserObjectName>("eos");

    // There is no coupling for the energy equation solid wall BC.
    // It simply returns zero...

    _sim.addBoundaryCondition("OneDEnergySolidWallBC", genName("bc", _id, "rhoE"), params);
  }
}
<|endoftext|>


<commit_before>//----------------------------------------------------------------------------
/// \file  time_val.hpp
//----------------------------------------------------------------------------
/// \brief Derived implementation of ACE TimeVal to represent timeval
/// structure.
/// \author:  Serge Aleynikov
/// The original version is included in
/// (http://www.cs.wustl.edu/~schmidt/ACE.html).
//----------------------------------------------------------------------------
// ACE Library Copyright (c) 1993-2009 Douglas C. Schmidt
// Created: 2003-07-10
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****

This file is part of the utxx open-source project.

Copyright (C) 2003 Serge Aleynikov <saleyn@gmail.com>

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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

***** END LICENSE BLOCK *****
*/

#ifndef _UTXX_TIME_VAL_HPP_
#define _UTXX_TIME_VAL_HPP_

#include <boost/static_assert.hpp>
#include <utxx/detail/gettimeofday.hpp>
#include <cstddef>
#include <stdint.h>
#include <ctime>
#include <sys/time.h>

namespace utxx {
    class time_val;

    /// Indication of use of absolute time
    struct abs_time {
        long sec, usec;
        abs_time(long s=0, long us=0) : sec(s), usec(us) {}
    };
    /// Indication of use of relative time
    struct rel_time {
        long sec, usec;
        rel_time(long s=0, long us=0) : sec(s), usec(us) {}
    };

    /// A helper class for dealing with 'struct timeval' structure. This class adds ability
    /// to perform arithmetic with the structure leaving the same footprint.
    class time_val
    {
        static const long   N10e6 = 1000000;
        static const size_t N10e9 = 1000000000u;
        struct timeval m_tv;

        void normalize() {
            if (m_tv.tv_usec >= N10e6)
                do { ++m_tv.tv_sec; m_tv.tv_usec -= N10e6; }
                while (m_tv.tv_usec >= N10e6);
            else if (m_tv.tv_usec <= -N10e6)
                do { --m_tv.tv_sec; m_tv.tv_usec += N10e6; }
                while (m_tv.tv_usec <= -N10e6);

            if (m_tv.tv_sec >= 1 && m_tv.tv_usec < 0)
                { --m_tv.tv_sec; m_tv.tv_usec += N10e6; }
            else if (m_tv.tv_sec <  0 && m_tv.tv_usec > 0)
                { ++m_tv.tv_sec; m_tv.tv_usec -= N10e6; }
        }

        void setd(int64_t val, int64_t divisor) {
            int64_t n = val / divisor;
            m_tv.tv_sec  = n;
            m_tv.tv_usec = val - n*divisor;
        }
    public:
        time_val()                   { m_tv.tv_sec=0; m_tv.tv_usec=0; }
        time_val(long _s, long _us)  { m_tv.tv_sec=_s; m_tv.tv_usec=_us; normalize(); }
        time_val(const time_val& tv, long _s, long _us=0) {
            set(tv, _s, _us);
        }
        time_val(const time_val& a) : m_tv(a.m_tv) {}
        explicit time_val(const struct timeval& a) {
            m_tv.tv_sec=a.tv_sec; m_tv.tv_usec=a.tv_usec; normalize();
        }

        explicit time_val(struct tm& a_tm) {
            m_tv.tv_sec = mktime(&a_tm); m_tv.tv_usec = 0;
        }

        /// Set time to abosolute time given by \a a
        explicit time_val(const abs_time& a) {
            m_tv.tv_sec=a.sec; m_tv.tv_usec=a.usec; normalize();
        }

        /// Set time to relative offset from now given by \a a time.
        explicit time_val(const rel_time& a) { now(a.sec, a.usec); }

        #if __cplusplus >= 201103L
        time_val(time_val&& a) : m_tv(std::move(a.m_tv)) {}
        #endif

        const struct timeval&   timeval() const { return m_tv; }
        struct timeval&         timeval()       { return m_tv; }
        long                    sec()     const { return m_tv.tv_sec;  }
        long                    usec()    const { return m_tv.tv_usec; }
        time_t&                 sec()           { return m_tv.tv_sec;  }
        suseconds_t&            usec()          { return m_tv.tv_usec; }
        time_t                  msec()    const { return m_tv.tv_usec / 1000; }

        uint64_t microseconds() const {
            return (uint64_t)m_tv.tv_sec*N10e6 + (uint64_t)m_tv.tv_usec;
        }

        double seconds()          const { return  (double)m_tv.tv_sec
                                                + (double)m_tv.tv_usec/N10e6; }

        long milliseconds()       const { return m_tv.tv_sec*1000u + m_tv.tv_usec/1000; }
        void sec (size_t s)             { m_tv.tv_sec  = s;  }
        void usec(size_t us)            { m_tv.tv_usec = us; normalize(); }
        void microseconds(uint64_t ms)  { setd(ms, N10e6); }
        void milliseconds(size_t   ms)  { setd(ms, 1000);  }
        void nanosec (uint64_t ms)      { setd(ms, N10e9); }
        bool empty()              const { return sec() == 0 && usec() == 0; }

        void clear()                    { m_tv.tv_sec = 0; m_tv.tv_usec = 0; }

        void set(const time_val& tv, long _s=0, long _us=0) {
            m_tv.tv_sec = tv.sec() + _s; m_tv.tv_usec = tv.usec() + _us; normalize();
        }

        void set(const struct timeval& tv, long _s=0, long _us=0) {
            m_tv.tv_sec = tv.tv_sec + _s; m_tv.tv_usec = tv.tv_usec + _us; normalize();
        }

        void copy_to(struct timeval& tv) {
            tv.tv_sec = m_tv.tv_sec; tv.tv_usec = m_tv.tv_usec;
        }

        double diff(const time_val& t) {
            time_val tv(this->timeval());
            tv -= t;
            return (double)tv.sec() + (double)tv.usec() / N10e6;
        }

        void add(long _sec, long _us) {
            m_tv.tv_sec += _sec; m_tv.tv_usec += _us;
            if (_sec || _us) normalize();
        }

        void now() { ::gettimeofday(&m_tv, 0); }

        static time_val universal_time() {
            time_val tv; ::gettimeofday(&tv, 0); return tv;
        }

        time_val& now(long addS, long addUS=0) {
            ::gettimeofday(&m_tv, 0); add(addS, addUS);
            return *this;
        }

        const time_val* ptr() const { return reinterpret_cast<const time_val*>(&m_tv); }
        time_val*       ptr()       { return reinterpret_cast<time_val*>(&m_tv); }

        static double now_diff(const time_val& start) {
            time_val tv; tv.now(); tv -= start;
            return (double)tv.sec() + (double)tv.usec() / N10e6;
        }

        time_val operator- (const time_val& tv) const {
            return time_val(m_tv.tv_sec - tv.sec(), m_tv.tv_usec - tv.usec());
        }
        time_val operator+ (const time_val& tv) const {
            return time_val(m_tv.tv_sec + tv.sec(), m_tv.tv_usec + tv.usec());
        }
        time_val operator- (const struct timeval& tv) const {
            return time_val(m_tv.tv_sec - tv.tv_sec, m_tv.tv_usec - tv.tv_usec);
        }
        time_val operator+ (const struct timeval& tv) const {
            return time_val(m_tv.tv_sec + tv.tv_sec, m_tv.tv_usec + tv.tv_usec);
        }

        void operator-= (const struct timeval& tv) {
            m_tv.tv_sec -= tv.tv_sec; m_tv.tv_usec -= tv.tv_usec; normalize();
        }
        void operator-= (const time_val& tv) {
            m_tv.tv_sec -= tv.sec(); m_tv.tv_usec -= tv.usec(); normalize();
        }
        void operator+= (const time_val& tv) {
            m_tv.tv_sec += tv.sec(); m_tv.tv_usec += tv.usec(); normalize();
        }
        void operator+= (int32_t _sec)      { m_tv.tv_sec += _sec; }
        void operator+= (int64_t _microsec) {
            int64_t n = _microsec / N10e6;
            m_tv.tv_sec  += n;
            m_tv.tv_usec += (_microsec - (n * N10e6));
            normalize();
        }

        #if __cplusplus >= 201103L
        time_val& operator=(time_val&& a_rhs) {
            m_tv = a_rhs.m_tv;
            return *this;
        }
        #endif

        void operator= (const time_val& t) {
            m_tv.tv_sec = t.sec(); m_tv.tv_usec = t.usec();
        }
        void operator= (const struct timeval& t) {
            m_tv.tv_sec = t.tv_sec; m_tv.tv_usec = t.tv_usec;
        }
        struct timeval* operator& ()               { return &m_tv; }
        bool operator== (const time_val& tv) const {
            return sec() == tv.sec() && usec() == tv.usec();
        }
        bool operator!= (const time_val& tv) const { return !operator== (tv); }
        bool operator>  (const time_val& tv) const {
            return sec() > tv.sec() || (sec() == tv.sec() && usec() > tv.usec());
        }
        bool operator>= (const time_val& tv) const {
            return sec() > tv.sec() || (sec() == tv.sec() && usec() >= tv.usec());
        }
        bool operator<  (const time_val& tv) const {
            return sec() < tv.sec() || (sec() == tv.sec() && usec() < tv.usec());
        }
        bool operator<= (const time_val& tv) const {
            return sec() < tv.sec() || (sec() == tv.sec() && usec() <= tv.usec());
        }

        operator bool() const { return sec() == 0 && usec() == 0; }
    };

    template <typename T>
    time_val& time_val_cast(T& tv) {
        BOOST_STATIC_ASSERT(sizeof(T) == sizeof(struct timeval));
        return reinterpret_cast<time_val&>(tv);
    }

    template <typename T>
    const time_val& time_val_cast(const T& tv) {
        BOOST_STATIC_ASSERT(sizeof(T) == sizeof(struct timeval));
        return reinterpret_cast<const time_val&>(tv);
    }

    /// Same as gettimeofday() call
    inline time_val now_utc() { return time_val::universal_time(); }

    /// Simple timer for measuring interval of time
    ///
    /// Example usage1:
    /// \code
    ///     timer t; do_something(); double elapsed = t.elapsed();
    /// \endcode
    /// Example usage2:
    /// \code
    ///     time_val time;
    ///     {
    ///         timer t(time);
    ///         do_something();
    ///     }
    ///     double elapsed = time.seconds();
    /// \endcode
    class timer {
        time_val* m_result;
        time_val  m_started;
    public:
        timer() : m_result(NULL), m_started(time_val::universal_time()) {}
        timer(time_val& tv) : m_result(tv.ptr()), m_started(time_val::universal_time()) {}

        ~timer() { if (m_result) *m_result = time_val::universal_time() - m_started; }

        void   reset() { m_started = time_val::universal_time(); }

        double elapsed() const { return time_val::now_diff(m_started); }
    };

} // namespace utxx

#endif // _UTXX_TIME_VAL_HPP_
<commit_msg>Fixed const signature<commit_after>//----------------------------------------------------------------------------
/// \file  time_val.hpp
//----------------------------------------------------------------------------
/// \brief Derived implementation of ACE TimeVal to represent timeval
/// structure.
/// \author:  Serge Aleynikov
/// The original version is included in
/// (http://www.cs.wustl.edu/~schmidt/ACE.html).
//----------------------------------------------------------------------------
// ACE Library Copyright (c) 1993-2009 Douglas C. Schmidt
// Created: 2003-07-10
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****

This file is part of the utxx open-source project.

Copyright (C) 2003 Serge Aleynikov <saleyn@gmail.com>

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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

***** END LICENSE BLOCK *****
*/

#ifndef _UTXX_TIME_VAL_HPP_
#define _UTXX_TIME_VAL_HPP_

#include <boost/static_assert.hpp>
#include <utxx/detail/gettimeofday.hpp>
#include <cstddef>
#include <stdint.h>
#include <ctime>
#include <sys/time.h>

namespace utxx {
    class time_val;

    /// Indication of use of absolute time
    struct abs_time {
        long sec, usec;
        abs_time(long s=0, long us=0) : sec(s), usec(us) {}
    };
    /// Indication of use of relative time
    struct rel_time {
        long sec, usec;
        rel_time(long s=0, long us=0) : sec(s), usec(us) {}
    };

    /// A helper class for dealing with 'struct timeval' structure. This class adds ability
    /// to perform arithmetic with the structure leaving the same footprint.
    class time_val
    {
        static const long   N10e6 = 1000000;
        static const size_t N10e9 = 1000000000u;
        struct timeval m_tv;

        void normalize() {
            if (m_tv.tv_usec >= N10e6)
                do { ++m_tv.tv_sec; m_tv.tv_usec -= N10e6; }
                while (m_tv.tv_usec >= N10e6);
            else if (m_tv.tv_usec <= -N10e6)
                do { --m_tv.tv_sec; m_tv.tv_usec += N10e6; }
                while (m_tv.tv_usec <= -N10e6);

            if (m_tv.tv_sec >= 1 && m_tv.tv_usec < 0)
                { --m_tv.tv_sec; m_tv.tv_usec += N10e6; }
            else if (m_tv.tv_sec <  0 && m_tv.tv_usec > 0)
                { ++m_tv.tv_sec; m_tv.tv_usec -= N10e6; }
        }

        void setd(int64_t val, int64_t divisor) {
            int64_t n = val / divisor;
            m_tv.tv_sec  = n;
            m_tv.tv_usec = val - n*divisor;
        }
    public:
        time_val()                   { m_tv.tv_sec=0; m_tv.tv_usec=0; }
        time_val(long _s, long _us)  { m_tv.tv_sec=_s; m_tv.tv_usec=_us; normalize(); }
        time_val(const time_val& tv, long _s, long _us=0) {
            set(tv, _s, _us);
        }
        time_val(const time_val& a) : m_tv(a.m_tv) {}
        explicit time_val(const struct timeval& a) {
            m_tv.tv_sec=a.tv_sec; m_tv.tv_usec=a.tv_usec; normalize();
        }

        explicit time_val(struct tm& a_tm) {
            m_tv.tv_sec = mktime(&a_tm); m_tv.tv_usec = 0;
        }

        /// Set time to abosolute time given by \a a
        explicit time_val(const abs_time& a) {
            m_tv.tv_sec=a.sec; m_tv.tv_usec=a.usec; normalize();
        }

        /// Set time to relative offset from now given by \a a time.
        explicit time_val(const rel_time& a) { now(a.sec, a.usec); }

        #if __cplusplus >= 201103L
        time_val(time_val&& a) : m_tv(std::move(a.m_tv)) {}
        #endif

        const struct timeval&   timeval() const { return m_tv; }
        struct timeval&         timeval()       { return m_tv; }
        long                    sec()     const { return m_tv.tv_sec;  }
        long                    usec()    const { return m_tv.tv_usec; }
        time_t&                 sec()           { return m_tv.tv_sec;  }
        suseconds_t&            usec()          { return m_tv.tv_usec; }
        time_t                  msec()    const { return m_tv.tv_usec / 1000; }

        uint64_t microseconds() const {
            return (uint64_t)m_tv.tv_sec*N10e6 + (uint64_t)m_tv.tv_usec;
        }

        double seconds()          const { return  (double)m_tv.tv_sec
                                                + (double)m_tv.tv_usec/N10e6; }

        long milliseconds()       const { return m_tv.tv_sec*1000u + m_tv.tv_usec/1000; }
        void sec (size_t s)             { m_tv.tv_sec  = s;  }
        void usec(size_t us)            { m_tv.tv_usec = us; normalize(); }
        void microseconds(uint64_t ms)  { setd(ms, N10e6); }
        void milliseconds(size_t   ms)  { setd(ms, 1000);  }
        void nanosec (uint64_t ms)      { setd(ms, N10e9); }
        bool empty()              const { return sec() == 0 && usec() == 0; }

        void clear()                    { m_tv.tv_sec = 0; m_tv.tv_usec = 0; }

        void set(const time_val& tv, long _s=0, long _us=0) {
            m_tv.tv_sec = tv.sec() + _s; m_tv.tv_usec = tv.usec() + _us; normalize();
        }

        void set(const struct timeval& tv, long _s=0, long _us=0) {
            m_tv.tv_sec = tv.tv_sec + _s; m_tv.tv_usec = tv.tv_usec + _us; normalize();
        }

        void copy_to(struct timeval& tv) const {
            tv.tv_sec = m_tv.tv_sec; tv.tv_usec = m_tv.tv_usec;
        }

        double diff(const time_val& t) const {
            time_val tv(this->timeval());
            tv -= t;
            return (double)tv.sec() + (double)tv.usec() / N10e6;
        }

        void add(long _sec, long _us) {
            m_tv.tv_sec += _sec; m_tv.tv_usec += _us;
            if (_sec || _us) normalize();
        }

        void now() { ::gettimeofday(&m_tv, 0); }

        static time_val universal_time() {
            time_val tv; ::gettimeofday(&tv, 0); return tv;
        }

        time_val& now(long addS, long addUS=0) {
            ::gettimeofday(&m_tv, 0); add(addS, addUS);
            return *this;
        }

        const time_val* ptr() const { return reinterpret_cast<const time_val*>(&m_tv); }
        time_val*       ptr()       { return reinterpret_cast<time_val*>(&m_tv); }

        static double now_diff(const time_val& start) {
            time_val tv; tv.now(); tv -= start;
            return (double)tv.sec() + (double)tv.usec() / N10e6;
        }

        time_val operator- (const time_val& tv) const {
            return time_val(m_tv.tv_sec - tv.sec(), m_tv.tv_usec - tv.usec());
        }
        time_val operator+ (const time_val& tv) const {
            return time_val(m_tv.tv_sec + tv.sec(), m_tv.tv_usec + tv.usec());
        }
        time_val operator- (const struct timeval& tv) const {
            return time_val(m_tv.tv_sec - tv.tv_sec, m_tv.tv_usec - tv.tv_usec);
        }
        time_val operator+ (const struct timeval& tv) const {
            return time_val(m_tv.tv_sec + tv.tv_sec, m_tv.tv_usec + tv.tv_usec);
        }

        void operator-= (const struct timeval& tv) {
            m_tv.tv_sec -= tv.tv_sec; m_tv.tv_usec -= tv.tv_usec; normalize();
        }
        void operator-= (const time_val& tv) {
            m_tv.tv_sec -= tv.sec(); m_tv.tv_usec -= tv.usec(); normalize();
        }
        void operator+= (const time_val& tv) {
            m_tv.tv_sec += tv.sec(); m_tv.tv_usec += tv.usec(); normalize();
        }
        void operator+= (int32_t _sec)      { m_tv.tv_sec += _sec; }
        void operator+= (int64_t _microsec) {
            int64_t n = _microsec / N10e6;
            m_tv.tv_sec  += n;
            m_tv.tv_usec += (_microsec - (n * N10e6));
            normalize();
        }

        #if __cplusplus >= 201103L
        time_val& operator=(time_val&& a_rhs) {
            m_tv = a_rhs.m_tv;
            return *this;
        }
        #endif

        void operator= (const time_val& t) {
            m_tv.tv_sec = t.sec(); m_tv.tv_usec = t.usec();
        }
        void operator= (const struct timeval& t) {
            m_tv.tv_sec = t.tv_sec; m_tv.tv_usec = t.tv_usec;
        }
        struct timeval* operator& ()               { return &m_tv; }
        bool operator== (const time_val& tv) const {
            return sec() == tv.sec() && usec() == tv.usec();
        }
        bool operator!= (const time_val& tv) const { return !operator== (tv); }
        bool operator>  (const time_val& tv) const {
            return sec() > tv.sec() || (sec() == tv.sec() && usec() > tv.usec());
        }
        bool operator>= (const time_val& tv) const {
            return sec() > tv.sec() || (sec() == tv.sec() && usec() >= tv.usec());
        }
        bool operator<  (const time_val& tv) const {
            return sec() < tv.sec() || (sec() == tv.sec() && usec() < tv.usec());
        }
        bool operator<= (const time_val& tv) const {
            return sec() < tv.sec() || (sec() == tv.sec() && usec() <= tv.usec());
        }

        operator bool() const { return sec() == 0 && usec() == 0; }
    };

    template <typename T>
    time_val& time_val_cast(T& tv) {
        BOOST_STATIC_ASSERT(sizeof(T) == sizeof(struct timeval));
        return reinterpret_cast<time_val&>(tv);
    }

    template <typename T>
    const time_val& time_val_cast(const T& tv) {
        BOOST_STATIC_ASSERT(sizeof(T) == sizeof(struct timeval));
        return reinterpret_cast<const time_val&>(tv);
    }

    /// Same as gettimeofday() call
    inline time_val now_utc() { return time_val::universal_time(); }

    /// Simple timer for measuring interval of time
    ///
    /// Example usage1:
    /// \code
    ///     timer t; do_something(); double elapsed = t.elapsed();
    /// \endcode
    /// Example usage2:
    /// \code
    ///     time_val time;
    ///     {
    ///         timer t(time);
    ///         do_something();
    ///     }
    ///     double elapsed = time.seconds();
    /// \endcode
    class timer {
        time_val* m_result;
        time_val  m_started;
    public:
        timer() : m_result(NULL), m_started(time_val::universal_time()) {}
        timer(time_val& tv) : m_result(tv.ptr()), m_started(time_val::universal_time()) {}

        ~timer() { if (m_result) *m_result = time_val::universal_time() - m_started; }

        void   reset() { m_started = time_val::universal_time(); }

        double elapsed() const { return time_val::now_diff(m_started); }
    };

} // namespace utxx

#endif // _UTXX_TIME_VAL_HPP_
<|endoftext|>


<commit_before>#pragma once

#include "resourcemapper.hpp"
#include "unzip.h"
#include "ioapi.h"

// Actually "ZIP64" file system, which removes 65k file limit and 4GB zip file size limit
class ZipFileSystem
{
public:
    ZipFileSystem()
    {
        zlib_filefunc_def filefunc32 = { 0 };

        unzOpen2("__notused__", &filefunc32);
    }
};
<commit_msg>current<commit_after>#pragma once

#include "resourcemapper.hpp"
#include "unzip.h"
#include "ioapi.h"
#include "iowin32.h"

// Actually "ZIP64" file system, which removes 65k file limit and 4GB zip file size limit
class ZipFileSystem
{
public:
    ZipFileSystem()
    {
        zlib_filefunc64_def filefunc32 = { };

        //fill_win32_filefunc64(&filefunc32);
        fill_fopen64_filefunc(&filefunc32);

        unzFile  f = unzOpen2_64("__notused__", &filefunc32);
        if (f)
        {
            unz_file_info64 fileInfo = {};
            unzGetCurrentFileInfo64(f, &fileInfo, "test.txt", 0, 0, 0, 0, 0);

            char buffer[10];
            unzReadCurrentFile(f, buffer, 10);

            unzClose(f);
        }
    }
};
<|endoftext|>


<commit_before><commit_msg>coverity#704879 Dereference after null check<commit_after><|endoftext|>


<commit_before>// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Physics 2D module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/Physics2D/RigidBody2D.hpp>
#include <Nazara/Math/Algorithm.hpp>
#include <Nazara/Physics2D/Config.hpp>
#include <Nazara/Physics2D/PhysWorld2D.hpp>
#include <chipmunk/chipmunk.h>
#include <chipmunk/chipmunk_private.h>
#include <algorithm>
#include <Nazara/Physics3D/Debug.hpp>

namespace Nz
{
	RigidBody2D::RigidBody2D(PhysWorld2D* world, float mass) :
	RigidBody2D(world, mass, nullptr)
	{
	}

	RigidBody2D::RigidBody2D(PhysWorld2D* world, float mass, Collider2DRef geom) :
	m_geom(),
	m_world(world),
	m_gravityFactor(1.f),
	m_mass(0.f)
	{
		NazaraAssert(m_world, "Invalid world");

		Create();

		SetGeom(geom);
		SetMass(mass);
	}

	RigidBody2D::RigidBody2D(const RigidBody2D& object) :
	m_geom(object.m_geom),
	m_world(object.m_world),
	m_gravityFactor(object.m_gravityFactor),
	m_mass(0.f)
	{
		NazaraAssert(m_world, "Invalid world");
		NazaraAssert(m_geom, "Invalid geometry");

		Create();

		SetGeom(object.GetGeom());
		SetMass(object.GetMass());
	}

	RigidBody2D::RigidBody2D(RigidBody2D&& object) :
	m_shapes(std::move(object.m_shapes)),
	m_geom(std::move(object.m_geom)),
	m_handle(object.m_handle),
	m_world(object.m_world),
	m_gravityFactor(object.m_gravityFactor),
	m_mass(object.m_mass)
	{
		object.m_handle = nullptr;
	}

	RigidBody2D::~RigidBody2D()
	{
		Destroy();
	}

	void RigidBody2D::AddForce(const Vector2f& force, CoordSys coordSys)
	{
		return AddForce(force, GetCenterOfGravity(coordSys), coordSys);
	}

	void RigidBody2D::AddForce(const Vector2f& force, const Vector2f& point, CoordSys coordSys)
	{
		switch (coordSys)
		{
			case CoordSys_Global:
				cpBodyApplyForceAtWorldPoint(m_handle, cpv(force.x, force.y), cpv(force.x, force.y));
				break;

			case CoordSys_Local:
				cpBodyApplyForceAtLocalPoint(m_handle, cpv(force.x, force.y), cpv(point.x, point.y));
				break;
		}
	}

	void RigidBody2D::AddTorque(float torque)
	{
		cpBodySetTorque(m_handle, cpBodyGetTorque(m_handle) + torque);
	}

	Rectf RigidBody2D::GetAABB() const
	{
		cpBB bb = cpBBNew(0.f, 0.f, 0.f, 0.f);
		for (cpShape* shape : m_shapes)
			bb = cpBBMerge(bb, cpShapeGetBB(shape));

		return Rectf(Rect<cpFloat>(bb.l, bb.t, bb.r - bb.l, bb.b - bb.t));
	}

	float RigidBody2D::GetAngularVelocity() const
	{
		return static_cast<float>(cpBodyGetAngularVelocity(m_handle));
	}

	const Collider2DRef& RigidBody2D::GetGeom() const
	{
		return m_geom;
	}

	cpBody* RigidBody2D::GetHandle() const
	{
		return m_handle;
	}

	float RigidBody2D::GetMass() const
	{
		return m_mass;
	}

	Vector2f RigidBody2D::GetCenterOfGravity(CoordSys coordSys) const
	{
		cpVect cog = cpBodyGetCenterOfGravity(m_handle);

		switch (coordSys)
		{
			case CoordSys_Global:
				cog = cpBodyLocalToWorld(m_handle, cog);
				break;

			case CoordSys_Local:
				break; // Nothing to do
		}

		return Vector2f(static_cast<float>(cog.x), static_cast<float>(cog.y));
	}

	Vector2f RigidBody2D::GetPosition() const
	{
		cpVect pos = cpBodyGetPosition(m_handle);
		return Vector2f(static_cast<float>(pos.x), static_cast<float>(pos.y));
	}

	float RigidBody2D::GetRotation() const
	{
		return static_cast<float>(cpBodyGetAngle(m_handle));
	}

	Vector2f RigidBody2D::GetVelocity() const
	{
		cpVect vel = cpBodyGetVelocity(m_handle);
		return Vector2f(static_cast<float>(vel.x), static_cast<float>(vel.y));
	}

	bool RigidBody2D::IsMoveable() const
	{
		return m_mass > 0.f;
	}

	bool RigidBody2D::IsSleeping() const
	{
		return cpBodyIsSleeping(m_handle) != 0;
	}

	void RigidBody2D::SetAngularVelocity(float angularVelocity)
	{
		cpBodySetAngularVelocity(m_handle, angularVelocity);
	}

	void RigidBody2D::SetGeom(Collider2DRef geom)
	{
		// We have no public way of getting rid of an existing geom without removing the whole body
		// So let's save some attributes of the body, destroy it and rebuild it
		if (m_geom)
		{
			cpVect pos = cpBodyGetPosition(m_handle);
			cpFloat mass = cpBodyGetMass(m_handle);
			cpFloat moment = cpBodyGetMoment(m_handle);
			cpFloat rot = cpBodyGetAngle(m_handle);
			cpVect vel = cpBodyGetVelocity(m_handle);

			Destroy();
			Create(mass, moment);

			cpBodySetAngle(m_handle, rot);
			cpBodySetPosition(m_handle, pos);
			cpBodySetVelocity(m_handle, vel);
		}

		if (geom)
			m_geom = geom;
		else
			m_geom = NullCollider2D::New();

		m_shapes = m_geom->CreateShapes(this);
	}

	void RigidBody2D::SetMass(float mass)
	{
		if (m_mass > 0.f)
		{
			if (mass > 0.f)
				cpBodySetMass(m_handle, mass);
			else
				cpBodySetType(m_handle, CP_BODY_TYPE_STATIC);
		}
		else if (mass > 0.f)
		{
			if (cpBodyGetType(m_handle) == CP_BODY_TYPE_STATIC)
			{
				cpBodySetType(m_handle, CP_BODY_TYPE_DYNAMIC);
				cpBodySetMass(m_handle, mass);
			}
		}

		m_mass = mass;
	}

	void RigidBody2D::SetMassCenter(const Vector2f& center)
	{
		if (m_mass > 0.f)
			cpBodySetCenterOfGravity(m_handle, cpv(center.x, center.y));
	}

	void RigidBody2D::SetPosition(const Vector2f& position)
	{
		cpBodySetPosition(m_handle, cpv(position.x, position.y));
	}

	void RigidBody2D::SetRotation(float rotation)
	{
		cpBodySetAngle(m_handle, rotation);
	}

	void RigidBody2D::SetVelocity(const Vector2f& velocity)
	{
		cpBodySetVelocity(m_handle, cpv(velocity.x, velocity.y));
	}

	RigidBody2D& RigidBody2D::operator=(const RigidBody2D& object)
	{
		RigidBody2D physObj(object);
		return operator=(std::move(physObj));
	}

	RigidBody2D& RigidBody2D::operator=(RigidBody2D&& object)
	{
		Destroy();

		m_handle             = object.m_handle;
		m_geom               = std::move(object.m_geom);
		m_gravityFactor      = object.m_gravityFactor;
		m_mass               = object.m_mass;
		m_shapes             = std::move(object.m_shapes);
		m_world              = object.m_world;

		object.m_handle = nullptr;

		return *this;
	}

	void RigidBody2D::Create(float mass, float moment)
	{
		m_handle = cpBodyNew(mass, moment);
		cpBodySetUserData(m_handle, this);
		cpSpaceAddBody(m_world->GetHandle(), m_handle);
	}

	void RigidBody2D::Destroy()
	{
		for (cpShape* shape : m_shapes)
			cpShapeFree(shape);

		if (m_handle)
			cpBodyFree(m_handle);
	}
}
<commit_msg>Physics2D/RigidBody2D: Fix removal of body from space<commit_after>// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Physics 2D module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/Physics2D/RigidBody2D.hpp>
#include <Nazara/Math/Algorithm.hpp>
#include <Nazara/Physics2D/Config.hpp>
#include <Nazara/Physics2D/PhysWorld2D.hpp>
#include <chipmunk/chipmunk.h>
#include <chipmunk/chipmunk_private.h>
#include <algorithm>
#include <Nazara/Physics3D/Debug.hpp>

namespace Nz
{
	RigidBody2D::RigidBody2D(PhysWorld2D* world, float mass) :
	RigidBody2D(world, mass, nullptr)
	{
	}

	RigidBody2D::RigidBody2D(PhysWorld2D* world, float mass, Collider2DRef geom) :
	m_geom(),
	m_world(world),
	m_gravityFactor(1.f),
	m_mass(0.f)
	{
		NazaraAssert(m_world, "Invalid world");

		Create();

		SetGeom(geom);
		SetMass(mass);
	}

	RigidBody2D::RigidBody2D(const RigidBody2D& object) :
	m_geom(object.m_geom),
	m_world(object.m_world),
	m_gravityFactor(object.m_gravityFactor),
	m_mass(0.f)
	{
		NazaraAssert(m_world, "Invalid world");
		NazaraAssert(m_geom, "Invalid geometry");

		Create();

		SetGeom(object.GetGeom());
		SetMass(object.GetMass());
	}

	RigidBody2D::RigidBody2D(RigidBody2D&& object) :
	m_shapes(std::move(object.m_shapes)),
	m_geom(std::move(object.m_geom)),
	m_handle(object.m_handle),
	m_world(object.m_world),
	m_gravityFactor(object.m_gravityFactor),
	m_mass(object.m_mass)
	{
		object.m_handle = nullptr;
	}

	RigidBody2D::~RigidBody2D()
	{
		Destroy();
	}

	void RigidBody2D::AddForce(const Vector2f& force, CoordSys coordSys)
	{
		return AddForce(force, GetCenterOfGravity(coordSys), coordSys);
	}

	void RigidBody2D::AddForce(const Vector2f& force, const Vector2f& point, CoordSys coordSys)
	{
		switch (coordSys)
		{
			case CoordSys_Global:
				cpBodyApplyForceAtWorldPoint(m_handle, cpv(force.x, force.y), cpv(force.x, force.y));
				break;

			case CoordSys_Local:
				cpBodyApplyForceAtLocalPoint(m_handle, cpv(force.x, force.y), cpv(point.x, point.y));
				break;
		}
	}

	void RigidBody2D::AddTorque(float torque)
	{
		cpBodySetTorque(m_handle, cpBodyGetTorque(m_handle) + torque);
	}

	Rectf RigidBody2D::GetAABB() const
	{
		cpBB bb = cpBBNew(0.f, 0.f, 0.f, 0.f);
		for (cpShape* shape : m_shapes)
			bb = cpBBMerge(bb, cpShapeGetBB(shape));

		return Rectf(Rect<cpFloat>(bb.l, bb.t, bb.r - bb.l, bb.b - bb.t));
	}

	float RigidBody2D::GetAngularVelocity() const
	{
		return static_cast<float>(cpBodyGetAngularVelocity(m_handle));
	}

	const Collider2DRef& RigidBody2D::GetGeom() const
	{
		return m_geom;
	}

	cpBody* RigidBody2D::GetHandle() const
	{
		return m_handle;
	}

	float RigidBody2D::GetMass() const
	{
		return m_mass;
	}

	Vector2f RigidBody2D::GetCenterOfGravity(CoordSys coordSys) const
	{
		cpVect cog = cpBodyGetCenterOfGravity(m_handle);

		switch (coordSys)
		{
			case CoordSys_Global:
				cog = cpBodyLocalToWorld(m_handle, cog);
				break;

			case CoordSys_Local:
				break; // Nothing to do
		}

		return Vector2f(static_cast<float>(cog.x), static_cast<float>(cog.y));
	}

	Vector2f RigidBody2D::GetPosition() const
	{
		cpVect pos = cpBodyGetPosition(m_handle);
		return Vector2f(static_cast<float>(pos.x), static_cast<float>(pos.y));
	}

	float RigidBody2D::GetRotation() const
	{
		return static_cast<float>(cpBodyGetAngle(m_handle));
	}

	Vector2f RigidBody2D::GetVelocity() const
	{
		cpVect vel = cpBodyGetVelocity(m_handle);
		return Vector2f(static_cast<float>(vel.x), static_cast<float>(vel.y));
	}

	bool RigidBody2D::IsMoveable() const
	{
		return m_mass > 0.f;
	}

	bool RigidBody2D::IsSleeping() const
	{
		return cpBodyIsSleeping(m_handle) != 0;
	}

	void RigidBody2D::SetAngularVelocity(float angularVelocity)
	{
		cpBodySetAngularVelocity(m_handle, angularVelocity);
	}

	void RigidBody2D::SetGeom(Collider2DRef geom)
	{
		// We have no public way of getting rid of an existing geom without removing the whole body
		// So let's save some attributes of the body, destroy it and rebuild it
		if (m_geom)
		{
			cpVect pos = cpBodyGetPosition(m_handle);
			cpFloat mass = cpBodyGetMass(m_handle);
			cpFloat moment = cpBodyGetMoment(m_handle);
			cpFloat rot = cpBodyGetAngle(m_handle);
			cpVect vel = cpBodyGetVelocity(m_handle);

			Destroy();
			Create(mass, moment);

			cpBodySetAngle(m_handle, rot);
			cpBodySetPosition(m_handle, pos);
			cpBodySetVelocity(m_handle, vel);
		}

		if (geom)
			m_geom = geom;
		else
			m_geom = NullCollider2D::New();

		m_shapes = m_geom->CreateShapes(this);
	}

	void RigidBody2D::SetMass(float mass)
	{
		if (m_mass > 0.f)
		{
			if (mass > 0.f)
				cpBodySetMass(m_handle, mass);
			else
				cpBodySetType(m_handle, CP_BODY_TYPE_STATIC);
		}
		else if (mass > 0.f)
		{
			if (cpBodyGetType(m_handle) == CP_BODY_TYPE_STATIC)
			{
				cpBodySetType(m_handle, CP_BODY_TYPE_DYNAMIC);
				cpBodySetMass(m_handle, mass);
			}
		}

		m_mass = mass;
	}

	void RigidBody2D::SetMassCenter(const Vector2f& center)
	{
		if (m_mass > 0.f)
			cpBodySetCenterOfGravity(m_handle, cpv(center.x, center.y));
	}

	void RigidBody2D::SetPosition(const Vector2f& position)
	{
		cpBodySetPosition(m_handle, cpv(position.x, position.y));
	}

	void RigidBody2D::SetRotation(float rotation)
	{
		cpBodySetAngle(m_handle, rotation);
	}

	void RigidBody2D::SetVelocity(const Vector2f& velocity)
	{
		cpBodySetVelocity(m_handle, cpv(velocity.x, velocity.y));
	}

	RigidBody2D& RigidBody2D::operator=(const RigidBody2D& object)
	{
		RigidBody2D physObj(object);
		return operator=(std::move(physObj));
	}

	RigidBody2D& RigidBody2D::operator=(RigidBody2D&& object)
	{
		Destroy();

		m_handle             = object.m_handle;
		m_geom               = std::move(object.m_geom);
		m_gravityFactor      = object.m_gravityFactor;
		m_mass               = object.m_mass;
		m_shapes             = std::move(object.m_shapes);
		m_world              = object.m_world;

		object.m_handle = nullptr;

		return *this;
	}

	void RigidBody2D::Create(float mass, float moment)
	{
		m_handle = cpBodyNew(mass, moment);
		cpBodySetUserData(m_handle, this);
		cpSpaceAddBody(m_world->GetHandle(), m_handle);
	}

	void RigidBody2D::Destroy()
	{
		for (cpShape* shape : m_shapes)
			cpShapeFree(shape);

		if (m_handle)
		{
			cpSpaceRemoveBody(m_world->GetHandle(), m_handle);
			cpBodyFree(m_handle);
		}
	}
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <xmloff/ProgressBarHelper.hxx>
#include <xmloff/xmltoken.hxx>

#include <stdlib.h>

using namespace ::com::sun::star;

static const sal_Int32 nDefaultProgressBarRange = 1000000;

ProgressBarHelper::ProgressBarHelper(const ::com::sun::star::uno::Reference < ::com::sun::star::task::XStatusIndicator>& xTempStatusIndicator,
                                    const bool bTempStrict)
: xStatusIndicator(xTempStatusIndicator)
, nRange(nDefaultProgressBarRange)
, nReference(100)
, nValue(0)
, bStrict(bTempStrict)
, bRepeat(true)
#ifdef DBG_UTIL
, bFailure(false)
#endif
{
}

ProgressBarHelper::~ProgressBarHelper()
{
}

sal_Int32 ProgressBarHelper::ChangeReference(sal_Int32 nNewReference)
{
    if((nNewReference > 0) && (nNewReference != nReference))
    {
        if (nReference)
        {
            double fPercent(nNewReference / nReference);
            double fValue(nValue * fPercent);
#if OSL_DEBUG_LEVEL > 0
            // workaround for toolchain bug on solaris/x86 Sun C++ 5.5
            // just call some function here
            (void) abs(nValue);
#endif
            nValue = static_cast< sal_Int32 >(fValue);
            nReference = nNewReference;
        }
        else
        {
            nReference = nNewReference;
            nValue = 0;
        }
    }
    return nValue;
}

void ProgressBarHelper::SetValue(sal_Int32 nTempValue)
{
    if (xStatusIndicator.is() && (nReference > 0))
    {
        if ((nTempValue >= nValue) && (!bStrict || (bStrict && (nTempValue <= nReference))))
        {
            // #91317# no progress bar with values > 100%
            if (nTempValue > nReference)
            {
                if (!bRepeat)
                    nValue = nReference;
                else
                {
                    xStatusIndicator->reset();
                    nValue = 0;
                }
            }
            else
                nValue = nTempValue;

            double fValue(nValue);
            double fNewValue ((fValue * nRange) / nReference);

            xStatusIndicator->setValue((sal_Int32)fNewValue);

            // #95181# disabled, because we want to call setValue very often to enable a good reschedule
        }
#ifdef DBG_UTIL
        else if (!bFailure)
        {
            OSL_FAIL("tried to set a wrong value on the progressbar");
            bFailure = true;
        }
#endif
    }
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>xmloff: remove yet another SunStudio workaround<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <xmloff/ProgressBarHelper.hxx>
#include <xmloff/xmltoken.hxx>

using namespace ::com::sun::star;

static const sal_Int32 nDefaultProgressBarRange = 1000000;

ProgressBarHelper::ProgressBarHelper(const ::com::sun::star::uno::Reference < ::com::sun::star::task::XStatusIndicator>& xTempStatusIndicator,
                                    const bool bTempStrict)
: xStatusIndicator(xTempStatusIndicator)
, nRange(nDefaultProgressBarRange)
, nReference(100)
, nValue(0)
, bStrict(bTempStrict)
, bRepeat(true)
#ifdef DBG_UTIL
, bFailure(false)
#endif
{
}

ProgressBarHelper::~ProgressBarHelper()
{
}

sal_Int32 ProgressBarHelper::ChangeReference(sal_Int32 nNewReference)
{
    if((nNewReference > 0) && (nNewReference != nReference))
    {
        if (nReference)
        {
            double fPercent(nNewReference / nReference);
            double fValue(nValue * fPercent);
            nValue = static_cast<sal_Int32>(fValue);
            nReference = nNewReference;
        }
        else
        {
            nReference = nNewReference;
            nValue = 0;
        }
    }
    return nValue;
}

void ProgressBarHelper::SetValue(sal_Int32 nTempValue)
{
    if (xStatusIndicator.is() && (nReference > 0))
    {
        if ((nTempValue >= nValue) && (!bStrict || (bStrict && (nTempValue <= nReference))))
        {
            // #91317# no progress bar with values > 100%
            if (nTempValue > nReference)
            {
                if (!bRepeat)
                    nValue = nReference;
                else
                {
                    xStatusIndicator->reset();
                    nValue = 0;
                }
            }
            else
                nValue = nTempValue;

            double fValue(nValue);
            double fNewValue ((fValue * nRange) / nReference);

            xStatusIndicator->setValue((sal_Int32)fNewValue);

            // #95181# disabled, because we want to call setValue very often to enable a good reschedule
        }
#ifdef DBG_UTIL
        else if (!bFailure)
        {
            OSL_FAIL("tried to set a wrong value on the progressbar");
            bFailure = true;
        }
#endif
    }
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before><commit_msg>SwpHintsArray: deploy some asserts<commit_after><|endoftext|>