<commit_before>#ifndef ITER_RANGE_H_
#define ITER_RANGE_H_

#include "internal/iterbase.hpp"

#include <cassert>
#include <exception>
#include <iterator>
#include <type_traits>

namespace iter {
  namespace impl {
    template <typename T>
    class Range;
  }

  template <typename T>
  constexpr impl::Range<T> range(T) noexcept;
  template <typename T>
  constexpr impl::Range<T> range(T, T) noexcept;
  template <typename T>
  constexpr impl::Range<T> range(T, T, T) noexcept;
}

namespace iter {
  namespace detail {
    template <typename T, bool IsFloat = std::is_floating_point<T>::value>
    class RangeIterData;

    // everything except floats
    template <typename T>
    class RangeIterData<T, false> {
     private:
      T value_{};
      T step_{};

     public:
      constexpr RangeIterData() noexcept = default;
      constexpr RangeIterData(T in_value, T in_step) noexcept
          : value_{in_value},
            step_{in_step} {}

      constexpr T value() const noexcept {
        return value_;
      }

      constexpr T step() const noexcept {
        return step_;
      }

      void inc() noexcept {
        value_ += step_;
      }

      constexpr bool operator==(const RangeIterData& other) const noexcept {
        return value_ == other.value_;
      }

      constexpr bool operator!=(const RangeIterData& other) const noexcept {
        return !(*this == other);
      }
    };

    // float data
    template <typename T>
    class RangeIterData<T, true> {
     private:
      T start_{};
      T value_{};
      T step_{};
      std::size_t steps_taken_{};

     public:
      constexpr RangeIterData() noexcept = default;
      constexpr RangeIterData(T in_start, T in_step) noexcept
          : start_{in_start},
            value_{in_start},
            step_{in_step} {}

      constexpr T value() const noexcept {
        return value_;
      }

      constexpr T step() const noexcept {
        return step_;
      }

      void inc() noexcept {
        ++steps_taken_;
        value_ = start_ + (step_ * steps_taken_);
      }

      constexpr bool operator==(const RangeIterData& other) const noexcept {
        // if the difference between the two values is less than the
        // step_ size, they are considered equal
        return (value_ < other.value_ ? other.value_ - value_
                                      : value_ - other.value_)
               < step_;
      }

      constexpr bool operator!=(const RangeIterData& other) const noexcept {
        return !(*this == other);
      }
    };
  }
}

template <typename T>
class iter::impl::Range {
  // see stackoverflow.com/questions/32174186 about why only specializations
  // aren't marked as friend
  template <typename U>
  friend constexpr Range<U> iter::range(U) noexcept;
  template <typename U>
  friend constexpr Range<U> iter::range(U, U) noexcept;
  template <typename U>
  friend constexpr Range<U> iter::range(U, U, U) noexcept;

 private:
  const T start_;
  const T stop_;
  const T step_;

  constexpr Range(T stop) noexcept : start_{0}, stop_{stop}, step_{1} {}

  constexpr Range(T start, T stop, T step = 1) noexcept : start_{start},
                                                          stop_{stop},
                                                          step_{step} {}

 public:
  // the reference type here is T, which doesn't strictly follow all
  // of the rules, but std::vector<bool>::iterator::reference isn't
  // a reference type either, this isn't any worse

  class Iterator {
   private:
    iter::detail::RangeIterData<T> data;
    bool is_end;

    // compare unsigned values
    static bool not_equal_to_impl(const Iterator& iter,
        const Iterator& end_iter, std::true_type) noexcept {
      assert(!iter.is_end);
      assert(end_iter.is_end);
      return iter.data.value() < end_iter.data.value();
    }

    // compare signed values
    static bool not_equal_to_impl(const Iterator& iter,
        const Iterator& end_iter, std::false_type) noexcept {
      assert(!iter.is_end);
      assert(end_iter.is_end);
      return !(iter.data.step() > 0
                 && iter.data.value() >= end_iter.data.value())
             && !(iter.data.step() < 0
                    && iter.data.value() <= end_iter.data.value());
    }

    static bool not_equal_to_end(
        const Iterator& lhs, const Iterator& rhs) noexcept {
      if (rhs.is_end) {
        return not_equal_to_impl(lhs, rhs, std::is_unsigned<T>{});
      }
      return not_equal_to_impl(rhs, lhs, std::is_unsigned<T>{});
    }

   public:
    using iterator_category = std::forward_iterator_tag;
    using value_type = T;
    using difference_type = std::ptrdiff_t;
    using pointer = value_type*;
    using reference = value_type&;

    constexpr Iterator() noexcept = default;

    constexpr Iterator(T in_value, T in_step, bool in_is_end) noexcept
        : data(in_value, in_step),
          is_end{in_is_end} {}

    constexpr T operator*() const noexcept {
      return data.value();
    }

    constexpr ArrowProxy<T> operator->() const noexcept {
      return {**this};
    }

    Iterator& operator++() noexcept {
      data.inc();
      return *this;
    }

    Iterator operator++(int)noexcept {
      auto ret = *this;
      ++*this;
      return ret;
    }

    // This operator would more accurately read as "in bounds"
    // or "incomplete" because exact comparison with the end
    // isn't good enough for the purposes of this Iterator.
    // There are two odd cases that need to be handled
    //
    // 1) The Range is infinite, such as
    // Range (-1, 0, -1) which would go forever down toward
    // infinitely (theoretically).  If this occurs, the Range
    // will instead effectively be empty
    //
    // 2) (stop_ - start_) % step_ != 0.  For
    // example Range(1, 10, 2).  The iterator will never be
    // exactly equal to the stop_ value.
    //
    // Another way to think about it is that the "end"
    // iterator represents the range of values that are invalid
    // So, if an iterator is not equal to that, it is valid
    //
    // Two end iterators will compare equal
    //
    // Two non-end iterators will compare by their stored values
    bool operator!=(const Iterator& other) const noexcept {
      if (is_end && other.is_end) {
        return false;
      }

      if (!is_end && !other.is_end) {
        return data != other.data;
      }
      return not_equal_to_end(*this, other);
    }

    bool operator==(const Iterator& other) const noexcept {
      return !(*this != other);
    }
  };

  constexpr Iterator begin() const noexcept {
    return {start_, step_, false};
  }

  constexpr Iterator end() const noexcept {
    return {stop_, step_, true};
  }
};

template <typename T>
constexpr iter::impl::Range<T> iter::range(T stop_) noexcept {
  return {stop_};
}

template <typename T>
constexpr iter::impl::Range<T> iter::range(T start_, T stop_) noexcept {
  return {start_, stop_};
}

template <typename T>
constexpr iter::impl::Range<T> iter::range(
    T start_, T stop_, T step_) noexcept {
  return step_ == T(0) ? impl::Range<T>{0}
                       : impl::Range<T>{start_, stop_, step_};
}

#endif
<commit_msg>Fix Range<T>::Iterator::reference<commit_after>#ifndef ITER_RANGE_H_
#define ITER_RANGE_H_

#include "internal/iterbase.hpp"

#include <cassert>
#include <exception>
#include <iterator>
#include <type_traits>

namespace iter {
  namespace impl {
    template <typename T>
    class Range;
  }

  template <typename T>
  constexpr impl::Range<T> range(T) noexcept;
  template <typename T>
  constexpr impl::Range<T> range(T, T) noexcept;
  template <typename T>
  constexpr impl::Range<T> range(T, T, T) noexcept;
}

namespace iter {
  namespace detail {
    template <typename T, bool IsFloat = std::is_floating_point<T>::value>
    class RangeIterData;

    // everything except floats
    template <typename T>
    class RangeIterData<T, false> {
     private:
      T value_{};
      T step_{};

     public:
      constexpr RangeIterData() noexcept = default;
      constexpr RangeIterData(T in_value, T in_step) noexcept
          : value_{in_value},
            step_{in_step} {}

      constexpr T value() const noexcept {
        return value_;
      }

      constexpr T step() const noexcept {
        return step_;
      }

      void inc() noexcept {
        value_ += step_;
      }

      constexpr bool operator==(const RangeIterData& other) const noexcept {
        return value_ == other.value_;
      }

      constexpr bool operator!=(const RangeIterData& other) const noexcept {
        return !(*this == other);
      }
    };

    // float data
    template <typename T>
    class RangeIterData<T, true> {
     private:
      T start_{};
      T value_{};
      T step_{};
      std::size_t steps_taken_{};

     public:
      constexpr RangeIterData() noexcept = default;
      constexpr RangeIterData(T in_start, T in_step) noexcept
          : start_{in_start},
            value_{in_start},
            step_{in_step} {}

      constexpr T value() const noexcept {
        return value_;
      }

      constexpr T step() const noexcept {
        return step_;
      }

      void inc() noexcept {
        ++steps_taken_;
        value_ = start_ + (step_ * steps_taken_);
      }

      constexpr bool operator==(const RangeIterData& other) const noexcept {
        // if the difference between the two values is less than the
        // step_ size, they are considered equal
        return (value_ < other.value_ ? other.value_ - value_
                                      : value_ - other.value_)
               < step_;
      }

      constexpr bool operator!=(const RangeIterData& other) const noexcept {
        return !(*this == other);
      }
    };
  }
}

template <typename T>
class iter::impl::Range {
  // see stackoverflow.com/questions/32174186 about why only specializations
  // aren't marked as friend
  template <typename U>
  friend constexpr Range<U> iter::range(U) noexcept;
  template <typename U>
  friend constexpr Range<U> iter::range(U, U) noexcept;
  template <typename U>
  friend constexpr Range<U> iter::range(U, U, U) noexcept;

 private:
  const T start_;
  const T stop_;
  const T step_;

  constexpr Range(T stop) noexcept : start_{0}, stop_{stop}, step_{1} {}

  constexpr Range(T start, T stop, T step = 1) noexcept : start_{start},
                                                          stop_{stop},
                                                          step_{step} {}

 public:
  // the reference type here is T, which doesn't strictly follow all
  // of the rules, but std::vector<bool>::iterator::reference isn't
  // a reference type either, this isn't any worse

  class Iterator {
   private:
    iter::detail::RangeIterData<T> data;
    bool is_end;

    // compare unsigned values
    static bool not_equal_to_impl(const Iterator& iter,
        const Iterator& end_iter, std::true_type) noexcept {
      assert(!iter.is_end);
      assert(end_iter.is_end);
      return iter.data.value() < end_iter.data.value();
    }

    // compare signed values
    static bool not_equal_to_impl(const Iterator& iter,
        const Iterator& end_iter, std::false_type) noexcept {
      assert(!iter.is_end);
      assert(end_iter.is_end);
      return !(iter.data.step() > 0
                 && iter.data.value() >= end_iter.data.value())
             && !(iter.data.step() < 0
                    && iter.data.value() <= end_iter.data.value());
    }

    static bool not_equal_to_end(
        const Iterator& lhs, const Iterator& rhs) noexcept {
      if (rhs.is_end) {
        return not_equal_to_impl(lhs, rhs, std::is_unsigned<T>{});
      }
      return not_equal_to_impl(rhs, lhs, std::is_unsigned<T>{});
    }

   public:
    using iterator_category = std::forward_iterator_tag;
    using value_type = T;
    using difference_type = std::ptrdiff_t;
    using pointer = value_type*;
    using reference = value_type;

    constexpr Iterator() noexcept = default;

    constexpr Iterator(T in_value, T in_step, bool in_is_end) noexcept
        : data(in_value, in_step),
          is_end{in_is_end} {}

    constexpr T operator*() const noexcept {
      return data.value();
    }

    constexpr ArrowProxy<T> operator->() const noexcept {
      return {**this};
    }

    Iterator& operator++() noexcept {
      data.inc();
      return *this;
    }

    Iterator operator++(int)noexcept {
      auto ret = *this;
      ++*this;
      return ret;
    }

    // This operator would more accurately read as "in bounds"
    // or "incomplete" because exact comparison with the end
    // isn't good enough for the purposes of this Iterator.
    // There are two odd cases that need to be handled
    //
    // 1) The Range is infinite, such as
    // Range (-1, 0, -1) which would go forever down toward
    // infinitely (theoretically).  If this occurs, the Range
    // will instead effectively be empty
    //
    // 2) (stop_ - start_) % step_ != 0.  For
    // example Range(1, 10, 2).  The iterator will never be
    // exactly equal to the stop_ value.
    //
    // Another way to think about it is that the "end"
    // iterator represents the range of values that are invalid
    // So, if an iterator is not equal to that, it is valid
    //
    // Two end iterators will compare equal
    //
    // Two non-end iterators will compare by their stored values
    bool operator!=(const Iterator& other) const noexcept {
      if (is_end && other.is_end) {
        return false;
      }

      if (!is_end && !other.is_end) {
        return data != other.data;
      }
      return not_equal_to_end(*this, other);
    }

    bool operator==(const Iterator& other) const noexcept {
      return !(*this != other);
    }
  };

  constexpr Iterator begin() const noexcept {
    return {start_, step_, false};
  }

  constexpr Iterator end() const noexcept {
    return {stop_, step_, true};
  }
};

template <typename T>
constexpr iter::impl::Range<T> iter::range(T stop_) noexcept {
  return {stop_};
}

template <typename T>
constexpr iter::impl::Range<T> iter::range(T start_, T stop_) noexcept {
  return {start_, stop_};
}

template <typename T>
constexpr iter::impl::Range<T> iter::range(
    T start_, T stop_, T step_) noexcept {
  return step_ == T(0) ? impl::Range<T>{0}
                       : impl::Range<T>{start_, stop_, step_};
}

#endif
<|endoftext|>


<commit_before>/*
 * Demonstration of how we might port the Python h2olog to C++.
 * Compile with: "g++ -o h2olog -I/usr/include/bcc/compat h2olog.cc -lbcc"
 */

#include <bcc/BPF.h>
#include <iostream>

const std::string QUIC_BPF = R"(
struct event_t {
  uint64_t at;
};

BPF_PERF_OUTPUT(events);

int trace_quicly__accept(struct pt_regs *ctx) {
  struct event_t event = {};
  bpf_usdt_readarg(2, ctx, &event.at);
  events.perf_submit(ctx, &event, sizeof(event));
  return 0;
}
)";

#define POLL_TIMEOUT 100

struct event_t {
  uint64_t at;
};

void handle_quic_event(void *cpu, void *data, int len) {
  struct event_t *ev = (event_t*)data;
  std::cout << "time: " << ev->at << std::endl;
}

int main(int argc, char **argv) {
  // Simplified for demonstration purpose.
  pid_t pid = -1;
  if (argc < 2) {
    std::cerr << "h2olog <pid>" << std::endl;
    return 1;
  }
  pid = std::atoi(argv[1]);

  ebpf::BPF *bpf = new ebpf::BPF();
  ebpf::USDT u("", pid, "quicly", "accept", "trace_quicly__accept");
  ebpf::StatusTuple ret = bpf->init(QUIC_BPF, {}, {u});
  if (ret.code() != 0) {
    std::cerr << ret.msg() << std::endl;
    return 1;
  }

  ret = bpf->attach_usdt(u);
  if (ret.code() != 0) {
    std::cerr << ret.msg() << std::endl;
    return 1;
  }

  ret = bpf->open_perf_buffer("events", &handle_quic_event);
  if (ret.code() != 0) {
    std::cerr << ret.msg() << std::endl;
    return 1;
  }

  ebpf::BPFPerfBuffer *perf_buffer = bpf->get_perf_buffer("events");
  if (perf_buffer)
    while (true)
      perf_buffer->poll(POLL_TIMEOUT);

  return 0;
}
<commit_msg>add base code for options handling<commit_after>/*
 * Demonstration of how we might port the Python h2olog to C++.
 * Compile with: "g++ -o h2olog -I/usr/include/bcc/compat h2olog.cc -lbcc"
 */

#include <inttypes.h>
#include <bcc/BPF.h>
#include <iostream>

const std::string QUIC_BPF = R"(
struct event_t {
  uint64_t at;
};

BPF_PERF_OUTPUT(events);

int trace_quicly__accept(struct pt_regs *ctx) {
  struct event_t event = {};
  bpf_usdt_readarg(2, ctx, &event.at);
  events.perf_submit(ctx, &event, sizeof(event));
  return 0;
}
)";

#define VERSION "0.1.0"
#define POLL_TIMEOUT 100

struct event_t {
  uint64_t at;
};

static void usage(void) {
  printf("h2olog (%s)\n", VERSION);
  printf("-p PID of the H2O server\n");
  printf("-h Print this help and exit\n");
  return;
}

void handle_quic_event(void *cpu, void *data, int len) {
  struct event_t *ev = (event_t*)data;
  printf("time: %" PRIu64 "\n", ev->at);
}

int main(int argc, char **argv) {
  pid_t pid = -1;
  int c;
  while ((c = getopt(argc, argv, "hvp:t:s:dP:")) != -1) {
    switch(c) {
    case 'p':
      pid = atoi(optarg);
      break;
    case 'h':
      usage();
      exit(EXIT_SUCCESS);
    }
  }

  if (pid == -1) {
    fprintf(stderr, "Error: -p option is missing\n");
    exit(EXIT_FAILURE);
  }

  ebpf::BPF *bpf = new ebpf::BPF();
  ebpf::USDT u("", pid, "quicly", "accept", "trace_quicly__accept");
  ebpf::StatusTuple ret = bpf->init(QUIC_BPF, {}, {u});
  if (ret.code() != 0) {
    std::cerr << ret.msg() << std::endl;
    return 1;
  }

  ret = bpf->attach_usdt(u);
  if (ret.code() != 0) {
    std::cerr << ret.msg() << std::endl;
    return 1;
  }

  ret = bpf->open_perf_buffer("events", &handle_quic_event);
  if (ret.code() != 0) {
    std::cerr << ret.msg() << std::endl;
    return 1;
  }

  ebpf::BPFPerfBuffer *perf_buffer = bpf->get_perf_buffer("events");
  if (perf_buffer)
    while (true)
      perf_buffer->poll(POLL_TIMEOUT);

  return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <string>

using namespace std;

class Matrix
{
private:
	int Columns;
	int Strings;
	int **matrix;
public:
	Matrix();

	Matrix(int _Columns, int _Strings);

	Matrix(const Matrix& result);

	~Matrix();

	int Columns_();

	int Strings_();

	void search(string filename);

	bool operator == (const Matrix& m2) const;

	Matrix operator + (const Matrix& m2) const;

	Matrix operator * (const Matrix& m2) const;

	Matrix& operator = (const Matrix& result);

	friend ostream& operator << (ostream& outfile, const Matrix& result);

	friend istream& operator >> (istream& infile, const Matrix& result);
};
<commit_msg>Delete matrix.hpp<commit_after><|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2007-2009, Image Engine Design 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 Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "boost/python.hpp"

#include "IECore/NumericParameter.h"
#include "IECore/CompoundObject.h"
#include "IECore/bindings/IntrusivePtrPatch.h"
#include "IECore/bindings/ParameterBinding.h"
#include "IECore/bindings/RunTimeTypedBinding.h"

using namespace std;
using namespace boost;
using namespace boost::python;

namespace IECore
{

template<class T>
static ParameterPtr numericConstructor( const std::string &name, const std::string &description, T defaultValue, T minValue, T maxValue,
	const object &presets, bool presetsOnly, object userData )
{
	typename NumericParameter<T>::PresetsContainer p = parameterPresets<typename NumericParameter<T>::PresetsContainer>( presets );

	// get the optional userData parameter.
	ConstCompoundObjectPtr ptrUserData = 0;
	if (userData != object()) {
		extract<CompoundObjectPtr> elem(userData);
		// try if elem is an exact CompoundObjectPtr
		if (elem.check()) {
			ptrUserData = elem();
		} else {
			// now try for ConstCompoundObjectPtr
			extract<ConstCompoundObjectPtr> elem(userData);
			if (elem.check()) {
				ptrUserData = elem();
			} else {
			   	PyErr_SetString(PyExc_TypeError, "Parameter userData is not an instance of CompoundObject!");
			  	throw_error_already_set();
				ParameterPtr res;
				return res;
			}
		}
	}
	return new NumericParameter<T>( name, description, defaultValue, minValue, maxValue, p, presetsOnly, ptrUserData );
}

template<typename T>
static void bindNumericParameter( const char *name )
{
	typedef class_< NumericParameter<T>, typename NumericParameter<T>::Ptr, boost::noncopyable, bases<Parameter> > NumericParameterPyClass;
	NumericParameterPyClass( name, no_init )
		.def( "__init__", make_constructor( &numericConstructor<T>, default_call_policies(), ( boost::python::arg_( "name" ), boost::python::arg_( "description" ), boost::python::arg_( "defaultValue" ) = T(), boost::python::arg_( "minValue" ) = Imath::limits<T>::min(), boost::python::arg_( "maxValue" ) = Imath::limits<T>::max(), boost::python::arg_( "presets" ) = boost::python::tuple(), boost::python::arg_( "presetsOnly" ) = false, boost::python::arg_( "userData" ) = object() ) ) )
		.add_property( "numericDefaultValue", &NumericParameter<T>::numericDefaultValue  )
		.def( "getNumericValue", &NumericParameter<T>::getNumericValue  )
		.def( "setNumericValue", &NumericParameter<T>::setNumericValue  )
		.def( "getTypedValue", &NumericParameter<T>::getNumericValue )		// added for consistency
		.def( "setTypedValue", &NumericParameter<T>::setNumericValue )		// added for consistency
		.IE_COREPYTHON_DEFPARAMETERWRAPPERFNS( NumericParameter<T> )
		.def( "hasMinValue", &NumericParameter<T>::hasMinValue )
		.def( "hasMaxValue", &NumericParameter<T>::hasMaxValue )
		.add_property( "minValue", &NumericParameter<T>::minValue )
		.add_property( "maxValue", &NumericParameter<T>::maxValue )
		.IE_COREPYTHON_DEFRUNTIMETYPEDSTATICMETHODS( NumericParameter<T> )
	;
	INTRUSIVE_PTR_PATCH( NumericParameter<T>, typename NumericParameterPyClass );
	implicitly_convertible<typename NumericParameter<T>::Ptr, ParameterPtr>();
}

void bindNumericParameter()
{
	bindNumericParameter<int>( "IntParameter" );
	bindNumericParameter<float>( "FloatParameter" );
	bindNumericParameter<double>( "DoubleParameter" );
}

};
<commit_msg>Updated NumericParameter binding<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2007-2009, Image Engine Design 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 Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "boost/python.hpp"

#include "IECore/bindings/ParameterBinding.h"
#include "IECore/NumericParameter.h"
#include "IECore/CompoundObject.h"
#include "IECore/bindings/Wrapper.h"
#include "IECore/bindings/IntrusivePtrPatch.h"
#include "IECore/bindings/WrapperToPython.h"
#include "IECore/bindings/RunTimeTypedBinding.h"

using namespace std;
using namespace boost;
using namespace boost::python;

namespace IECore
{

template<typename T>
class NumericParameterWrap : public NumericParameter<T>, public Wrapper<NumericParameter<T> >
{
	public :

		NumericParameterWrap( PyObject *self, const std::string &n, const std::string &d, T v = T(), T minValue = Imath::limits<T>::min(),
			T maxValue = Imath::limits<T>::max(), const object &p = boost::python::tuple(), bool po = false, CompoundObjectPtr ud = 0 )
			:	NumericParameter<T>( n, d, v, minValue, maxValue, parameterPresets<typename NumericParameter<T>::PresetsContainer>( p ), po, ud ), Wrapper<NumericParameter<T> >( self, this ) {};

		IE_COREPYTHON_PARAMETERWRAPPERFNS( NumericParameter<T> );
		IE_CORE_DECLAREMEMBERPTR( NumericParameterWrap<T> );
};

template<typename T>
static void bindNumericParameter( const char *name )
{
	using boost::python::arg;

	typedef class_< NumericParameter<T>, typename NumericParameterWrap<T>::Ptr, boost::noncopyable, bases<Parameter> > NumericParameterPyClass;
	NumericParameterPyClass( name, no_init )
		.def(
			init<const std::string &, const std::string &, boost::python::optional< T, T, T, const object &, bool, CompoundObjectPtr> >
			(
				(
					arg( "name" ),
					arg( "description" ),
					arg( "defaultValue" ) = T(),
					arg( "minValue" ) = Imath::limits<T>::min(),
					arg( "maxValue" ) = Imath::limits<T>::max(),
					arg( "presets" ) = boost::python::tuple(),
					arg( "presetsOnly" ) = false,
					arg( "userData" ) = CompoundObject::Ptr( 0 )
				)
			)
		)
		.add_property( "numericDefaultValue", &NumericParameter<T>::numericDefaultValue  )
		.def( "getNumericValue", &NumericParameter<T>::getNumericValue  )
		.def( "setNumericValue", &NumericParameter<T>::setNumericValue  )
		.def( "getTypedValue", &NumericParameter<T>::getNumericValue )		// added for consistency
		.def( "setTypedValue", &NumericParameter<T>::setNumericValue )		// added for consistency
		.IE_COREPYTHON_DEFPARAMETERWRAPPERFNS( NumericParameter<T> )
		.def( "hasMinValue", &NumericParameter<T>::hasMinValue )
		.def( "hasMaxValue", &NumericParameter<T>::hasMaxValue )
		.add_property( "minValue", &NumericParameter<T>::minValue )
		.add_property( "maxValue", &NumericParameter<T>::maxValue )
		.IE_COREPYTHON_DEFRUNTIMETYPEDSTATICMETHODS( NumericParameter<T> )
	;
	INTRUSIVE_PTR_PATCH( NumericParameter<T>, typename NumericParameterPyClass );
	implicitly_convertible<typename NumericParameter<T>::Ptr, ParameterPtr>();
	implicitly_convertible<typename NumericParameter<T>::Ptr, typename NumericParameter<T>::ConstPtr>();
}

void bindNumericParameter()
{
	bindNumericParameter<int>( "IntParameter" );
	bindNumericParameter<float>( "FloatParameter" );
	bindNumericParameter<double>( "DoubleParameter" );
}

};
<|endoftext|>


<commit_before>// hello.cpp: Nelson Urbina
// Description: A program that prints "Hello World!"
// Now, let's play a little with it

#include <iostream>
#include <string>

int main(){
  std::cout << "Hello World!" << '\n';
  /**
   * This idea came out from a post I read in the Q&A section of Sololearn:
   *  Let's make a piramid!
   **/
  std::string s = "Hello World!";
  for (int i = s.length(); i >= 0;--i){
    std::cout << s.substr(0,s.length()-i) << '\n';
  }
  // And the other way around
  for (int i = 0; i < s.length();++i){
    std::cout << s.substr(0,s.length()-i) << '\n';
  }
  return 0;
}
<commit_msg>'Testing some io functions'<commit_after>// hello.cpp: Nelson Urbina
// Description: A program that prints "Hello World!"
// Now, let's play a little with it

#include <iostream>
#include <string>

int main(){
  std::cout << "Hello World!" << '\n';
  /**
   * This idea came out from a post I read in the Q&A section of Sololearn:
   *  Let's make a piramid!
   **/
  std::string s = "Hello World!";
  for (int i = s.length();i >= 0;--i){
    std::cout << s.substr(0,s.length()-i) << '\n';
  }
  // And the other way around
  for (int i = 0;i < s.length();++i){
    std::cout << s.substr(0,s.length()-i) << '\n';
  }

  std::cout.width(20);
  std::cout.fill('=');
  std::cout << '\n';

  std::cout.width(17);
  for (int i = 0;i < 6;++i){
    for (int j = 0;j < 4; ++j){
      std::cout << s;
    }
    std::cout << '\n';
  }

  return 0;
}
<|endoftext|>


<commit_before>//
//  learn.cpp
//
//
//  Created by 夏嘉会 on 16/3/2.
//
//

#include "learn.hpp"
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <iomanip>
using namespace std;
// enum gameResult{win,lose,tie,cancel};
// struct myTimeStruct
// {
// 	/* data */
// 	unsigned int year;
// 	unsigned int month;
// 	unsigned int day;

// 	unsigned int hour;
// 	unsigned int min;
// 	unsigned int sec;
// };

// double power(int x, int n){
// 	double val = 1. ;
// 	while(n--){
// 		val *= x;
// 	}
// 	return val;
// }

// double arctan(double x){
// 	double sqr = x*x;
// 	double r = 0;
// 	double e = x;
// 	int i = 1;
// 	while(e/i>1e-15){
// 		double f = e/i;
// 		r = (i%4==1)?r+f:r-f;
// 		e = e*sqr;
// 		i += 2;
// 	}
// 	return r;
// }

// bool symm(unsigned n){
// 	unsigned temp = n;
// 	unsigned m = 0;
// 	while(temp!=0){
// 		m = m*10 + temp%10;
// 		temp /= 10;
// 	}
// 	return (m == n);
// }

// double tsin(double x){
// 	double r = 0;
// 	double t = x;
// 	int n = 1;
// 	do{
// 		r += t;
// 		n++;
// 		t = -t*x*x/(2*n-1)/(2*n-2);
// 	}
// 	while(fabs(t)>1e-10);
// 	return r;
// }

// int rollDice(){
// 	int die1 = 1 + rand()%6;
// 	int die2 = 1 + rand()%6;
// 	int sum = die1 + die2;
// 	cout<<"player rolled "<<die1<<" + "<<die2<<" = "<<sum<<endl;
// 	return sum;
// }

// enum GameStatus { WIN,LOSE,PLAYING };

// int comm(int n, int k){
// 	if(k>n){
// 		return 0;
// 	}
// 	else if(n == k||k == 0){
// 		return 1;
// 	}
// 	else
// 		return comm(n-1,k) + comm(n-1,k-1);
// }

// void move(char src,char dest){
// 	cout<<src<<"==>"<<dest<<endl;
// }

// void hanoi(int n,char src,char medium,char dest){
// 	if(n == 1){
// 		move(src,dest);
// 	}
// 	else{
// 		hanoi(n-1,src,dest,medium);
// 		move(src,dest);
// 		hanoi(n-1,medium,src,dest);
// 	}
// }
// void swap(int &a,int &b){
// 	int t;
// 	t = a;
// 	a = b;
// 	b = t;
// }

// const double PI = 3.14159265358979;
// inline double calArea(double radius){
// 	return PI*radius*radius;
// }

// int getVolume(int length,int width=2, int height=3){
// 	cout << setw(5) << length << setw(5) << width << setw(5)<< height << '\t';
// return length * width * height;
// }

class Clock{
public:
	Clock(int newH, int newM, int newS);
	void setTime(int newH, int newM,int newS);
	void showTime();
private:
	int hour, minute, second;
};
void Clock::setTime(int newH, int newM, int newS) {
   hour = newH;
   minute = newM;
   second = newS;
}
void Clock::showTime() {
   cout << hour << ":" << minute << ":" << second<<endl;
}
Clock::Clock(int newH, int newM, int newS):hour(newH), minute(newM), second(newS){

}

int main()
{
	Clock c(0,0,0);
	c.showTime();

	// int angle;
	// cout<<"Enter an angle: ";
	// cin>>angle;
	// double radian = angle*PI/180.0;
	// cout<<"sin("<<angle<<")= "<<sin(radian)<<endl;
	// cout<<"cos("<<angle<<")= "<<cos(radian)<<endl;
	// cout<<"tan("<<angle<<")= "<<tan(radian)<<endl;

	// const int X = 10, Y = 12, Z = 15;
	// cout << "Some box data is " ;
	// cout << getVolume(X, Y, Z) << endl;
	// cout << "Some box data is " ;
	// cout << getVolume(X, Y) << endl;
	// cout << "Some box data is " ;
	// cout << getVolume(X) << endl;

	// double r = 3.0;
	// double area = calArea(r);
	// cout<<area<<endl;

	// int x = 5;
	// int y = 10;
	// cout<<"x and y before swap: x = "<<x<<" y = "<<y<<endl;
	// swap(x,y);
	// cout<<"x and y after swap: x = "<<x<<" y = "<<y<<endl;

	// int m;
	// cout<<"Enter the number of discs: ";
	// cin>>m;
	// cout<<"the step of moving "<<m<<"discs: "<<endl;
	// hanoi(m,'A','B','C');

	// int n,k;
	// cout<<"Enter n and k: ";
	// cin>>n>>k;
	// cout<<"C(n,k): "<<comm(n,k)<<endl;

	//以下为正序排列，以上为倒序排列
    /*
    const double pi=3.14159;
    int radius=0;
    int a=0;
    int b=0;
    int x = 0;
    cout<<"The initial radius is: "<<radius<<'\n';
    cout<<"pi is: "<<pi<<'\n';
    cout<<"Please enter a different radius!\n";
    cin>>radius;
    cout<<"Now the radius changes to: "<<radius<<'\n';
    cout<<"pi is still "<<pi<<'\n'; //pi is not changed.
    cout<<"Enter a: \n";
    cin>>a;
    cout<<"Enter b: \n";
    cin>>b;
    x = a>b?a:b;
    cout<<"The bigger one is "<<x<<'\n';
    */

    /*
    double x=9;
    float y=2e15;
    cout<<sizeof(short)<<endl;
    cout<<sizeof x<<endl;
    cout<<static_cast<long>(y)<<endl;
	*/
	/*
	int x,y;
    cout<<"enter two numbers: "<<endl;
    cin>>x>>y;
	if(x==y) cout<<"x = y = "<<x<<endl;
	else{
		if(x<y) cout<<"x < y = "<<y<<endl;
		else cout<<"y < x = "<<x<<endl;
		}
	*/

	/*
	int day;
	cout<<"Enter a number: "<<endl;
	cin>>day;
	switch(day){
		case 0: cout<<"Sunday"<<endl;
		break;
		case 1: cout<<"Monday"<<endl;
		break;
		case 2: cout<<"Tuesday"<<endl;
		break;
		case 3: cout<<"Wensday"<<endl;
		break;
		case 4: cout<<"Thursday"<<endl;
		break;
		case 5: cout<<"Friday"<<endl;
		break;
		case 6: cout<<"Saturday"<<endl;
		break;
		default: cout<<"numbers out of range..."<<endl;

	}
	*/
	/*
	int i=1, sum=0, upperpoint;
	cout<<"Enter a number: "<<endl;
	cin>>upperpoint;
	while(i<=upperpoint){
		sum += i;
		i++;
	}
	cout<<"sum = "<<sum<<endl;
	*/
	/*
	int num=0,result=0;
	cout<<"Enter a number: "<<endl;
	cin>>num;
	do{
		result *= 10;
		result += num % 10;
		num /= 10;
	}
	while(num != 0);

	cout<<"the reverse number is "<<result<<endl;
	*/

	/*
	int n;
	cout<<"Enter a number: "<<endl;
	cin>>n;
	for(int i=1;i<=n;i++){
		if(n % i == 0)
			cout<<i<<" ";
	}
	cout<<endl;
	*/

	/*
	int i=0,j=0,n;
	cout<<"Enter a number,enter 0 to stop: "<<endl;
	cin>>n;
	while(n != 0){
		if(n>0) i++;
		else j++;
		cin>>n;
	}
	cout<<"You entered "<<i<<" positive numbers"<<" and "<<j<<" negative numbers"<<endl;
	*/

	/*
	myTimeStruct myTime = {2016,3,2,12,30,0};
	cout<<"Current time is: "<<myTime.year<<"-"<<myTime.month<<"-"<<myTime.day<<" "<<myTime.hour<<":"<<myTime.min<<":"<<myTime.sec<<endl;

	cout<<"Enter year: "<<endl;
	cin>>myTime.year;

	cout<<"Enter month: "<<endl;
	cin>>myTime.month;

	cout<<"Enter day: "<<endl;
	cin>>myTime.day;

	cout<<"Enter hour: "<<endl;
	cin>>myTime.hour;

	cout<<"Enter min: "<<endl;
	cin>>myTime.min;

	cout<<"Enter sec: "<<endl;
	cin>>myTime.sec;

	cout<<"Now the time is set to: "<<myTime.year<<"-"<<myTime.month<<"-"<<myTime.day<<" "<<myTime.hour<<":"<<myTime.min<<":"<<myTime.sec<<endl;
	*/

	// int x,n;
	// double result;
	// cout<<"Enter two numbers, latter for base and former for power: "<<endl;
	// cin>>x>>n;
	// result = power(x,n);
	// cout<<"The result is: "<<result<<endl;

	// int input;
	// int value;

	// cout<<"Enter a 8 bit binary num: "<<endl;
	// cin>>input;
	// for(int i=0;input!=0;i++){
	// 	int temp = input % 10;
	// 	if(temp!=0){
	// 		value += power(2,i);
	// 	}
	// 	input /= 10;

	// }
	// cout<<"the decimal num is: "<<value<<endl;

	// double a = 16.0 * arctan(1/5.0);
	// double b = 4.0 * arctan(1/239.0);
	// cout<<"PI = "<<a-b<<endl;

	// for(int i = 1;i < 1000;i++){
	// 	if(symm(i)&&symm(i*i)&&symm(i*i*i)){
	// 		cout<<"i = "<<i<<"; ";
	// 		cout<<"i*i = "<<i*i<<"; ";
	// 		cout<<"i*i*i = "<<i*i*i<<endl;
	// 	}
	// }

	// double k,r,s;
	// cout<<"k = ";
	// cin>>k;
	// cout<<"r = ";
	// cin>>r;
	// cout<<"s = ";
	// cin>>s;
	// if(r*r <= s*s){
	// 	k = sqrt(tsin(r)*tsin(r)+tsin(s)*tsin(s));
	// }
	// else{
	// 	k = tsin(r*s)/2;
	// }
	// cout<<k<<endl;

	// int sum,myPoint;
	// GameStatus status;
	// unsigned seed;
	// cout<<"Enter a num: ";
	// cin>>seed;
	// srand(seed);
	// sum = rollDice();
	// switch(sum){
	// 	case 7:
	// 	case 11:
	// 		status = WIN;
	// 		break;
	// 	case 2:
	// 	case 3:
	// 	case 12:
	// 		status = LOSE;
	// 		break;
	// 	default:
	// 		status = PLAYING;
	// 		myPoint = sum;
	// 		cout<<"point is "<<myPoint<<endl;
	// 		break;
	// }
	// while(status == PLAYING){
	// 	sum = rollDice();
	// 	if(sum == myPoint){
	// 		status = WIN;
	// 	}
	// 	else if(sum == 7){
	// 		status = LOSE;
	// 	}
	// }
	// if(status == WIN){
	// 	cout<<"player wins!"<<endl;
	// }
	// else
	// 	cout<<"player loses!"<<endl;

    return 0;

}<commit_msg>new practice.<commit_after>//
//  learn.cpp
//
//
//  Created by 夏嘉会 on 16/3/2.
//
//

#include "learn.hpp"
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <iomanip>
using namespace std;
// enum gameResult{win,lose,tie,cancel};
// struct myTimeStruct
// {
// 	/* data */
// 	unsigned int year;
// 	unsigned int month;
// 	unsigned int day;

// 	unsigned int hour;
// 	unsigned int min;
// 	unsigned int sec;
// };

// double power(int x, int n){
// 	double val = 1. ;
// 	while(n--){
// 		val *= x;
// 	}
// 	return val;
// }

// double arctan(double x){
// 	double sqr = x*x;
// 	double r = 0;
// 	double e = x;
// 	int i = 1;
// 	while(e/i>1e-15){
// 		double f = e/i;
// 		r = (i%4==1)?r+f:r-f;
// 		e = e*sqr;
// 		i += 2;
// 	}
// 	return r;
// }

// bool symm(unsigned n){
// 	unsigned temp = n;
// 	unsigned m = 0;
// 	while(temp!=0){
// 		m = m*10 + temp%10;
// 		temp /= 10;
// 	}
// 	return (m == n);
// }

// double tsin(double x){
// 	double r = 0;
// 	double t = x;
// 	int n = 1;
// 	do{
// 		r += t;
// 		n++;
// 		t = -t*x*x/(2*n-1)/(2*n-2);
// 	}
// 	while(fabs(t)>1e-10);
// 	return r;
// }

// int rollDice(){
// 	int die1 = 1 + rand()%6;
// 	int die2 = 1 + rand()%6;
// 	int sum = die1 + die2;
// 	cout<<"player rolled "<<die1<<" + "<<die2<<" = "<<sum<<endl;
// 	return sum;
// }

// enum GameStatus { WIN,LOSE,PLAYING };

// int comm(int n, int k){
// 	if(k>n){
// 		return 0;
// 	}
// 	else if(n == k||k == 0){
// 		return 1;
// 	}
// 	else
// 		return comm(n-1,k) + comm(n-1,k-1);
// }

// void move(char src,char dest){
// 	cout<<src<<"==>"<<dest<<endl;
// }

// void hanoi(int n,char src,char medium,char dest){
// 	if(n == 1){
// 		move(src,dest);
// 	}
// 	else{
// 		hanoi(n-1,src,dest,medium);
// 		move(src,dest);
// 		hanoi(n-1,medium,src,dest);
// 	}
// }
// void swap(int &a,int &b){
// 	int t;
// 	t = a;
// 	a = b;
// 	b = t;
// }

// const double PI = 3.14159265358979;
// inline double calArea(double radius){
// 	return PI*radius*radius;
// }

// int getVolume(int length,int width=2, int height=3){
// 	cout << setw(5) << length << setw(5) << width << setw(5)<< height << '\t';
// return length * width * height;
// }

// class Clock{
// public:
// 	Clock(int newH, int newM, int newS);
// 	Clock();
// 	void setTime(int newH, int newM,int newS);
// 	void showTime();
// private:
// 	int hour, minute, second;
// };
// void Clock::setTime(int newH, int newM, int newS) {
//    hour = newH;
//    minute = newM;
//    second = newS;
// }
// void Clock::showTime() {
//    cout << hour << ":" << minute << ":" << second<<endl;
// }
// Clock::Clock(int newH, int newM, int newS):hour(newH), minute(newM), second(newS){

// }
// Clock::Clock():hour(0),minute(0),second(0){

// }
class Point{
public:
	Point(int xx=0, int yy=0){
		x = xx;
		y = yy;
	}
	Point(Point &p);
	int getX(){return x;}
	int getY(){return y;}
private:
	int x,y;
};
Point::Point(Point &p){
	x = p.x;
	y = p.y;
	cout<<"Calling the constructor of Point"<<endl;
}

class Line{
public:
	Line(Point xp1, Point xp2);
	Line(Line &l);
	double getLen(){return len;}
private:
	Point p1,p2;
	double len;
};

Line::Line(Point xp1, Point xp2):p1(xp1),p2(xp2){
	cout<<"Calling constructor of Line"<<endl;
	double x = static_cast<double>(p1.getX()-p2.getX());
	double y = static_cast<double>(p1.getY()-p2.getY());
	len = sqrt(x*x + y*y);
}

Line::Line(Line &l):p1(l.p1),p2(l.p2){
	cout<<"Calling the copy constructor of Line"<<endl;
	len = l.len;
}

int main()
{
	Point myp1(1,1), myp2(4,5);
	Line line(myp1, myp2);
	Line line2(line);
	cout << "The length of the line is: ";
	cout << line.getLen() << endl;
	cout << "The length of the line2 is: ";
	cout << line2.getLen() << endl;
	// Clock c1(8,10,0);
	// Clock c2;
	// c1.showTime();
	// c2.showTime();

	// int angle;
	// cout<<"Enter an angle: ";
	// cin>>angle;
	// double radian = angle*PI/180.0;
	// cout<<"sin("<<angle<<")= "<<sin(radian)<<endl;
	// cout<<"cos("<<angle<<")= "<<cos(radian)<<endl;
	// cout<<"tan("<<angle<<")= "<<tan(radian)<<endl;

	// const int X = 10, Y = 12, Z = 15;
	// cout << "Some box data is " ;
	// cout << getVolume(X, Y, Z) << endl;
	// cout << "Some box data is " ;
	// cout << getVolume(X, Y) << endl;
	// cout << "Some box data is " ;
	// cout << getVolume(X) << endl;

	// double r = 3.0;
	// double area = calArea(r);
	// cout<<area<<endl;

	// int x = 5;
	// int y = 10;
	// cout<<"x and y before swap: x = "<<x<<" y = "<<y<<endl;
	// swap(x,y);
	// cout<<"x and y after swap: x = "<<x<<" y = "<<y<<endl;

	// int m;
	// cout<<"Enter the number of discs: ";
	// cin>>m;
	// cout<<"the step of moving "<<m<<"discs: "<<endl;
	// hanoi(m,'A','B','C');

	// int n,k;
	// cout<<"Enter n and k: ";
	// cin>>n>>k;
	// cout<<"C(n,k): "<<comm(n,k)<<endl;

	//以下为正序排列，以上为倒序排列
    /*
    const double pi=3.14159;
    int radius=0;
    int a=0;
    int b=0;
    int x = 0;
    cout<<"The initial radius is: "<<radius<<'\n';
    cout<<"pi is: "<<pi<<'\n';
    cout<<"Please enter a different radius!\n";
    cin>>radius;
    cout<<"Now the radius changes to: "<<radius<<'\n';
    cout<<"pi is still "<<pi<<'\n'; //pi is not changed.
    cout<<"Enter a: \n";
    cin>>a;
    cout<<"Enter b: \n";
    cin>>b;
    x = a>b?a:b;
    cout<<"The bigger one is "<<x<<'\n';
    */

    /*
    double x=9;
    float y=2e15;
    cout<<sizeof(short)<<endl;
    cout<<sizeof x<<endl;
    cout<<static_cast<long>(y)<<endl;
	*/
	/*
	int x,y;
    cout<<"enter two numbers: "<<endl;
    cin>>x>>y;
	if(x==y) cout<<"x = y = "<<x<<endl;
	else{
		if(x<y) cout<<"x < y = "<<y<<endl;
		else cout<<"y < x = "<<x<<endl;
		}
	*/

	/*
	int day;
	cout<<"Enter a number: "<<endl;
	cin>>day;
	switch(day){
		case 0: cout<<"Sunday"<<endl;
		break;
		case 1: cout<<"Monday"<<endl;
		break;
		case 2: cout<<"Tuesday"<<endl;
		break;
		case 3: cout<<"Wensday"<<endl;
		break;
		case 4: cout<<"Thursday"<<endl;
		break;
		case 5: cout<<"Friday"<<endl;
		break;
		case 6: cout<<"Saturday"<<endl;
		break;
		default: cout<<"numbers out of range..."<<endl;

	}
	*/
	/*
	int i=1, sum=0, upperpoint;
	cout<<"Enter a number: "<<endl;
	cin>>upperpoint;
	while(i<=upperpoint){
		sum += i;
		i++;
	}
	cout<<"sum = "<<sum<<endl;
	*/
	/*
	int num=0,result=0;
	cout<<"Enter a number: "<<endl;
	cin>>num;
	do{
		result *= 10;
		result += num % 10;
		num /= 10;
	}
	while(num != 0);

	cout<<"the reverse number is "<<result<<endl;
	*/

	/*
	int n;
	cout<<"Enter a number: "<<endl;
	cin>>n;
	for(int i=1;i<=n;i++){
		if(n % i == 0)
			cout<<i<<" ";
	}
	cout<<endl;
	*/

	/*
	int i=0,j=0,n;
	cout<<"Enter a number,enter 0 to stop: "<<endl;
	cin>>n;
	while(n != 0){
		if(n>0) i++;
		else j++;
		cin>>n;
	}
	cout<<"You entered "<<i<<" positive numbers"<<" and "<<j<<" negative numbers"<<endl;
	*/

	/*
	myTimeStruct myTime = {2016,3,2,12,30,0};
	cout<<"Current time is: "<<myTime.year<<"-"<<myTime.month<<"-"<<myTime.day<<" "<<myTime.hour<<":"<<myTime.min<<":"<<myTime.sec<<endl;

	cout<<"Enter year: "<<endl;
	cin>>myTime.year;

	cout<<"Enter month: "<<endl;
	cin>>myTime.month;

	cout<<"Enter day: "<<endl;
	cin>>myTime.day;

	cout<<"Enter hour: "<<endl;
	cin>>myTime.hour;

	cout<<"Enter min: "<<endl;
	cin>>myTime.min;

	cout<<"Enter sec: "<<endl;
	cin>>myTime.sec;

	cout<<"Now the time is set to: "<<myTime.year<<"-"<<myTime.month<<"-"<<myTime.day<<" "<<myTime.hour<<":"<<myTime.min<<":"<<myTime.sec<<endl;
	*/

	// int x,n;
	// double result;
	// cout<<"Enter two numbers, latter for base and former for power: "<<endl;
	// cin>>x>>n;
	// result = power(x,n);
	// cout<<"The result is: "<<result<<endl;

	// int input;
	// int value;

	// cout<<"Enter a 8 bit binary num: "<<endl;
	// cin>>input;
	// for(int i=0;input!=0;i++){
	// 	int temp = input % 10;
	// 	if(temp!=0){
	// 		value += power(2,i);
	// 	}
	// 	input /= 10;

	// }
	// cout<<"the decimal num is: "<<value<<endl;

	// double a = 16.0 * arctan(1/5.0);
	// double b = 4.0 * arctan(1/239.0);
	// cout<<"PI = "<<a-b<<endl;

	// for(int i = 1;i < 1000;i++){
	// 	if(symm(i)&&symm(i*i)&&symm(i*i*i)){
	// 		cout<<"i = "<<i<<"; ";
	// 		cout<<"i*i = "<<i*i<<"; ";
	// 		cout<<"i*i*i = "<<i*i*i<<endl;
	// 	}
	// }

	// double k,r,s;
	// cout<<"k = ";
	// cin>>k;
	// cout<<"r = ";
	// cin>>r;
	// cout<<"s = ";
	// cin>>s;
	// if(r*r <= s*s){
	// 	k = sqrt(tsin(r)*tsin(r)+tsin(s)*tsin(s));
	// }
	// else{
	// 	k = tsin(r*s)/2;
	// }
	// cout<<k<<endl;

	// int sum,myPoint;
	// GameStatus status;
	// unsigned seed;
	// cout<<"Enter a num: ";
	// cin>>seed;
	// srand(seed);
	// sum = rollDice();
	// switch(sum){
	// 	case 7:
	// 	case 11:
	// 		status = WIN;
	// 		break;
	// 	case 2:
	// 	case 3:
	// 	case 12:
	// 		status = LOSE;
	// 		break;
	// 	default:
	// 		status = PLAYING;
	// 		myPoint = sum;
	// 		cout<<"point is "<<myPoint<<endl;
	// 		break;
	// }
	// while(status == PLAYING){
	// 	sum = rollDice();
	// 	if(sum == myPoint){
	// 		status = WIN;
	// 	}
	// 	else if(sum == 7){
	// 		status = LOSE;
	// 	}
	// }
	// if(status == WIN){
	// 	cout<<"player wins!"<<endl;
	// }
	// else
	// 	cout<<"player loses!"<<endl;

    return 0;

}<|endoftext|>


<commit_before>#include "level.h"
#include "log.h"
#include "activemodel.h"
#include "ball.h"
#include "asteroid.h"
#include "kamikaze.h"
#include "turret.h"
#include "boundingsphere.h"
#include "boundingshape.h"
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <sstream>

Level::Level() {
    amodels = new ModelList();
    pmodels = new ModelList();
    geometries = new GeometryList();
    bombs = new BombList();
    walls = new WallList();
    forces = new ForceList();
    ship = new Ship();
    ptree = kd_create(3);
    atree = kd_create(3);
    myScore = 0;
    maxRadius = 0;
    maxARadius = 0;
    worldDepth = -10.0;
    frame = 0;
    enemieson = true;
}

Level::~Level() {
    size_t i;
    for (i = 0; i < amodels->size(); i++) delete amodels->at(i);
    delete amodels;
    for (i = 0; i < pmodels->size(); i++) delete pmodels->at(i);
    delete pmodels;
    delete geometries;
    delete bombs;
    delete walls;
}

void Level::update() {
    frame++;
    if (frame > 90) {
        frame = 0;
    }

    if (enemieson){
        debug("hey");
        generateEnemies();
    }

    updateActiveModels();
    checkActiveCollisions();
    checkShipCollisions();
    checkWallCollisions();

}

void Level::updateActiveModels() {
    ActiveModel *am;
    for (size_t i = 0; i < amodels->size(); i++) {
        am = (ActiveModel *) amodels->at(i);
        if (!behindShip(am)) {
            for (size_t j = 0; j < forces->size(); j++) {
                am->applyForce(forces->at(j));
            }
            am->update();
        }
    }
    updateATree();
}

void Level::checkActiveCollisions() {
    ActiveModel *am;
    Model *model;
    BoundingSphere *bs;
    BoundingShape *bsh;
    struct kdres *presults;
    Eigen::Vector3f pos;

    for (size_t i = 0; i < amodels->size(); i++) {
        am = (ActiveModel*) amodels->at(i);
        pos = am->position;

        // check against passive objects
        presults = kd_nearest_range3f(ptree, pos.x(), pos.y(), pos.z(), maxRadius + am->bs->radius);
        if (kd_res_size(presults) > 0) {
            /* For each bounding sphere */
            while (!kd_res_end(presults)) {
                bsh =  (BoundingShape *) kd_res_item_data(presults);
                // checks intersection
                if (bsh->intersect((BoundingSphere *) am->bs)) {
                    model = bsh->model;
                    if (!model->dead && !am->dead) {
                        //debug("Passive Hit");

                        if(!am->isAsteroid){
                            model->hit(am);
                            am->hit(model);
                        }

                        if (model->dead && am->shipPart) {
                            myScore += model->getScore(); // sets the score to 0 after reading it
                        }
                    }
                }
                kd_res_next(presults);
            }
        }

        // check against active objects
        presults = kd_nearest_range3f(atree, pos.x(), pos.y(), pos.z(), am->radius + maxARadius);
        while (!kd_res_end(presults)) {
            bs = (BoundingSphere *) kd_res_item_data(presults);
            // check intersection
            if (am->bs->intersect(bs)) {
                model = bs->model;
                if (model != am && !model->dead && !am->dead) {
                    debug("Active Hit");
                    //debug("%f", am->radius + maxARadius);
                    model->hit(am);
                    am->hit(model);
                    //SCORE WON"T WORK
                    if (model->dead) {
                        myScore += model->getScore(); // sets the score to 0 after reading it
                    }
                }

            }
            kd_res_next(presults);
        }

        kd_res_free(presults);
    }
}

void Level::checkShipCollisions() {
    Model *model;
    BoundingSphere *bs;
    Eigen::Vector3f pos = ship->position;
    struct kdres *presults = kd_nearest_range3f(ptree, pos.x(), pos.y(), pos.z(), ship->radius + maxRadius);

    if (kd_res_size(presults) > 0) {
        // for each bounding sphere
        while (!kd_res_end(presults)) {
            bs = (BoundingSphere *) kd_res_item_data(presults);
            // check intersection
            if (ship->bs->intersect(bs)) {
                model = bs->model;
                if (!model->dead) {
                    model->hit(ship);
                    ship->hit(model);
                }
            }
            kd_res_next(presults);
        }
    }

    presults = kd_nearest_range3f(atree, pos.x(), pos.y(), pos.z(), ship->radius + maxARadius);
    if (kd_res_size(presults) > 0) {
        /* For each bounding sphere */
        while( !kd_res_end( presults ) ) {
            bs = (BoundingSphere*) kd_res_item_data(presults);
            //Checks intersection
            if(ship->bs->intersect(bs)){
                model = bs->model;
                if(!model->dead){
                    model->hit(ship);
                    ship->hit(model);
                }
            }
            kd_res_next( presults );
        }
    }

    kd_res_free(presults);
}

void Level::checkWallCollisions() {
    ActiveModel *am;
    Wall *w;
    for (size_t i = 0; i < walls->size(); i++) {
        w = walls->at(i);
        for (size_t j = 0; j < amodels->size(); j++) {
            am = (ActiveModel *) amodels->at(j);
            if (w->collide(am->position, ship->position)) {
                am->die();
                debug("Wall Hit");
            }
        }
    }
}

void Level::clean() {
    Model *model;
    for (size_t i = 0; i < amodels->size(); i++) {
        model = amodels->at(i);
        if(model->dead){
            amodels->erase(amodels->begin()+i);
            delete model;
            i--;
            debug("Deleted an acitve model");
        }
    }
    for (size_t i = 0; i < bombs->size(); i++) {
        model = (Model*) bombs->at(i);
        if(model->dead){
            bombs->erase(bombs->begin()+i);
            i--;
            debug("Removed a bomb");
        }
    }
}

void Level::calculateMaxRadius() {
    Model *model;
    for (size_t i = 0; i < pmodels->size(); i++) {
        model = pmodels->at(i);
        maxRadius = max(model->bs->radius, maxRadius);
    }
    for (size_t i = 0; i < amodels->size(); i++) {
        model = amodels->at(i);
        maxRadius = max(model->bs->radius, maxRadius);
    }
    debug("%f", maxRadius);
}

void Level::createTree() {
    LOG("[Level] \tMaking tree ",1);
    Model *model;
    for (size_t i = 0; i < pmodels->size(); i++) {
        model = pmodels->at(i);
        model->addSelf(ptree);
        LOG("[Level] \tInserting model " << i,1);
    }
    LOG("[Level] \tDone with tree ",1);
}

void Level::updateATree() {
    kd_clear(atree);
    atree = kd_create(3);
    Model *model;
    for (size_t i = 0; i < amodels->size(); i++) {
        model = amodels->at(i);
        maxARadius = max(model->bs->radius, maxARadius);
        model->addSelf(atree);
    }
    //debug("%f", maxARadius);
}

void Level::dump() {
    LOG("[Level] \t Dump" ,1);
    LOG("Max Radius" << maxRadius,1);
    LOG("Max A Radius" << maxARadius,1);
    LOG("Passive Models:" ,1);
    for (size_t i = 0; i < pmodels->size(); i++) {
        pmodels->at(i)->dump();
    }
    LOG("Active Models:" ,1);
    for (size_t i = 0; i < amodels->size(); i++) {
        amodels->at(i)->dump();
    }
    LOG("Geometries:" ,1);
    for (size_t i = 0; i < geometries->size(); i++) {
        geometries->at(i)->dump();
    }
    LOG("Walls:" ,1);
    for (size_t i = 0; i < walls->size(); i++) {
        walls->at(i)->dump();
    }
}

void Level::draw(float farClippingPlane) {
    drawActive(farClippingPlane);
    drawPassive(farClippingPlane);
    clean();
}

void Level::drawActive(float farClippingPlane) {
    Model *model;
    for (size_t i = 0; i < amodels->size(); i++) {
        model = amodels->at(i);
        if (model->position.z() < farClippingPlane && !behindShip(model)) {
            model->draw();
        }
    }
}

void Level::drawPassive(float farClippingPlane) {
    Model *model;
    for (size_t i = 0; i < pmodels->size(); i++) {
        model = pmodels->at(i);
        if (model->position.z() < farClippingPlane && !behindShip(model)) {
            model->draw();
        }
    }
}

bool Level::behindShip(Model *model) {
    return model->position.z() > ship->position.z() + 5.0;
}

void Level::generateEnemies() {
	// randomly generate enemies to attack the ship
	int random_integer = rand() % 20 + 1;

	//debug("random number %d", random_integer);
            //      if (random_integer == 3) { // 1 in 20 chance we make a kamikaze
            //            Eigen::Vector3f entryPos = ship->position;
            //            entryPos[2] -= 5;
            //            entryPos[0] = -0.2 + (rand() %50) / 100.0;
            //            Kamikaze * suicide = new Kamikaze();
            //            suicide->position = entryPos;
            //
            //            enemies->push_back((Enemy *)suicide);
            //
            //          //BS INIT
            // suicide->bs->transform(&suicide->transM, suicide->scale[0]);
            //            amodels->push_back(suicide);
            //     }
    //
	if (random_integer == 20) { // 1 in 10 chance we make an asteroid
		Eigen::Vector3f entryPos = ship->position;
		entryPos[2] -= 5;
		entryPos[1] = -0.5 + (rand() %100) /100.0;
		entryPos[0] = -0.5 + (rand() %100) / 100.0;
		Eigen::Vector3f vel = (ship->position - entryPos);
		vel.normalize();
		vel /= 30;
		unsigned int astNum = rand() % 18 + 1;
		Asteroid * rock = new Asteroid(astNum);
		rock->position = entryPos;
		rock->velocity = -vel;
        rock->scale = Eigen::Vector3f(0.3,0.3,0.3);
        rock->calculateTransform();

		//BS INIT
        rock->bs->transform(&rock->transM, rock->scale[0]);
		amodels->push_back(rock);
	}

	//if (done != 0) {
	//	debug ("creating new turret");
	//	Turret * newTurret = new Turret();

	//	newTurret->position = ship->position;
	//	newTurret->position.z() -= 0.1;
	//
	//	enemies->push_back((Enemy *) newTurret);
	//	pmodels->push_back(newTurret);
	//	done = 0;
	//}
}

void Level::drawHealthBar() {
	unsigned int myHealth = ship->health;
	if (myHealth < 0 || myHealth > 100) {
        myHealth = 0;
	}
	renderHealthbar((float)myHealth);

	// draw the current health number
	char health_str[4];
	itoa(myHealth, health_str);
	void *font = GLUT_BITMAP_9_BY_15;
	int health_pos_x = 112;
	int health_pos_y = 20;
	Color health_color = Color(1.0,1.0,1.0);
	if (myHealth > 60) {
		health_color = Color(0.0,1.0,0.0);
	} else if (myHealth > 30) {
		health_color = Color(1.0,1.0,0.0);
	} else {
		health_color = Color(1.0,0.0,0.0);
	}
	renderText(health_pos_x, health_pos_y, font, health_str, health_color);
}

void Level::drawScore() {
	char score_str[MAX_SCORE_DIGITS+1];
	itoa(myScore, score_str);

	renderScore(score_str);
}
<commit_msg>Updated the level to removal stupid debug statements<commit_after>#include "level.h"
#include "log.h"
#include "activemodel.h"
#include "ball.h"
#include "asteroid.h"
#include "kamikaze.h"
#include "turret.h"
#include "boundingsphere.h"
#include "boundingshape.h"
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <sstream>

Level::Level() {
    amodels = new ModelList();
    pmodels = new ModelList();
    geometries = new GeometryList();
    bombs = new BombList();
    walls = new WallList();
    forces = new ForceList();
    ship = new Ship();
    ptree = kd_create(3);
    atree = kd_create(3);
    myScore = 0;
    maxRadius = 0;
    maxARadius = 0;
    worldDepth = -10.0;
    frame = 0;
    enemieson = true;
}

Level::~Level() {
    size_t i;
    for (i = 0; i < amodels->size(); i++) delete amodels->at(i);
    delete amodels;
    for (i = 0; i < pmodels->size(); i++) delete pmodels->at(i);
    delete pmodels;
    delete geometries;
    delete bombs;
    delete walls;
}

void Level::update() {
    frame++;
    if (frame > 90) {
        frame = 0;
    }

    if (enemieson){
        generateEnemies();
    }

    updateActiveModels();
    checkActiveCollisions();
    checkShipCollisions();
    checkWallCollisions();

}

void Level::updateActiveModels() {
    ActiveModel *am;
    for (size_t i = 0; i < amodels->size(); i++) {
        am = (ActiveModel *) amodels->at(i);
        if (!behindShip(am)) {
            for (size_t j = 0; j < forces->size(); j++) {
                am->applyForce(forces->at(j));
            }
            am->update();
        }
    }
    updateATree();
}

void Level::checkActiveCollisions() {
    ActiveModel *am;
    Model *model;
    BoundingSphere *bs;
    BoundingShape *bsh;
    struct kdres *presults;
    Eigen::Vector3f pos;

    for (size_t i = 0; i < amodels->size(); i++) {
        am = (ActiveModel*) amodels->at(i);
        pos = am->position;

        // check against passive objects
        presults = kd_nearest_range3f(ptree, pos.x(), pos.y(), pos.z(), maxRadius + am->bs->radius);
        if (kd_res_size(presults) > 0) {
            /* For each bounding sphere */
            while (!kd_res_end(presults)) {
                bsh =  (BoundingShape *) kd_res_item_data(presults);
                // checks intersection
                if (bsh->intersect((BoundingSphere *) am->bs)) {
                    model = bsh->model;
                    if (!model->dead && !am->dead) {
                        //debug("Passive Hit");

                        if(!am->isAsteroid){
                            model->hit(am);
                            am->hit(model);
                        }

                        if (model->dead && am->shipPart) {
                            myScore += model->getScore(); // sets the score to 0 after reading it
                        }
                    }
                }
                kd_res_next(presults);
            }
        }

        // check against active objects
        presults = kd_nearest_range3f(atree, pos.x(), pos.y(), pos.z(), am->radius + maxARadius);
        while (!kd_res_end(presults)) {
            bs = (BoundingSphere *) kd_res_item_data(presults);
            // check intersection
            if (am->bs->intersect(bs)) {
                model = bs->model;
                if (model != am && !model->dead && !am->dead) {
                    debug("Active Hit");
                    //debug("%f", am->radius + maxARadius);
                    model->hit(am);
                    am->hit(model);
                    //SCORE WON"T WORK
                    if (model->dead) {
                        myScore += model->getScore(); // sets the score to 0 after reading it
                    }
                }

            }
            kd_res_next(presults);
        }

        kd_res_free(presults);
    }
}

void Level::checkShipCollisions() {
    Model *model;
    BoundingSphere *bs;
    Eigen::Vector3f pos = ship->position;
    struct kdres *presults = kd_nearest_range3f(ptree, pos.x(), pos.y(), pos.z(), ship->radius + maxRadius);

    if (kd_res_size(presults) > 0) {
        // for each bounding sphere
        while (!kd_res_end(presults)) {
            bs = (BoundingSphere *) kd_res_item_data(presults);
            // check intersection
            if (ship->bs->intersect(bs)) {
                model = bs->model;
                if (!model->dead) {
                    model->hit(ship);
                    ship->hit(model);
                }
            }
            kd_res_next(presults);
        }
    }

    presults = kd_nearest_range3f(atree, pos.x(), pos.y(), pos.z(), ship->radius + maxARadius);
    if (kd_res_size(presults) > 0) {
        /* For each bounding sphere */
        while( !kd_res_end( presults ) ) {
            bs = (BoundingSphere*) kd_res_item_data(presults);
            //Checks intersection
            if(ship->bs->intersect(bs)){
                model = bs->model;
                if(!model->dead){
                    model->hit(ship);
                    ship->hit(model);
                }
            }
            kd_res_next( presults );
        }
    }

    kd_res_free(presults);
}

void Level::checkWallCollisions() {
    ActiveModel *am;
    Wall *w;
    for (size_t i = 0; i < walls->size(); i++) {
        w = walls->at(i);
        for (size_t j = 0; j < amodels->size(); j++) {
            am = (ActiveModel *) amodels->at(j);
            if (w->collide(am->position, ship->position)) {
                am->die();
                debug("Wall Hit");
            }
        }
    }
}

void Level::clean() {
    Model *model;
    for (size_t i = 0; i < amodels->size(); i++) {
        model = amodels->at(i);
        if(model->dead){
            amodels->erase(amodels->begin()+i);
            if (model->isAsteroid)
                debug("Deleted an asteroid");
            else
                debug("Deleted an acitve model");
            delete model;
            i--;
        }
    }
    for (size_t i = 0; i < bombs->size(); i++) {
        model = (Model*) bombs->at(i);
        if(model->dead){
            bombs->erase(bombs->begin()+i);
            i--;
            debug("Removed a bomb");
        }
    }
}

void Level::calculateMaxRadius() {
    Model *model;
    for (size_t i = 0; i < pmodels->size(); i++) {
        model = pmodels->at(i);
        maxRadius = max(model->bs->radius, maxRadius);
    }
    for (size_t i = 0; i < amodels->size(); i++) {
        model = amodels->at(i);
        maxRadius = max(model->bs->radius, maxRadius);
    }
    debug("%f", maxRadius);
}

void Level::createTree() {
    LOG("[Level] \tMaking tree ",1);
    Model *model;
    for (size_t i = 0; i < pmodels->size(); i++) {
        model = pmodels->at(i);
        model->addSelf(ptree);
        LOG("[Level] \tInserting model " << i,1);
    }
    LOG("[Level] \tDone with tree ",1);
}

void Level::updateATree() {
    kd_clear(atree);
    atree = kd_create(3);
    Model *model;
    for (size_t i = 0; i < amodels->size(); i++) {
        model = amodels->at(i);
        maxARadius = max(model->bs->radius, maxARadius);
        model->addSelf(atree);
    }
    //debug("%f", maxARadius);
}

void Level::dump() {
    LOG("[Level] \t Dump" ,1);
    LOG("Max Radius" << maxRadius,1);
    LOG("Max A Radius" << maxARadius,1);
    LOG("Passive Models:" ,1);
    for (size_t i = 0; i < pmodels->size(); i++) {
        pmodels->at(i)->dump();
    }
    LOG("Active Models:" ,1);
    for (size_t i = 0; i < amodels->size(); i++) {
        amodels->at(i)->dump();
    }
    LOG("Geometries:" ,1);
    for (size_t i = 0; i < geometries->size(); i++) {
        geometries->at(i)->dump();
    }
    LOG("Walls:" ,1);
    for (size_t i = 0; i < walls->size(); i++) {
        walls->at(i)->dump();
    }
}

void Level::draw(float farClippingPlane) {
    drawActive(farClippingPlane);
    drawPassive(farClippingPlane);
    clean();
}

void Level::drawActive(float farClippingPlane) {
    Model *model;
    for (size_t i = 0; i < amodels->size(); i++) {
        model = amodels->at(i);
        if (model->position.z() < farClippingPlane && !behindShip(model)) {
            model->draw();
        }
    }
}

void Level::drawPassive(float farClippingPlane) {
    Model *model;
    for (size_t i = 0; i < pmodels->size(); i++) {
        model = pmodels->at(i);
        if (model->position.z() < farClippingPlane && !behindShip(model)) {
            model->draw();
        }
    }
}

bool Level::behindShip(Model *model) {
    return model->position.z() > ship->position.z() + 5.0;
}

void Level::generateEnemies() {
	// randomly generate enemies to attack the ship
	int random_integer = rand() % 20 + 1;

	//debug("random number %d", random_integer);
            //      if (random_integer == 3) { // 1 in 20 chance we make a kamikaze
            //            Eigen::Vector3f entryPos = ship->position;
            //            entryPos[2] -= 5;
            //            entryPos[0] = -0.2 + (rand() %50) / 100.0;
            //            Kamikaze * suicide = new Kamikaze();
            //            suicide->position = entryPos;
            //
            //            enemies->push_back((Enemy *)suicide);
            //
            //          //BS INIT
            // suicide->bs->transform(&suicide->transM, suicide->scale[0]);
            //            amodels->push_back(suicide);
            //     }
    //
	if (random_integer == 20) { // 1 in 10 chance we make an asteroid
		Eigen::Vector3f entryPos = ship->position;
		entryPos[2] -= 5;
		entryPos[1] = -0.5 + (rand() %100) /100.0;
		entryPos[0] = -0.5 + (rand() %100) / 100.0;
		Eigen::Vector3f vel = (ship->position - entryPos);
		vel.normalize();
		vel /= 30;
		unsigned int astNum = rand() % 18 + 1;
		Asteroid * rock = new Asteroid(astNum);
		rock->position = entryPos;
		rock->velocity = -vel;
        rock->scale = Eigen::Vector3f(0.3,0.3,0.3);
        rock->calculateTransform();

		//BS INIT
        rock->bs->transform(&rock->transM, rock->scale[0]);
		amodels->push_back(rock);
	}

	//if (done != 0) {
	//	debug ("creating new turret");
	//	Turret * newTurret = new Turret();

	//	newTurret->position = ship->position;
	//	newTurret->position.z() -= 0.1;
	//
	//	enemies->push_back((Enemy *) newTurret);
	//	pmodels->push_back(newTurret);
	//	done = 0;
	//}
}

void Level::drawHealthBar() {
	unsigned int myHealth = ship->health;
	if (myHealth < 0 || myHealth > 100) {
        myHealth = 0;
	}
	renderHealthbar((float)myHealth);

	// draw the current health number
	char health_str[4];
	itoa(myHealth, health_str);
	void *font = GLUT_BITMAP_9_BY_15;
	int health_pos_x = 112;
	int health_pos_y = 20;
	Color health_color = Color(1.0,1.0,1.0);
	if (myHealth > 60) {
		health_color = Color(0.0,1.0,0.0);
	} else if (myHealth > 30) {
		health_color = Color(1.0,1.0,0.0);
	} else {
		health_color = Color(1.0,0.0,0.0);
	}
	renderText(health_pos_x, health_pos_y, font, health_str, health_color);
}

void Level::drawScore() {
	char score_str[MAX_SCORE_DIGITS+1];
	itoa(myScore, score_str);

	renderScore(score_str);
}
<|endoftext|>


<commit_before>#include <seastar/core/print.hh>
#include <seastar/core/reactor.hh>
#include <seastar/util/log.hh>
#include "lister.hh"
#include "disk-error-handler.hh"
#include "checked-file-impl.hh"

static seastar::logger llogger("lister");

lister::lister(file f, dir_entry_types type, walker_type walker, filter_type filter, fs::path dir, lister::show_hidden do_show_hidden)
        : _f(std::move(f))
        , _walker(std::move(walker))
        , _filter(std::move(filter))
        , _expected_type(std::move(type))
        , _listing(_f.list_directory([this] (directory_entry de) { return visit(de); }))
        , _dir(std::move(dir))
        , _show_hidden(do_show_hidden) {}

future<> lister::visit(directory_entry de) {
    return guarantee_type(std::move(de)).then([this] (directory_entry de) {
        // Hide all synthetic directories and hidden files if not requested to show them.
        if ((!_expected_type.empty() && !_expected_type.count(*(de.type))) || (!_show_hidden && de.name[0] == '.')) {
            return make_ready_future<>();
        }

        // apply a filter
        if (!_filter(_dir, de)) {
            return make_ready_future<>();
        }

        return _walker(_dir, std::move(de));
    });
}

future<> lister::done() {
    return _listing.done().then([this] {
        return _f.close();
    });
}

future<directory_entry> lister::guarantee_type(directory_entry de) {
    if (de.type) {
        return make_ready_future<directory_entry>(std::move(de));
    } else {
        auto f = engine().file_type((_dir / de.name.c_str()).native());
        return f.then([dir = _dir, de = std::move(de)] (std::optional<directory_entry_type> t) mutable {
            // If some FS error occures - return an exceptional future
            if (!t) {
                return make_exception_future<directory_entry>(std::runtime_error(format("Failed to get {} type.", (dir / de.name.c_str()).native())));
            }
            de.type = t;
            return make_ready_future<directory_entry>(std::move(de));
        });
    }
}

future<> lister::scan_dir(fs::path dir, lister::dir_entry_types type, lister::show_hidden do_show_hidden, walker_type walker, filter_type filter) {
    return open_checked_directory(general_disk_error_handler, dir.native()).then([type = std::move(type), walker = std::move(walker), filter = std::move(filter), dir, do_show_hidden] (file f) {
            auto l = make_lw_shared<lister>(std::move(f), std::move(type), std::move(walker), std::move(filter), std::move(dir), do_show_hidden);
            return l->done().then([l] { });
    });
}

future<> lister::rmdir(fs::path dir) {
    // first, kill the contents of the directory
    return lister::scan_dir(dir, {}, show_hidden::yes, [] (fs::path parent_dir, directory_entry de) mutable {
        fs::path current_entry_path(parent_dir / de.name.c_str());

        if (de.type.value() == directory_entry_type::directory) {
            return rmdir(std::move(current_entry_path));
        } else {
            return io_check(remove_file, current_entry_path.native());
        }
    }).then([dir] {
        // ...then kill the directory itself
        return io_check(remove_file, dir.native());
    });
}
<commit_msg>lister::guarantee_type: do not follow symlink<commit_after>#include <seastar/core/print.hh>
#include <seastar/core/reactor.hh>
#include <seastar/util/log.hh>
#include "lister.hh"
#include "disk-error-handler.hh"
#include "checked-file-impl.hh"

static seastar::logger llogger("lister");

lister::lister(file f, dir_entry_types type, walker_type walker, filter_type filter, fs::path dir, lister::show_hidden do_show_hidden)
        : _f(std::move(f))
        , _walker(std::move(walker))
        , _filter(std::move(filter))
        , _expected_type(std::move(type))
        , _listing(_f.list_directory([this] (directory_entry de) { return visit(de); }))
        , _dir(std::move(dir))
        , _show_hidden(do_show_hidden) {}

future<> lister::visit(directory_entry de) {
    return guarantee_type(std::move(de)).then([this] (directory_entry de) {
        // Hide all synthetic directories and hidden files if not requested to show them.
        if ((!_expected_type.empty() && !_expected_type.count(*(de.type))) || (!_show_hidden && de.name[0] == '.')) {
            return make_ready_future<>();
        }

        // apply a filter
        if (!_filter(_dir, de)) {
            return make_ready_future<>();
        }

        return _walker(_dir, std::move(de));
    });
}

future<> lister::done() {
    return _listing.done().then([this] {
        return _f.close();
    });
}

future<directory_entry> lister::guarantee_type(directory_entry de) {
    if (de.type) {
        return make_ready_future<directory_entry>(std::move(de));
    } else {
        auto f = engine().file_type((_dir / de.name.c_str()).native(), follow_symlink::no);
        return f.then([dir = _dir, de = std::move(de)] (std::optional<directory_entry_type> t) mutable {
            // If some FS error occures - return an exceptional future
            if (!t) {
                return make_exception_future<directory_entry>(std::runtime_error(format("Failed to get {} type.", (dir / de.name.c_str()).native())));
            }
            de.type = t;
            return make_ready_future<directory_entry>(std::move(de));
        });
    }
}

future<> lister::scan_dir(fs::path dir, lister::dir_entry_types type, lister::show_hidden do_show_hidden, walker_type walker, filter_type filter) {
    return open_checked_directory(general_disk_error_handler, dir.native()).then([type = std::move(type), walker = std::move(walker), filter = std::move(filter), dir, do_show_hidden] (file f) {
            auto l = make_lw_shared<lister>(std::move(f), std::move(type), std::move(walker), std::move(filter), std::move(dir), do_show_hidden);
            return l->done().then([l] { });
    });
}

future<> lister::rmdir(fs::path dir) {
    // first, kill the contents of the directory
    return lister::scan_dir(dir, {}, show_hidden::yes, [] (fs::path parent_dir, directory_entry de) mutable {
        fs::path current_entry_path(parent_dir / de.name.c_str());

        if (de.type.value() == directory_entry_type::directory) {
            return rmdir(std::move(current_entry_path));
        } else {
            return io_check(remove_file, current_entry_path.native());
        }
    }).then([dir] {
        // ...then kill the directory itself
        return io_check(remove_file, dir.native());
    });
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2008-2016 the MRtrix3 contributors
 *
 * 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/
 *
 * MRtrix 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.
 *
 * For more details, see www.mrtrix.org
 *
 */

#include <unsupported/Eigen/MatrixFunctions>
#include <algorithm>
#include "command.h"
#include "math/math.h"
#include "math/average_space.h"
#include "image.h"
#include "file/nifti1_utils.h"
#include "transform.h"
#include "file/key_value.h"

using namespace MR;
using namespace App;

const char* operations[] = {
  "invert",
  "half",
  "rigid",
  "header",
  "average",
  "interpolate",
  "decompose",
  NULL
};

void usage ()
{
  AUTHOR = "Max Pietsch (maximilian.pietsch@kcl.ac.uk)";

  DESCRIPTION
  + "This command's function is to process linear transformation matrices."

  + "It allows to perform affine matrix operations or to convert the transformation matrix provided by FSL's flirt command to a format usable in MRtrix"
  ;

  ARGUMENTS
  + Argument ("input", "the input for the specified operation").allow_multiple()
  + Argument ("operation", "the operation to perform, one of: " + join(operations, ", ") + "."
    + "\n\ninvert: invert the input transformation:\nmatrix_in invert output"

    + "\n\nhalf: calculate the matrix square root of the input transformation:\nmatrix_in half output"

    + "\n\nrigid: calculate the rigid transformation of the affine input transformation:\nmatrix_in rigid output"

    + "\n\nheader: calculate the transformation matrix from an original image and an image with modified header:\nmov mapmovhdr header output"

    + "\n\naverage: calculate the average affine matrix of all input matrices:\ninput ... average output"

    + "\n\ninterpolate: create interpolated transformation matrix between input (t=0) and input2 (t=1). "
        "Based on matrix decomposition with linear interpolation of "
        " translation, rotation and stretch described in "
        " Shoemake, K., Hill, M., & Duff, T. (1992). Matrix Animation and Polar Decomposition. "
        " Matrix, 92, 258-264. doi:10.1.1.56.1336"
        "\ninput input2 interpolate output"

    + "\n\ndecompose: decompose transformation matrix M into translation, rotation and stretch and shear (M = T * R * S). "
        "The output is a key-value text file "
        "scaling: vector of 3 scaling factors in x, y, z direction, "
        "shear: list of shear factors for xy, xz, yz axes, "
        "angles: list of Euler angles about static x, y, z axes in radians in the range [0:pi]x[-pi:pi]x[-pi:pi], "
        "translation : translation vector along x, y, z axes in mm, "
        "R: composed roation matrix (R = rot_x * rot_y * rot_z), "
        "S: composed scaling and shear matrix."
        "\nmatrix_in decompose output"
    ).type_choice (operations)
  + Argument ("output", "the output transformation matrix.").type_file_out ();
}

template <typename T> int sgn(T val) {
    return (T(0) < val) - (val < T(0));
}

void run ()
{
  const size_t num_inputs = argument.size() - 2;
  const int op = argument[num_inputs];
  const std::string& output_path = argument.back();

  switch (op) {
    case 0: { // invert
      if (num_inputs != 1)
        throw Exception ("invert requires 1 input");
      transform_type input = load_transform<default_type> (argument[0]);
      save_transform (input.inverse(), output_path);
      break;
    }
    case 1: { // half
      if (num_inputs != 1)
        throw Exception ("half requires 1 input");
      Eigen::Transform<default_type, 3, Eigen::Projective> input = load_transform<default_type> (argument[0]);
      transform_type output;
      Eigen::Matrix<default_type, 4, 4> half = input.matrix().sqrt();
      output.matrix() = half.topLeftCorner(3,4);
      save_transform (output, output_path);
      break;
    }
    case 2: { // rigid
      if (num_inputs != 1)
        throw Exception ("rigid requires 1 input");
      transform_type input = load_transform<default_type> (argument[0]);
      transform_type output (input);
      output.linear() = input.rotation();
      save_transform (output, output_path);
      break;
    }
    case 3: { // header
      if (num_inputs != 2)
        throw Exception ("header requires 2 inputs");
      auto orig_header = Header::open (argument[0]);
      auto modified_header = Header::open (argument[1]);

      transform_type forward_transform = Transform(modified_header).voxel2scanner * Transform(orig_header).voxel2scanner.inverse();
      save_transform (forward_transform.inverse(), output_path);
      break;
    }
    case 4: { // average
      if (num_inputs < 2)
        throw Exception ("average requires at least 2 inputs");
      transform_type transform_out;
      Eigen::Transform<default_type, 3, Eigen::Projective> Tin;
      Eigen::MatrixXd Min;
      std::vector<Eigen::MatrixXd> matrices;
      for (size_t i = 0; i < num_inputs; i++) {
        DEBUG(str(argument[i]));
        Tin = load_transform<default_type> (argument[i]);
        matrices.push_back(Tin.matrix());
      }

      Eigen::MatrixXd average_matrix;
      Math::matrix_average ( matrices, average_matrix);
      transform_out.matrix() = average_matrix.topLeftCorner(3,4);
      save_transform (transform_out, output_path);
      break;
    }
    case 5: { // interpolate
      if (num_inputs != 3)
        throw Exception ("interpolation requires 3 inputs");
      transform_type transform1 = load_transform<default_type> (argument[0]);
      transform_type transform2 = load_transform<default_type> (argument[1]);
      default_type t = parse_floats(argument[2])[0];

      transform_type transform_out;

      if (t < 0.0 || t > 1.0)
        throw Exception ("t has to be in the interval [0,1]");

      Eigen::MatrixXd M1 = transform1.linear();
      Eigen::MatrixXd M2 = transform2.linear();
      if (sgn(M1.determinant()) != sgn(M2.determinant()))
        WARN("transformation determinants have different signs");

      Eigen::Matrix3d R1 = transform1.rotation();
      Eigen::Matrix3d R2 = transform2.rotation();
      Eigen::Quaterniond Q1(R1);
      Eigen::Quaterniond Q2(R2);
      Eigen::Quaterniond Qout;

      // stretch (shear becomes roation and stretch)
      Eigen::MatrixXd S1 = R1.transpose() * M1;
      Eigen::MatrixXd S2 = R2.transpose() * M2;
      if (!M1.isApprox(R1*S1))
        WARN ("M1 matrix decomposition might have failed");
      if (!M2.isApprox(R2*S2))
        WARN ("M2 matrix decomposition might have failed");

      transform_out.translation() = ((1.0 - t) * transform1.translation() + t * transform2.translation());
      Qout = Q1.slerp(t, Q2);
      transform_out.linear() = Qout * ((1 - t) * S1 + t * S2);
      INFO("\n"+str(transform_out.matrix().format(
        Eigen::IOFormat(Eigen::FullPrecision, 0, ", ", ",\n", "[", "]", "[", "]"))));
      save_transform (transform_out, output_path);
      break;
    }
    case 6: { // decompose
      if (num_inputs != 1)
        throw Exception ("decomposition requires 1 input");
      transform_type transform = load_transform<default_type> (argument[0]);

      Eigen::MatrixXd M = transform.linear();
      Eigen::Matrix3d R = transform.rotation();
      Eigen::MatrixXd S = R.transpose() * M;
      if (!M.isApprox(R*S))
        WARN ("matrix decomposition might have failed");

      Eigen::Vector3d euler_angles = R.eulerAngles(0, 1, 2);
      assert (R.isApprox((Eigen::AngleAxisd(euler_angles[0], Eigen::Vector3d::UnitX())
              * Eigen::AngleAxisd(euler_angles[1], Eigen::Vector3d::UnitY())
              * Eigen::AngleAxisd(euler_angles[2], Eigen::Vector3d::UnitZ())).matrix()));

      File::OFStream out (output_path);
      Eigen::IOFormat fmt(Eigen::FullPrecision, Eigen::DontAlignCols, " ", "\n", "", "", "", "\n");
      out << "scaling: "     << Eigen::RowVector3d(S(0,0), S(1,1), S(2,2)).format(fmt);
      out << "shear: "       << Eigen::RowVector3d(S(0,0), S(1,1), S(2,2)).format(fmt);
      out << "angles: "      << euler_angles.transpose().format(fmt);
      out << "translation: " << transform.translation().transpose().format(fmt);
      out << "R: " << R.row(0).format(fmt);
      out << "R: " << R.row(1).format(fmt);
      out << "R: " << R.row(2).format(fmt);
      out << "S: " << S.row(0).format(fmt);
      out << "S: " << S.row(1).format(fmt);
      out << "S: " << S.row(2).format(fmt);

      break;
    }
    default: assert (0);
  }

}
<commit_msg>transformclac: fexed bug in shear output. added angle axis output<commit_after>/*
 * Copyright (c) 2008-2016 the MRtrix3 contributors
 *
 * 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/
 *
 * MRtrix 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.
 *
 * For more details, see www.mrtrix.org
 *
 */

#include <unsupported/Eigen/MatrixFunctions>
#include <algorithm>
#include "command.h"
#include "math/math.h"
#include "math/average_space.h"
#include "image.h"
#include "file/nifti1_utils.h"
#include "transform.h"
#include "file/key_value.h"

using namespace MR;
using namespace App;

const char* operations[] = {
  "invert",
  "half",
  "rigid",
  "header",
  "average",
  "interpolate",
  "decompose",
  NULL
};

void usage ()
{
  AUTHOR = "Max Pietsch (maximilian.pietsch@kcl.ac.uk)";

  DESCRIPTION
  + "This command's function is to process linear transformation matrices."

  + "It allows to perform affine matrix operations or to convert the transformation matrix provided by FSL's flirt command to a format usable in MRtrix"
  ;

  ARGUMENTS
  + Argument ("input", "the input for the specified operation").allow_multiple()
  + Argument ("operation", "the operation to perform, one of: " + join(operations, ", ") + "."
    + "\n\ninvert: invert the input transformation:\nmatrix_in invert output"

    + "\n\nhalf: calculate the matrix square root of the input transformation:\nmatrix_in half output"

    + "\n\nrigid: calculate the rigid transformation of the affine input transformation:\nmatrix_in rigid output"

    + "\n\nheader: calculate the transformation matrix from an original image and an image with modified header:\nmov mapmovhdr header output"

    + "\n\naverage: calculate the average affine matrix of all input matrices:\ninput ... average output"

    + "\n\ninterpolate: create interpolated transformation matrix between input (t=0) and input2 (t=1). "
        "Based on matrix decomposition with linear interpolation of "
        " translation, rotation and stretch described in "
        " Shoemake, K., Hill, M., & Duff, T. (1992). Matrix Animation and Polar Decomposition. "
        " Matrix, 92, 258-264. doi:10.1.1.56.1336"
        "\ninput input2 interpolate output"

    + "\n\ndecompose: decompose transformation matrix M into translation, rotation and stretch and shear (M = T * R * S). "
        "The output is a key-value text file "
        "scaling: vector of 3 scaling factors in x, y, z direction, "
        "shear: list of shear factors for xy, xz, yz axes, "
        "angles: list of Euler angles about static x, y, z axes in radians in the range [0:pi]x[-pi:pi]x[-pi:pi], "
        "angle_axis: angle in radians and rotation axis, "
        "translation : translation vector along x, y, z axes in mm, "
        "R: composed roation matrix (R = rot_x * rot_y * rot_z), "
        "S: composed scaling and shear matrix."
        "\nmatrix_in decompose output"
    ).type_choice (operations)
  + Argument ("output", "the output transformation matrix.").type_file_out ();
}

template <typename T> int sgn(T val) {
    return (T(0) < val) - (val < T(0));
}

void run ()
{
  const size_t num_inputs = argument.size() - 2;
  const int op = argument[num_inputs];
  const std::string& output_path = argument.back();

  switch (op) {
    case 0: { // invert
      if (num_inputs != 1)
        throw Exception ("invert requires 1 input");
      transform_type input = load_transform<default_type> (argument[0]);
      save_transform (input.inverse(), output_path);
      break;
    }
    case 1: { // half
      if (num_inputs != 1)
        throw Exception ("half requires 1 input");
      Eigen::Transform<default_type, 3, Eigen::Projective> input = load_transform<default_type> (argument[0]);
      transform_type output;
      Eigen::Matrix<default_type, 4, 4> half = input.matrix().sqrt();
      output.matrix() = half.topLeftCorner(3,4);
      save_transform (output, output_path);
      break;
    }
    case 2: { // rigid
      if (num_inputs != 1)
        throw Exception ("rigid requires 1 input");
      transform_type input = load_transform<default_type> (argument[0]);
      transform_type output (input);
      output.linear() = input.rotation();
      save_transform (output, output_path);
      break;
    }
    case 3: { // header
      if (num_inputs != 2)
        throw Exception ("header requires 2 inputs");
      auto orig_header = Header::open (argument[0]);
      auto modified_header = Header::open (argument[1]);

      transform_type forward_transform = Transform(modified_header).voxel2scanner * Transform(orig_header).voxel2scanner.inverse();
      save_transform (forward_transform.inverse(), output_path);
      break;
    }
    case 4: { // average
      if (num_inputs < 2)
        throw Exception ("average requires at least 2 inputs");
      transform_type transform_out;
      Eigen::Transform<default_type, 3, Eigen::Projective> Tin;
      Eigen::MatrixXd Min;
      std::vector<Eigen::MatrixXd> matrices;
      for (size_t i = 0; i < num_inputs; i++) {
        DEBUG(str(argument[i]));
        Tin = load_transform<default_type> (argument[i]);
        matrices.push_back(Tin.matrix());
      }

      Eigen::MatrixXd average_matrix;
      Math::matrix_average ( matrices, average_matrix);
      transform_out.matrix() = average_matrix.topLeftCorner(3,4);
      save_transform (transform_out, output_path);
      break;
    }
    case 5: { // interpolate
      if (num_inputs != 3)
        throw Exception ("interpolation requires 3 inputs");
      transform_type transform1 = load_transform<default_type> (argument[0]);
      transform_type transform2 = load_transform<default_type> (argument[1]);
      default_type t = parse_floats(argument[2])[0];

      transform_type transform_out;

      if (t < 0.0 || t > 1.0)
        throw Exception ("t has to be in the interval [0,1]");

      Eigen::MatrixXd M1 = transform1.linear();
      Eigen::MatrixXd M2 = transform2.linear();
      if (sgn(M1.determinant()) != sgn(M2.determinant()))
        WARN("transformation determinants have different signs");

      Eigen::Matrix3d R1 = transform1.rotation();
      Eigen::Matrix3d R2 = transform2.rotation();
      Eigen::Quaterniond Q1(R1);
      Eigen::Quaterniond Q2(R2);
      Eigen::Quaterniond Qout;

      // stretch (shear becomes roation and stretch)
      Eigen::MatrixXd S1 = R1.transpose() * M1;
      Eigen::MatrixXd S2 = R2.transpose() * M2;
      if (!M1.isApprox(R1*S1))
        WARN ("M1 matrix decomposition might have failed");
      if (!M2.isApprox(R2*S2))
        WARN ("M2 matrix decomposition might have failed");

      transform_out.translation() = ((1.0 - t) * transform1.translation() + t * transform2.translation());
      Qout = Q1.slerp(t, Q2);
      transform_out.linear() = Qout * ((1 - t) * S1 + t * S2);
      INFO("\n"+str(transform_out.matrix().format(
        Eigen::IOFormat(Eigen::FullPrecision, 0, ", ", ",\n", "[", "]", "[", "]"))));
      save_transform (transform_out, output_path);
      break;
    }
    case 6: { // decompose
      if (num_inputs != 1)
        throw Exception ("decomposition requires 1 input");
      transform_type transform = load_transform<default_type> (argument[0]);

      Eigen::MatrixXd M = transform.linear();
      Eigen::Matrix3d R = transform.rotation();
      Eigen::MatrixXd S = R.transpose() * M;
      if (!M.isApprox(R*S))
        WARN ("matrix decomposition might have failed");

      Eigen::Vector3d euler_angles = R.eulerAngles(0, 1, 2);
      assert (R.isApprox((Eigen::AngleAxisd(euler_angles[0], Eigen::Vector3d::UnitX())
              * Eigen::AngleAxisd(euler_angles[1], Eigen::Vector3d::UnitY())
              * Eigen::AngleAxisd(euler_angles[2], Eigen::Vector3d::UnitZ())).matrix()));

      Eigen::RowVector4d angle_axis;
      {
        auto AA = Eigen::AngleAxis<default_type> (R);
        angle_axis(0) = AA.angle();
        angle_axis.block<1,3>(0,1) = AA.axis();
      }

      File::OFStream out (output_path);
      Eigen::IOFormat fmt(Eigen::FullPrecision, Eigen::DontAlignCols, " ", "\n", "", "", "", "\n");
      out << "scaling: "     << Eigen::RowVector3d(S(0,0), S(1,1), S(2,2)).format(fmt);
      out << "shear: "       << Eigen::RowVector3d(S(0,1), S(0,2), S(1,2)).format(fmt);
      out << "angles: "      << euler_angles.transpose().format(fmt);
      out << "angle_axis: "   << angle_axis.format(fmt);
      out << "translation: " << transform.translation().transpose().format(fmt);
      out << "R: " << R.row(0).format(fmt);
      out << "R: " << R.row(1).format(fmt);
      out << "R: " << R.row(2).format(fmt);
      out << "S: " << S.row(0).format(fmt);
      out << "S: " << S.row(1).format(fmt);
      out << "S: " << S.row(2).format(fmt);

      break;
    }
    default: assert (0);
  }

}
<|endoftext|>


<commit_before>#include "../include/debugGTK.h"
#include "machine.cpp"
#include <iostream>

debugGTK::debugGTK()
	:
	step("Step"),
	finish("Finish"),
	quit("Quit"),
	advance("Advance")
{
	BFM = new machine(30000, false, true, "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]@>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>@+.>++@.!");
	add(masterGrid);
	masterGrid.set_border_width(5);
	set_title("Therapist Debugger");
	set_size_request(800, 500);

	get_size(windowWidth, windowHeight);

	masterGrid.attach(controlFrame, 1, 1, 1, 3);
	masterGrid.attach(tapeFrame, 2, 1, windowWidth-1, 1);

	drawControlFrame();
	createTapeFrame();
	show_all_children();

	step.signal_clicked().connect(sigc::mem_fun(*this, &debugGTK::stepF));
	BFM->notify_tape_change().connect(sigc::mem_fun(*this, &debugGTK::drawTapeFrame));

	advance.signal_clicked().connect(sigc::mem_fun(*this, &debugGTK::advanceToHalt));
	finish.signal_clicked().connect(sigc::mem_fun(*this, &debugGTK::advanceToEnd));
	quit.signal_clicked().connect(sigc::mem_fun(*this, &debugGTK::endDebugger));
}

void debugGTK::createTapeFrame(){
	tapeFrame.set_border_width(10);
	tapeFrame.set_shadow_type(Gtk::SHADOW_ETCHED_OUT);
	tapeFrame.set_label("Tape");
	tapeFrame.add(tapeGrid);

	for(int i = 0; i < 10; i++){
		tapeCells[i].set_margin_start(10);
		tapeCells[i].set_margin_end(10);
		tapeCells[i].property_use_markup();
		tapeGrid.attach(tapeCells[i], i+1, 1, 1, 1);
	}

	drawTapeFrame();
}

void debugGTK::drawTapeFrame(){
	for(int i = 0; i < 10; i++){
		tapeCells[i].set_text(std::to_string(BFM->getTapeAt(i)));
	}
}

void debugGTK::drawControlFrame(){

	controlFrame.set_border_width(10);
	controlFrame.set_shadow_type(Gtk::SHADOW_ETCHED_OUT);
	controlFrame.set_label("Controls");
	controlFrame.add(controlGrid);

	controlGrid.set_border_width(5);
	controlGrid.attach(step, 1, 1, 1, 1);
	controlGrid.attach(advance, 1, 2, 1, 1);
	controlGrid.attach(finish, 1, 3, 1, 1);
	controlGrid.attach(quit, 1, 4, 1, 1);

	step.set_border_width(5);
	finish.set_border_width(5);
	quit.set_border_width(5);
}

debugGTK::~debugGTK(){}

void debugGTK::stepF(){
	char retOp = BFM->processChar(1);
}

void debugGTK::advanceToEnd(){
	BFM->processSource();
	drawTapeFrame();
}

void debugGTK::advanceToHalt(){
	while(BFM->processChar(1) != '@');
	drawTapeFrame();
}

void debugGTK::endDebugger(){
	exit(0);
}
<commit_msg>Tape highlights cells by data pointer now<commit_after>#include "../include/debugGTK.h"
#include "machine.cpp"
#include <iostream>

debugGTK::debugGTK()
	:
	step("Step"),
	finish("Finish"),
	quit("Quit"),
	advance("Advance")
{
	BFM = new machine(30000, false, true, "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]@>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>@+.>++@.!");
	add(masterGrid);
	masterGrid.set_border_width(5);
	set_title("Therapist Debugger");
	set_size_request(800, 500);

	get_size(windowWidth, windowHeight);

	masterGrid.attach(controlFrame, 1, 1, 1, 3);
	masterGrid.attach(tapeFrame, 2, 1, windowWidth-1, 1);

	drawControlFrame();
	createTapeFrame();
	show_all_children();

	step.signal_clicked().connect(sigc::mem_fun(*this, &debugGTK::stepF));
	BFM->notify_tape_change().connect(sigc::mem_fun(*this, &debugGTK::drawTapeFrame));

	advance.signal_clicked().connect(sigc::mem_fun(*this, &debugGTK::advanceToHalt));
	finish.signal_clicked().connect(sigc::mem_fun(*this, &debugGTK::advanceToEnd));
	quit.signal_clicked().connect(sigc::mem_fun(*this, &debugGTK::endDebugger));
}

void debugGTK::createTapeFrame(){
	tapeFrame.set_border_width(10);
	tapeFrame.set_shadow_type(Gtk::SHADOW_ETCHED_OUT);
	tapeFrame.set_label("Tape");
	tapeFrame.add(tapeGrid);

	for(int i = 0; i < 10; i++){
		tapeCells[i].set_margin_start(10);
		tapeCells[i].set_margin_end(10);
		tapeCells[i].property_use_markup();
		tapeGrid.attach(tapeCells[i], i+1, 1, 1, 1);
	}

	drawTapeFrame();
}

void debugGTK::drawTapeFrame(){
	for(int i = -1; i < 9; i++){
		if(!i)
			tapeCells[i+1].override_color(Gdk::RGBA("red"), Gtk::STATE_FLAG_NORMAL);
		else
			tapeCells[i+1].override_color(Gdk::RGBA("black"), Gtk::STATE_FLAG_NORMAL);
		tapeCells[i+1].set_label(std::to_string(BFM->getTapeAt(BFM->getDataPointer()+i)));
	}
}

void debugGTK::drawControlFrame(){

	controlFrame.set_border_width(10);
	controlFrame.set_shadow_type(Gtk::SHADOW_ETCHED_OUT);
	controlFrame.set_label("Controls");
	controlFrame.add(controlGrid);

	controlGrid.set_border_width(5);
	controlGrid.attach(step, 1, 1, 1, 1);
	controlGrid.attach(advance, 1, 2, 1, 1);
	controlGrid.attach(finish, 1, 3, 1, 1);
	controlGrid.attach(quit, 1, 4, 1, 1);

	step.set_border_width(5);
	finish.set_border_width(5);
	quit.set_border_width(5);
}

debugGTK::~debugGTK(){}

void debugGTK::stepF(){
	char retOp = BFM->processChar(1);
}

void debugGTK::advanceToEnd(){
	BFM->processSource();
	drawTapeFrame();
}

void debugGTK::advanceToHalt(){
	while(BFM->processChar(1) != '@');
	drawTapeFrame();
}

void debugGTK::endDebugger(){
	exit(0);
}
<|endoftext|>