<commit_before>#include "stdafx.hpp"

#include <functional>

#include "CppUnitTest.h"
#include "..\TestUtilities\TestUtilities.hpp"
#include "..\TestUtilities\QuantityComparisons.hpp"
#include "..\TestUtilities\GeometryComparisons.hpp"
#include "..\TestUtilities\Algebra.hpp"

#include "..\Quantities\Dimensionless.hpp"
#include "..\Quantities\Quantities.hpp"
#include "..\Quantities\SI.hpp"
#include "..\Quantities\Constants.hpp"
#include "..\Quantities\UK.hpp"
#include "..\Quantities\BIPM.hpp"
#include "..\Quantities\Astronomy.hpp"
#include "..\Geometry\R3Element.hpp"
#include "..\Geometry\Grassmann.hpp"
#include "..\Quantities\ElementaryFunctions.hpp"

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace Principia {
namespace GeometryTests
{
using namespace Geometry;
using namespace Quantities;
using namespace SI;
using namespace UK;
using namespace BIPM;
using namespace Astronomy;
using namespace Constants;
using namespace TestUtilities;

TEST_CLASS(GeometryTests)
{
 public:
  struct World;
  TEST_METHOD(Dumb3Vector) {
    R3Element<Speed> nullVector(0 * Metre / Second,
                                0 * Metre / Second,
                                0 * Metre / Second);
    R3Element<Speed> u(1 * Metre / Second,
                       120 * Kilo(Metre) / Hour,
                       -SpeedOfLight);
    R3Element<Speed> v(-20 * Knot,
                       2 * π * AstronomicalUnit / JulianYear,
                       1 * Admiralty::NauticalMile / Hour);
    R3Element<Speed> w(-1 * Mile / Hour, -2 * Foot / Second, -3 * Knot);
    R3Element<Speed> a(88 * Mile / Hour, 300 * Metre / Second, 46 * Knot);
    AssertEqual((e * Dimensionless(42)) * v, e * (Dimensionless(42) * v));
    TestVectorSpace<R3Element<Speed>,
                    Dimensionless>(nullVector, u, v, w, Dimensionless(0),
                                   Dimensionless(1), e, Dimensionless(42));
    TestAlternatingBilinearMap(Cross<Speed, Speed>, u,
                               v, w, a, Dimensionless(42));
    TestSymmetricPositiveDefiniteBilinearMap(Dot<Speed, Speed>,
                                             u, v, w, a, Dimensionless(42));
  }

  TEST_METHOD(SpecialOrthogonalLieAlgebra) {
    R3Element<Dimensionless> u(3, -42, 0);
    R3Element<Dimensionless> v(-π, -e, -1);
    R3Element<Dimensionless> w(2, 2, 2);
    R3Element<Dimensionless> a(1.2, 2.3, 3.4);
    TestLieBracket(Commutator<Dimensionless, Dimensionless, World>,
                   Bivector<Dimensionless, World>(u),
                   Bivector<Dimensionless, World>(v),
                   Bivector<Dimensionless, World>(w),
                   Bivector<Dimensionless, World>(a), Dimensionless(0.42));
  }

  TEST_METHOD(VectorSpaces) {
    R3Element<Length> nullDisplacement(0 * Metre, 0 * Metre, 0 * Metre);
    R3Element<Length> u(3 * Metre, -42 * Metre, 0 * Metre);
    R3Element<Length> v(-π * Metre, -e * Metre, -1 * Metre);
    R3Element<Length> w(2 * Metre, 2 * Metre, 2 * Metre);
    R3Element<Length> a(1 * Inch, 2 * Foot, 3 * Admiralty::Fathom);
    {
      std::function<Area(Vector<Length, World>,
                         Vector<Length, World>)> vectorInnerProduct =
      [](Vector<Length, World> a, Vector<Length, World> b) {
        return InnerProduct(a, b);
      };
      std::function<Area(Bivector<Length, World>,
                         Bivector<Length, World>)> bivectorInnerProduct =
      [](Bivector<Length, World> a, Bivector<Length, World> b) {
        return InnerProduct(a, b);
      };
      std::function<Area(Trivector<Length, World>,
                         Trivector<Length, World>)> trivectorInnerProduct =
      [](Trivector<Length, World> a, Trivector<Length, World> b) {
        return InnerProduct(a, b);
      };
      TestInnerProductSpace(vectorInnerProduct,
                            Vector<Length, World>(nullDisplacement),
                            Vector<Length, World>(u), Vector<Length, World>(v),
                            Vector<Length, World>(w), Vector<Length, World>(a),
                            Dimensionless(0), Dimensionless(1), Sqrt(163),
                            -Sqrt(2));
      TestInnerProductSpace(bivectorInnerProduct,
                            Bivector<Length, World>(nullDisplacement),
                            Bivector<Length, World>(u),
                            Bivector<Length, World>(v),
                            Bivector<Length, World>(w),
                            Bivector<Length, World>(a),
                            Dimensionless(0), Dimensionless(1), Sqrt(163),
                            -Sqrt(2));
      TestInnerProductSpace(trivectorInnerProduct,
                            Trivector<Length, World>(nullDisplacement.x),
                            Trivector<Length, World>(u.y),
                            Trivector<Length, World>(v.z),
                            Trivector<Length, World>(w.x),
                            Trivector<Length, World>(a.y),
                            Dimensionless(0), Dimensionless(1), Sqrt(163),
                            -Sqrt(2));
    }
    {
      std::function<Dimensionless(Vector<Dimensionless, World>,
                                  Vector<Dimensionless, World>)>
      vectorInnerProduct = [](Vector<Dimensionless, World> a,
                              Vector<Dimensionless, World> b) {
        return InnerProduct(a, b);
      };
      std::function<Dimensionless(Bivector<Dimensionless, World>,
                                  Bivector<Dimensionless, World>)>
      bivectorInnerProduct = [](Bivector<Dimensionless, World> a,
                                Bivector<Dimensionless, World> b) {
        return InnerProduct(a, b);
      };
      std::function<Dimensionless(Trivector<Dimensionless, World>,
                                  Trivector<Dimensionless, World>)>
      trivectorInnerProduct = [](Trivector<Dimensionless, World> a,
                                 Trivector<Dimensionless, World> b) {
        return InnerProduct(a, b);
      };
      TestInnerProductSpace(vectorInnerProduct,
                            Vector<Dimensionless,
                                   World>(nullDisplacement / Metre),
                            Vector<Dimensionless, World>(u / Metre),
                            Vector<Dimensionless, World>(v / Metre),
                            Vector<Dimensionless, World>(w / Metre),
                            Vector<Dimensionless, World>(a / Metre),
                            Dimensionless(0), Dimensionless(1), Sqrt(163),
                            -Sqrt(2));
      TestInnerProductSpace(bivectorInnerProduct,
                            Bivector<Dimensionless,
                                     World>(nullDisplacement / Metre),
                            Bivector<Dimensionless, World>(u / Metre),
                            Bivector<Dimensionless, World>(v / Metre),
                            Bivector<Dimensionless, World>(w / Metre),
                            Bivector<Dimensionless, World>(a / Metre),
                            Dimensionless(0), Dimensionless(1), Sqrt(163),
                            -Sqrt(2));
      TestInnerProductSpace(trivectorInnerProduct,
                            Trivector<Dimensionless,
                                      World>(nullDisplacement.x / Metre),
                            Trivector<Dimensionless, World>(u.y / Metre),
                            Trivector<Dimensionless, World>(v.z / Metre),
                            Trivector<Dimensionless, World>(w.x / Metre),
                            Trivector<Dimensionless, World>(a.y / Metre),
                            Dimensionless(0), Dimensionless(1), Sqrt(163),
                            -Sqrt(2));
    }
  }
  TEST_METHOD(GrassmannAlgebra) {
    R3Element<Dimensionless> u(3, -42, 0);
    R3Element<Dimensionless> v(-π, -e, -1);
    R3Element<Dimensionless> w(2, 2, 2);
    R3Element<Dimensionless> a(1.2, 2.3, 3.4);
    std::function<Bivector<Dimensionless,
                           World>(Vector<Dimensionless, World>,
                                  Vector<Dimensionless, World>)> vectorWedge =
      [](Vector<Dimensionless, World> a, Vector<Dimensionless, World> b) {
        return Wedge(a, b);
      };
    TestAlternatingBilinearMap(vectorWedge, Vector<Dimensionless, World>(u),
                               Vector<Dimensionless, World>(u),
                               Vector<Dimensionless, World>(u),
                               Vector<Dimensionless, World>(u),
                               Dimensionless(6 * 9));
  }
};
}  // namespace GeometryTests
}  // namespace Principia
<commit_msg>Not sure that's a good idea, but then it's easy to get confused between all these '}'s.<commit_after>#include "stdafx.hpp"

#include <functional>

#include "CppUnitTest.h"
#include "..\TestUtilities\TestUtilities.hpp"
#include "..\TestUtilities\QuantityComparisons.hpp"
#include "..\TestUtilities\GeometryComparisons.hpp"
#include "..\TestUtilities\Algebra.hpp"

#include "..\Quantities\Dimensionless.hpp"
#include "..\Quantities\Quantities.hpp"
#include "..\Quantities\SI.hpp"
#include "..\Quantities\Constants.hpp"
#include "..\Quantities\UK.hpp"
#include "..\Quantities\BIPM.hpp"
#include "..\Quantities\Astronomy.hpp"
#include "..\Geometry\R3Element.hpp"
#include "..\Geometry\Grassmann.hpp"
#include "..\Quantities\ElementaryFunctions.hpp"

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace Principia {
namespace GeometryTests
{
using namespace Geometry;
using namespace Quantities;
using namespace SI;
using namespace UK;
using namespace BIPM;
using namespace Astronomy;
using namespace Constants;
using namespace TestUtilities;

TEST_CLASS(GeometryTests)
{
 public:
  struct World;
  TEST_METHOD(Dumb3Vector) {
    R3Element<Speed> nullVector(0 * Metre / Second,
                                0 * Metre / Second,
                                0 * Metre / Second);
    R3Element<Speed> u(1 * Metre / Second,
                       120 * Kilo(Metre) / Hour,
                       -SpeedOfLight);
    R3Element<Speed> v(-20 * Knot,
                       2 * π * AstronomicalUnit / JulianYear,
                       1 * Admiralty::NauticalMile / Hour);
    R3Element<Speed> w(-1 * Mile / Hour, -2 * Foot / Second, -3 * Knot);
    R3Element<Speed> a(88 * Mile / Hour, 300 * Metre / Second, 46 * Knot);
    AssertEqual((e * Dimensionless(42)) * v, e * (Dimensionless(42) * v));
    TestVectorSpace<R3Element<Speed>,
                    Dimensionless>(nullVector, u, v, w, Dimensionless(0),
                                   Dimensionless(1), e, Dimensionless(42));
    TestAlternatingBilinearMap(Cross<Speed, Speed>, u,
                               v, w, a, Dimensionless(42));
    TestSymmetricPositiveDefiniteBilinearMap(Dot<Speed, Speed>,
                                             u, v, w, a, Dimensionless(42));
  }  // TEST_METHOD Dumb3Vector

  TEST_METHOD(SpecialOrthogonalLieAlgebra) {
    R3Element<Dimensionless> u(3, -42, 0);
    R3Element<Dimensionless> v(-π, -e, -1);
    R3Element<Dimensionless> w(2, 2, 2);
    R3Element<Dimensionless> a(1.2, 2.3, 3.4);
    TestLieBracket(Commutator<Dimensionless, Dimensionless, World>,
                   Bivector<Dimensionless, World>(u),
                   Bivector<Dimensionless, World>(v),
                   Bivector<Dimensionless, World>(w),
                   Bivector<Dimensionless, World>(a), Dimensionless(0.42));
  }  // TEST_METHOD SpecialOrthogonalLieAlgebra

  TEST_METHOD(VectorSpaces) {
    R3Element<Length> nullDisplacement(0 * Metre, 0 * Metre, 0 * Metre);
    R3Element<Length> u(3 * Metre, -42 * Metre, 0 * Metre);
    R3Element<Length> v(-π * Metre, -e * Metre, -1 * Metre);
    R3Element<Length> w(2 * Metre, 2 * Metre, 2 * Metre);
    R3Element<Length> a(1 * Inch, 2 * Foot, 3 * Admiralty::Fathom);
    {
      std::function<Area(Vector<Length, World>,
                         Vector<Length, World>)> vectorInnerProduct =
      [](Vector<Length, World> a, Vector<Length, World> b) {
        return InnerProduct(a, b);
      };
      std::function<Area(Bivector<Length, World>,
                         Bivector<Length, World>)> bivectorInnerProduct =
      [](Bivector<Length, World> a, Bivector<Length, World> b) {
        return InnerProduct(a, b);
      };
      std::function<Area(Trivector<Length, World>,
                         Trivector<Length, World>)> trivectorInnerProduct =
      [](Trivector<Length, World> a, Trivector<Length, World> b) {
        return InnerProduct(a, b);
      };
      TestInnerProductSpace(vectorInnerProduct,
                            Vector<Length, World>(nullDisplacement),
                            Vector<Length, World>(u), Vector<Length, World>(v),
                            Vector<Length, World>(w), Vector<Length, World>(a),
                            Dimensionless(0), Dimensionless(1), Sqrt(163),
                            -Sqrt(2));
      TestInnerProductSpace(bivectorInnerProduct,
                            Bivector<Length, World>(nullDisplacement),
                            Bivector<Length, World>(u),
                            Bivector<Length, World>(v),
                            Bivector<Length, World>(w),
                            Bivector<Length, World>(a),
                            Dimensionless(0), Dimensionless(1), Sqrt(163),
                            -Sqrt(2));
      TestInnerProductSpace(trivectorInnerProduct,
                            Trivector<Length, World>(nullDisplacement.x),
                            Trivector<Length, World>(u.y),
                            Trivector<Length, World>(v.z),
                            Trivector<Length, World>(w.x),
                            Trivector<Length, World>(a.y),
                            Dimensionless(0), Dimensionless(1), Sqrt(163),
                            -Sqrt(2));
    }
    {
      std::function<Dimensionless(Vector<Dimensionless, World>,
                                  Vector<Dimensionless, World>)>
      vectorInnerProduct = [](Vector<Dimensionless, World> a,
                              Vector<Dimensionless, World> b) {
        return InnerProduct(a, b);
      };
      std::function<Dimensionless(Bivector<Dimensionless, World>,
                                  Bivector<Dimensionless, World>)>
      bivectorInnerProduct = [](Bivector<Dimensionless, World> a,
                                Bivector<Dimensionless, World> b) {
        return InnerProduct(a, b);
      };
      std::function<Dimensionless(Trivector<Dimensionless, World>,
                                  Trivector<Dimensionless, World>)>
      trivectorInnerProduct = [](Trivector<Dimensionless, World> a,
                                 Trivector<Dimensionless, World> b) {
        return InnerProduct(a, b);
      };
      TestInnerProductSpace(vectorInnerProduct,
                            Vector<Dimensionless,
                                   World>(nullDisplacement / Metre),
                            Vector<Dimensionless, World>(u / Metre),
                            Vector<Dimensionless, World>(v / Metre),
                            Vector<Dimensionless, World>(w / Metre),
                            Vector<Dimensionless, World>(a / Metre),
                            Dimensionless(0), Dimensionless(1), Sqrt(163),
                            -Sqrt(2));
      TestInnerProductSpace(bivectorInnerProduct,
                            Bivector<Dimensionless,
                                     World>(nullDisplacement / Metre),
                            Bivector<Dimensionless, World>(u / Metre),
                            Bivector<Dimensionless, World>(v / Metre),
                            Bivector<Dimensionless, World>(w / Metre),
                            Bivector<Dimensionless, World>(a / Metre),
                            Dimensionless(0), Dimensionless(1), Sqrt(163),
                            -Sqrt(2));
      TestInnerProductSpace(trivectorInnerProduct,
                            Trivector<Dimensionless,
                                      World>(nullDisplacement.x / Metre),
                            Trivector<Dimensionless, World>(u.y / Metre),
                            Trivector<Dimensionless, World>(v.z / Metre),
                            Trivector<Dimensionless, World>(w.x / Metre),
                            Trivector<Dimensionless, World>(a.y / Metre),
                            Dimensionless(0), Dimensionless(1), Sqrt(163),
                            -Sqrt(2));
    }
  }  // TEST_METHOD VectorSpaces

  TEST_METHOD(GrassmannAlgebra) {
    R3Element<Dimensionless> u(3, -42, 0);
    R3Element<Dimensionless> v(-π, -e, -1);
    R3Element<Dimensionless> w(2, 2, 2);
    R3Element<Dimensionless> a(1.2, 2.3, 3.4);
    std::function<Bivector<Dimensionless,
                           World>(Vector<Dimensionless, World>,
                                  Vector<Dimensionless, World>)> vectorWedge =
      [](Vector<Dimensionless, World> a, Vector<Dimensionless, World> b) {
        return Wedge(a, b);
      };
    TestAlternatingBilinearMap(vectorWedge, Vector<Dimensionless, World>(u),
                               Vector<Dimensionless, World>(u),
                               Vector<Dimensionless, World>(u),
                               Vector<Dimensionless, World>(u),
                               Dimensionless(6 * 9));
  }  // TEST_METHOD GrassmannAlgebra

};  // TEST_CLASS GeometryTests
}  // namespace GeometryTests
}  // namespace Principia
<|endoftext|>


<commit_before>/**
 * \file dcs/testbed/application.hpp
 *
 * \brief Generic application.
 *
 * \author Marco Guazzone (marco.guazzone@gmail.com)
 *
 *

 *
 * Copyright 2012 Marco Guazzone (marco.guazzone@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef DCS_TESTBED_APPLICATION_HPP
#define DCS_TESTBED_APPLICATION_HPP

#include <cstddef>
#include <dcs/assert.hpp>
#include <dcs/exception.hpp>
#include <dcs/testbed/application_performance_category.hpp>
#include <dcs/testbed/base_application.hpp>
#include <dcs/testbed/base_virtual_machine.hpp>
#include <map>
#include <stdexcept>
#include <vector>

namespace dcs { namespace testbed {

template <typename TraitsT>
class application: public base_application<TraitsT>
{
	private: typedef base_application<TraitsT> base_type;
	public: typedef typename base_type::traits_type traits_type;
	public: typedef typename base_type::vm_pointer vm_pointer;
	public: typedef typename base_type::sensor_pointer sensor_pointer;
	public: typedef typename base_type::slo_checker_type slo_checker_type;
	public: typedef typename base_type::real_type real_type;
//	private: typedef typename base_type::vm_type::identifier_type vm _identifier_type;
//	private: typedef ::std::map<vm_identifier_type,vm_pointer> vm_container;
	private: typedef ::std::vector<vm_pointer> vm_container;
	private: typedef ::std::map<application_performance_category,sensor_pointer> sensor_map;
	private: typedef ::std::map<application_performance_category,slo_checker_type> slo_checker_map;

	public: application()
	{
	}

	public: template <typename IterT>
			application(IterT vm_first, IterT vm_last)
	: vms_(vm_first,vm_last)
	{
//		while (vm_first != vm_last)
//		{
//			vms_[*(vm_first)->id()] = *vm_first;
//			++vm_first;
//		}
	}

	private: ::std::size_t do_num_vms() const
	{
		return vms_.size();
	}

	private: ::std::vector<vm_pointer> do_vms() const
	{
//		::std::vector<vm_pointer> vms(vms_.size());
//
//		::std::size_t i(0);
//		typename vm_container::const_iterator end_it(vms_.end());
//		for (typename vm_container::const_iterator it = vms_.begin();
//			 it != end_it;
//			 ++it)
//		{
//			vms[i] = *it;
//			++i;
//		}
//
//		return vms;
		return vms_;
	}

//	private: vm_pointer do_vm(vm_identifier_type id) const
//	{
//		DCS_ASSERT(vms_.count(id) > 0,
//				   DCS_EXCEPTION_THROW(::std::invalid_argument,
//									   "Invalid VM identifier"));
//
//		return vms_.at(id);
//	}

	private: void do_register_sensor(application_performance_category cat, sensor_pointer const& p_sens)
	{
		DCS_ASSERT(p_sens,
				   DCS_EXCEPTION_THROW(::std::invalid_argument,
									   "Invalid sensor"));

		sensors_[cat] = p_sens;
	}

	private: void do_deregister_sensor(application_performance_category cat)
	{
		DCS_ASSERT(sensors_.count(cat) > 0,
				   DCS_EXCEPTION_THROW(::std::invalid_argument,
									   "Invalid category: sensor not found"));

		sensors_.erase(cat);
	}

	private: sensor_pointer do_sensor(application_performance_category cat)
	{
		DCS_ASSERT(sensors_.count(cat) > 0,
				   DCS_EXCEPTION_THROW(::std::invalid_argument,
									   "Invalid category: sensor not found"));

		return sensors_.at(cat);
	}

	private: sensor_pointer do_sensor(application_performance_category cat) const
	{
		DCS_ASSERT(sensors_.count(cat) > 0,
				   DCS_EXCEPTION_THROW(::std::invalid_argument,
									   "Invalid category: sensor not found"));

		return sensors_.at(cat);
	}

	private: void do_slo(application_performance_category cat, slo_checker_type const& checker)
	{
		slo_map_[cat] = checker;
	}

	private: bool do_slo(application_performance_category cat, real_type val) const
	{
		DCS_ASSERT(slo_map_.count(cat) > 0,
				   DCS_EXCEPTION_THROW(::std::invalid_argument,
									   "Invalid category: SLO checker not found"));

		return slo_map_.at(cat)(val);
	}

	private: vm_container vms_;
	private: sensor_map sensors_;
	private: slo_checker_map slo_map_;
}; // application

}} // Namespace dcs::testbed

#endif // DCS_TESTBED_APPLICATION_HPP
<commit_msg>Improved inline doc<commit_after>/**
 * \file dcs/testbed/application.hpp
 *
 * \brief Generic application.
 *
 * \author Marco Guazzone (marco.guazzone@gmail.com)
 *
 *

 *
 * Copyright 2012 Marco Guazzone (marco.guazzone@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef DCS_TESTBED_APPLICATION_HPP
#define DCS_TESTBED_APPLICATION_HPP

#include <cstddef>
#include <dcs/assert.hpp>
#include <dcs/exception.hpp>
#include <dcs/testbed/application_performance_category.hpp>
#include <dcs/testbed/base_application.hpp>
#include <dcs/testbed/base_virtual_machine.hpp>
#include <map>
#include <stdexcept>
#include <vector>

namespace dcs { namespace testbed {

/**
 * \brief Generic application.
 *
 * \tparam TraitsT Traits type.
 *
 * \author Marco Guazzone (marco.guazzone@gmail.com)
 */
template <typename TraitsT>
class application: public base_application<TraitsT>
{
	private: typedef base_application<TraitsT> base_type;
	public: typedef typename base_type::traits_type traits_type;
	public: typedef typename base_type::vm_pointer vm_pointer;
	public: typedef typename base_type::sensor_pointer sensor_pointer;
	public: typedef typename base_type::slo_checker_type slo_checker_type;
	public: typedef typename base_type::real_type real_type;
//	private: typedef typename base_type::vm_type::identifier_type vm _identifier_type;
//	private: typedef ::std::map<vm_identifier_type,vm_pointer> vm_container;
	private: typedef ::std::vector<vm_pointer> vm_container;
	private: typedef ::std::map<application_performance_category,sensor_pointer> sensor_map;
	private: typedef ::std::map<application_performance_category,slo_checker_type> slo_checker_map;

	public: application()
	{
		// Empty
	}

	public: template <typename IterT>
			application(IterT vm_first, IterT vm_last)
	: vms_(vm_first,vm_last)
	{
//		while (vm_first != vm_last)
//		{
//			vms_[*(vm_first)->id()] = *vm_first;
//			++vm_first;
//		}
	}

	private: ::std::size_t do_num_vms() const
	{
		return vms_.size();
	}

	private: ::std::vector<vm_pointer> do_vms() const
	{
//		::std::vector<vm_pointer> vms(vms_.size());
//
//		::std::size_t i(0);
//		typename vm_container::const_iterator end_it(vms_.end());
//		for (typename vm_container::const_iterator it = vms_.begin();
//			 it != end_it;
//			 ++it)
//		{
//			vms[i] = *it;
//			++i;
//		}
//
//		return vms;
		return vms_;
	}

//	private: vm_pointer do_vm(vm_identifier_type id) const
//	{
//		DCS_ASSERT(vms_.count(id) > 0,
//				   DCS_EXCEPTION_THROW(::std::invalid_argument,
//									   "Invalid VM identifier"));
//
//		return vms_.at(id);
//	}

	private: void do_register_sensor(application_performance_category cat, sensor_pointer const& p_sens)
	{
		DCS_ASSERT(p_sens,
				   DCS_EXCEPTION_THROW(::std::invalid_argument,
									   "Invalid sensor"));

		sensors_[cat] = p_sens;
	}

	private: void do_deregister_sensor(application_performance_category cat)
	{
		DCS_ASSERT(sensors_.count(cat) > 0,
				   DCS_EXCEPTION_THROW(::std::invalid_argument,
									   "Invalid category: sensor not found"));

		sensors_.erase(cat);
	}

	private: sensor_pointer do_sensor(application_performance_category cat)
	{
		DCS_ASSERT(sensors_.count(cat) > 0,
				   DCS_EXCEPTION_THROW(::std::invalid_argument,
									   "Invalid category: sensor not found"));

		return sensors_.at(cat);
	}

	private: sensor_pointer do_sensor(application_performance_category cat) const
	{
		DCS_ASSERT(sensors_.count(cat) > 0,
				   DCS_EXCEPTION_THROW(::std::invalid_argument,
									   "Invalid category: sensor not found"));

		return sensors_.at(cat);
	}

	private: void do_slo(application_performance_category cat, slo_checker_type const& checker)
	{
		slo_map_[cat] = checker;
	}

	private: bool do_slo(application_performance_category cat, real_type val) const
	{
		DCS_ASSERT(slo_map_.count(cat) > 0,
				   DCS_EXCEPTION_THROW(::std::invalid_argument,
									   "Invalid category: SLO checker not found"));

		return slo_map_.at(cat)(val);
	}

	private: vm_container vms_;
	private: sensor_map sensors_;
	private: slo_checker_map slo_map_;
}; // application

}} // Namespace dcs::testbed

#endif // DCS_TESTBED_APPLICATION_HPP
<|endoftext|>


<commit_before>#include "stdafx.h"
#include <windows.h>

typedef LONG       KPRIORITY;
typedef struct _CLIENT_ID {
	DWORD          UniqueProcess;
	DWORD          UniqueThread;
} CLIENT_ID;

typedef struct _UNICODE_STRING {
	USHORT         Length;
	USHORT         MaximumLength;
	PWSTR          Buffer;
} UNICODE_STRING;

//from http://boinc.berkeley.edu/android-boinc/boinc/lib/diagnostics_win.h
typedef struct _VM_COUNTERS {
#ifdef _WIN64
	// the following was inferred by painful reverse engineering
	SIZE_T		   PeakVirtualSize;	// not actually
	SIZE_T         PageFaultCount;
	SIZE_T         PeakWorkingSetSize;
	SIZE_T         WorkingSetSize;
	SIZE_T         QuotaPeakPagedPoolUsage;
	SIZE_T         QuotaPagedPoolUsage;
	SIZE_T         QuotaPeakNonPagedPoolUsage;
	SIZE_T         QuotaNonPagedPoolUsage;
	SIZE_T         PagefileUsage;
	SIZE_T         PeakPagefileUsage;
	SIZE_T         VirtualSize;		// not actually
#else
	SIZE_T         PeakVirtualSize;
	SIZE_T         VirtualSize;
	ULONG          PageFaultCount;
	SIZE_T         PeakWorkingSetSize;
	SIZE_T         WorkingSetSize;
	SIZE_T         QuotaPeakPagedPoolUsage;
	SIZE_T         QuotaPagedPoolUsage;
	SIZE_T         QuotaPeakNonPagedPoolUsage;
	SIZE_T         QuotaNonPagedPoolUsage;
	SIZE_T         PagefileUsage;
	SIZE_T         PeakPagefileUsage;
#endif
} VM_COUNTERS;

typedef enum _KWAIT_REASON
{
	Executive = 0,
	FreePage = 1,
	PageIn = 2,
	PoolAllocation = 3,
	DelayExecution = 4,
	Suspended = 5,
	UserRequest = 6,
	WrExecutive = 7,
	WrFreePage = 8,
	WrPageIn = 9,
	WrPoolAllocation = 10,
	WrDelayExecution = 11,
	WrSuspended = 12,
	WrUserRequest = 13,
	WrEventPair = 14,
	WrQueue = 15,
	WrLpcReceive = 16,
	WrLpcReply = 17,
	WrVirtualMemory = 18,
	WrPageOut = 19,
	WrRendezvous = 20,
	Spare2 = 21,
	Spare3 = 22,
	Spare4 = 23,
	Spare5 = 24,
	WrCalloutStack = 25,
	WrKernel = 26,
	WrResource = 27,
	WrPushLock = 28,
	WrMutex = 29,
	WrQuantumEnd = 30,
	WrDispatchInt = 31,
	WrPreempted = 32,
	WrYieldExecution = 33,
	WrFastMutex = 34,
	WrGuardedMutex = 35,
	WrRundown = 36,
	MaximumWaitReason = 37
} KWAIT_REASON;

typedef struct _SYSTEM_THREAD_INFORMATION {
	LARGE_INTEGER KernelTime;
	LARGE_INTEGER UserTime;
	LARGE_INTEGER CreateTime;
	ULONG WaitTime;
	PVOID StartAddress;
	CLIENT_ID ClientId;
	KPRIORITY Priority;
	LONG BasePriority;
	ULONG ContextSwitchCount;
	ULONG ThreadState;
	KWAIT_REASON WaitReason;
#ifdef _WIN64
	ULONG Reserved[4];
#endif
}SYSTEM_THREAD_INFORMATION, *PSYSTEM_THREAD_INFORMATION;

typedef struct _SYSTEM_EXTENDED_THREAD_INFORMATION
{
	SYSTEM_THREAD_INFORMATION ThreadInfo;
	PVOID StackBase;
	PVOID StackLimit;
	PVOID Win32StartAddress;
	PVOID TebAddress; /* This is only filled in on Vista and above */
	ULONG Reserved1;
	ULONG Reserved2;
	ULONG Reserved3;
} SYSTEM_EXTENDED_THREAD_INFORMATION, *PSYSTEM_EXTENDED_THREAD_INFORMATION;
typedef struct _SYSTEM_EXTENDED_PROCESS_INFORMATION
{
	ULONG NextEntryOffset;
	ULONG NumberOfThreads;
	LARGE_INTEGER SpareLi1;
	LARGE_INTEGER SpareLi2;
	LARGE_INTEGER SpareLi3;
	LARGE_INTEGER CreateTime;
	LARGE_INTEGER UserTime;
	LARGE_INTEGER KernelTime;
	UNICODE_STRING ImageName;
	KPRIORITY BasePriority;
	ULONG ProcessId;
	ULONG InheritedFromUniqueProcessId;
	ULONG HandleCount;
	ULONG SessionId;
	PVOID PageDirectoryBase;
	VM_COUNTERS VirtualMemoryCounters;
	SIZE_T PrivatePageCount;
	IO_COUNTERS IoCounters;
	SYSTEM_EXTENDED_THREAD_INFORMATION Threads[1];
} SYSTEM_EXTENDED_PROCESS_INFORMATION, *PSYSTEM_EXTENDED_PROCESS_INFORMATION;

typedef enum _SYSTEM_INFORMATION_CLASS {
	SystemExtendedProcessInformation = 57
} SYSTEM_INFORMATION_CLASS;

typedef NTSTATUS(WINAPI *PNtQuerySystemInformation)(
	__in SYSTEM_INFORMATION_CLASS SystemInformationClass,
	__inout PVOID SystemInformation,
	__in ULONG SystemInformationLength,
	__out_opt PULONG ReturnLength
	);

int main()
{
	HMODULE ntdll = GetModuleHandle(TEXT("ntdll"));
	PNtQuerySystemInformation query = (PNtQuerySystemInformation)GetProcAddress(ntdll, "NtQuerySystemInformation");
	if (query == NULL) {
		printf("GetProcAddress() failed.\n");
		return 1;
	}
	ULONG len = 2000;
	NTSTATUS status = NULL;
	PSYSTEM_EXTENDED_PROCESS_INFORMATION pProcessInfo = NULL;
	do {
		len *= 2;
		pProcessInfo = (PSYSTEM_EXTENDED_PROCESS_INFORMATION)GlobalAlloc(GMEM_ZEROINIT, len);
		status = query(SystemExtendedProcessInformation, pProcessInfo, len, &len);
	} while (status == (NTSTATUS)0xc0000004);
	if (status != (NTSTATUS)0x0) {
		printf("NtQuerySystemInformation failed with error code 0x%X\n", status);
		return 1;
	}

	while (pProcessInfo->NextEntryOffset != NULL) {
		for (unsigned int i = 0; i < pProcessInfo->NumberOfThreads; i++) {
			PVOID stackBase = pProcessInfo->Threads[i].StackBase;
			PVOID stackLimit = pProcessInfo->Threads[i].StackLimit;
#ifdef _WIN64
			printf("Stack base 0x%llx\t", stackBase);
			printf("Stack limit 0x%llx\r\n", stackLimit);
#else
			printf("Stack base 0x%X\t", stackBase);
			printf("Stack limit 0x%X\r\n", stackLimit);
#endif
		}
		pProcessInfo = (PSYSTEM_EXTENDED_PROCESS_INFORMATION)((ULONG_PTR)pProcessInfo + pProcessInfo->NextEntryOffset);
	}
	return 0;
}

<commit_msg>remove unneeded ifdef struct change<commit_after>#include "stdafx.h"
#include <windows.h>

typedef LONG       KPRIORITY;
typedef struct _CLIENT_ID {
	DWORD          UniqueProcess;
	DWORD          UniqueThread;
} CLIENT_ID;

typedef struct _UNICODE_STRING {
	USHORT         Length;
	USHORT         MaximumLength;
	PWSTR          Buffer;
} UNICODE_STRING;

//from http://boinc.berkeley.edu/android-boinc/boinc/lib/diagnostics_win.h
typedef struct _VM_COUNTERS {
	// the following was inferred by painful reverse engineering
	SIZE_T		   PeakVirtualSize;	// not actually
	SIZE_T         PageFaultCount;
	SIZE_T         PeakWorkingSetSize;
	SIZE_T         WorkingSetSize;
	SIZE_T         QuotaPeakPagedPoolUsage;
	SIZE_T         QuotaPagedPoolUsage;
	SIZE_T         QuotaPeakNonPagedPoolUsage;
	SIZE_T         QuotaNonPagedPoolUsage;
	SIZE_T         PagefileUsage;
	SIZE_T         PeakPagefileUsage;
	SIZE_T         VirtualSize;		// not actually
} VM_COUNTERS;

typedef enum _KWAIT_REASON
{
	Executive = 0,
	FreePage = 1,
	PageIn = 2,
	PoolAllocation = 3,
	DelayExecution = 4,
	Suspended = 5,
	UserRequest = 6,
	WrExecutive = 7,
	WrFreePage = 8,
	WrPageIn = 9,
	WrPoolAllocation = 10,
	WrDelayExecution = 11,
	WrSuspended = 12,
	WrUserRequest = 13,
	WrEventPair = 14,
	WrQueue = 15,
	WrLpcReceive = 16,
	WrLpcReply = 17,
	WrVirtualMemory = 18,
	WrPageOut = 19,
	WrRendezvous = 20,
	Spare2 = 21,
	Spare3 = 22,
	Spare4 = 23,
	Spare5 = 24,
	WrCalloutStack = 25,
	WrKernel = 26,
	WrResource = 27,
	WrPushLock = 28,
	WrMutex = 29,
	WrQuantumEnd = 30,
	WrDispatchInt = 31,
	WrPreempted = 32,
	WrYieldExecution = 33,
	WrFastMutex = 34,
	WrGuardedMutex = 35,
	WrRundown = 36,
	MaximumWaitReason = 37
} KWAIT_REASON;

typedef struct _SYSTEM_THREAD_INFORMATION {
	LARGE_INTEGER KernelTime;
	LARGE_INTEGER UserTime;
	LARGE_INTEGER CreateTime;
	ULONG WaitTime;
	PVOID StartAddress;
	CLIENT_ID ClientId;
	KPRIORITY Priority;
	LONG BasePriority;
	ULONG ContextSwitchCount;
	ULONG ThreadState;
	KWAIT_REASON WaitReason;
#ifdef _WIN64
	ULONG Reserved[4];
#endif
}SYSTEM_THREAD_INFORMATION, *PSYSTEM_THREAD_INFORMATION;

typedef struct _SYSTEM_EXTENDED_THREAD_INFORMATION
{
	SYSTEM_THREAD_INFORMATION ThreadInfo;
	PVOID StackBase;
	PVOID StackLimit;
	PVOID Win32StartAddress;
	PVOID TebAddress; /* This is only filled in on Vista and above */
	ULONG Reserved1;
	ULONG Reserved2;
	ULONG Reserved3;
} SYSTEM_EXTENDED_THREAD_INFORMATION, *PSYSTEM_EXTENDED_THREAD_INFORMATION;
typedef struct _SYSTEM_EXTENDED_PROCESS_INFORMATION
{
	ULONG NextEntryOffset;
	ULONG NumberOfThreads;
	LARGE_INTEGER SpareLi1;
	LARGE_INTEGER SpareLi2;
	LARGE_INTEGER SpareLi3;
	LARGE_INTEGER CreateTime;
	LARGE_INTEGER UserTime;
	LARGE_INTEGER KernelTime;
	UNICODE_STRING ImageName;
	KPRIORITY BasePriority;
	ULONG ProcessId;
	ULONG InheritedFromUniqueProcessId;
	ULONG HandleCount;
	ULONG SessionId;
	PVOID PageDirectoryBase;
	VM_COUNTERS VirtualMemoryCounters;
	SIZE_T PrivatePageCount;
	IO_COUNTERS IoCounters;
	SYSTEM_EXTENDED_THREAD_INFORMATION Threads[1];
} SYSTEM_EXTENDED_PROCESS_INFORMATION, *PSYSTEM_EXTENDED_PROCESS_INFORMATION;

typedef enum _SYSTEM_INFORMATION_CLASS {
	SystemExtendedProcessInformation = 57
} SYSTEM_INFORMATION_CLASS;

typedef NTSTATUS(WINAPI *PNtQuerySystemInformation)(
	__in SYSTEM_INFORMATION_CLASS SystemInformationClass,
	__inout PVOID SystemInformation,
	__in ULONG SystemInformationLength,
	__out_opt PULONG ReturnLength
	);

int main()
{
	HMODULE ntdll = GetModuleHandle(TEXT("ntdll"));
	PNtQuerySystemInformation query = (PNtQuerySystemInformation)GetProcAddress(ntdll, "NtQuerySystemInformation");
	if (query == NULL) {
		printf("GetProcAddress() failed.\n");
		return 1;
	}
	ULONG len = 2000;
	NTSTATUS status = NULL;
	PSYSTEM_EXTENDED_PROCESS_INFORMATION pProcessInfo = NULL;
	do {
		len *= 2;
		pProcessInfo = (PSYSTEM_EXTENDED_PROCESS_INFORMATION)GlobalAlloc(GMEM_ZEROINIT, len);
		status = query(SystemExtendedProcessInformation, pProcessInfo, len, &len);
	} while (status == (NTSTATUS)0xc0000004);
	if (status != (NTSTATUS)0x0) {
		printf("NtQuerySystemInformation failed with error code 0x%X\n", status);
		return 1;
	}

	while (pProcessInfo->NextEntryOffset != NULL) {
		for (unsigned int i = 0; i < pProcessInfo->NumberOfThreads; i++) {
			PVOID stackBase = pProcessInfo->Threads[i].StackBase;
			PVOID stackLimit = pProcessInfo->Threads[i].StackLimit;
#ifdef _WIN64
			printf("Stack base 0x%llx\t", stackBase);
			printf("Stack limit 0x%llx\r\n", stackLimit);
#else
			printf("Stack base 0x%X\t", stackBase);
			printf("Stack limit 0x%X\r\n", stackLimit);
#endif
		}
		pProcessInfo = (PSYSTEM_EXTENDED_PROCESS_INFORMATION)((ULONG_PTR)pProcessInfo + pProcessInfo->NextEntryOffset);
	}
	return 0;
}

<|endoftext|>


<commit_before>/**************************************************************************
** This file is part of LiteIDE
**
** Copyright (c) 2011-2017 LiteIDE Team. All rights reserved.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
** Lesser General Public License for more details.
**
** In addition, as a special exception,  that plugins developed for LiteIDE,
** are allowed to remain closed sourced and can be distributed under any license .
** These rights are included in the file LGPL_EXCEPTION.txt in this package.
**
**************************************************************************/
// Module: goremovetagsdialog.cpp
// Creator: visualfc <visualfc@gmail.com>

#include "goremovetagsdialog.h"
#include "ui_goremovetagsdialog.h"
//lite_memory_check_begin
#if defined(WIN32) && defined(_MSC_VER) &&  defined(_DEBUG)
     #define _CRTDBG_MAP_ALLOC
     #include <stdlib.h>
     #include <crtdbg.h>
     #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )
     #define new DEBUG_NEW
#endif
//lite_memory_check_end

GoRemoveTagsDialog::GoRemoveTagsDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::GoRemoveTagsDialog)
{
    ui->setupUi(this);
    connect(ui->clearAllTagsRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments()));
    connect(ui->clearAllOptionsRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments()));

    connect(ui->removeJsonTagRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments()));
    connect(ui->removeXmlOptionRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments()));
    connect(ui->removeCustomTagRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments()));

    connect(ui->removeJsonOptionRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments()));
    connect(ui->removeXmlOptionRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments()));
    connect(ui->removeCustomOptionRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments()));

    connect(ui->customTaglineEdit,SIGNAL(textChanged(QString)),this,SLOT(updateArguments()));
    connect(ui->jsonOptionLineEdit,SIGNAL(textChanged(QString)),this,SLOT(updateArguments()));
    connect(ui->xmlOptionLineEdit,SIGNAL(textChanged(QString)),this,SLOT(updateArguments()));
    connect(ui->customOptionLineEdit,SIGNAL(textChanged(QString)),this,SLOT(updateArguments()));
}

GoRemoveTagsDialog::~GoRemoveTagsDialog()
{
    delete ui;
}

void GoRemoveTagsDialog::setInfo(const QString &info)
{
    ui->infoLabel->setText(info);
}

QString GoRemoveTagsDialog::arguments() const
{
    return ui->argumentsEdit->toPlainText().trimmed();
}

static QString removeHead(const QString &text, const QString &head)
{
    if (text.startsWith(head)) {
        return text.mid(head.length());
    }
    return text;
}

void GoRemoveTagsDialog::updateArguments()
{
    QString args;
    if (ui->clearAllTagsRadioButton->isChecked()) {
        args = "-clear-tags";
    } else if (ui->clearAllOptionsRadioButton->isChecked()) {
        args = "-clear-options";
    } else if (ui->removeJsonTagRadioButton->isChecked()) {
        args = "-remove-tags json";
    } else if (ui->removeXmlTagRadioButton->isChecked()) {
        args = "-remove-tags xml";
    } else if (ui->removeCustomTagRadioButton->isChecked()) {
        QString tag = ui->customTaglineEdit->text().trimmed();
        if (!tag.isEmpty()) {
            args = "-remove-tags "+tag;
        }
    } else if (ui->removeJsonOptionRadioButton->isChecked()) {
        QStringList optList = ui->jsonOptionLineEdit->text().trimmed().split(",",QString::SkipEmptyParts);
        QStringList options;
        foreach (QString opt, optList) {
            options << "json="+opt;
        }
        if (!options.isEmpty()) {
            args = "-remove-options "+options.join(",");
        }
    } else if (ui->removeXmlOptionRadioButton->isChecked()) {
        QStringList optList = ui->xmlOptionLineEdit->text().trimmed().split(",",QString::SkipEmptyParts);
        QStringList options;
        foreach (QString opt, optList) {
            options << "json="+opt;
        }
        if (!options.isEmpty()) {
            args = "-remove-options "+options.join(",");
        }
    } else if(ui->removeCustomOptionRadioButton->isChecked()) {
        QString opt = ui->customOptionLineEdit->text().trimmed();
        if (opt == ui->customOptionLineEdit->placeholderText()) {
            if (ui->customOptionLineEdit->cursorPosition() == 0) {
                opt.clear();
            }
        }
        if (opt.contains("=")) {
            args = "-remove-options "+opt;
        }
    }

    ui->argumentsEdit->setPlainText(args);
}
<commit_msg>golangedit: fix removetags xml option<commit_after>/**************************************************************************
** This file is part of LiteIDE
**
** Copyright (c) 2011-2017 LiteIDE Team. All rights reserved.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
** Lesser General Public License for more details.
**
** In addition, as a special exception,  that plugins developed for LiteIDE,
** are allowed to remain closed sourced and can be distributed under any license .
** These rights are included in the file LGPL_EXCEPTION.txt in this package.
**
**************************************************************************/
// Module: goremovetagsdialog.cpp
// Creator: visualfc <visualfc@gmail.com>

#include "goremovetagsdialog.h"
#include "ui_goremovetagsdialog.h"
//lite_memory_check_begin
#if defined(WIN32) && defined(_MSC_VER) &&  defined(_DEBUG)
     #define _CRTDBG_MAP_ALLOC
     #include <stdlib.h>
     #include <crtdbg.h>
     #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )
     #define new DEBUG_NEW
#endif
//lite_memory_check_end

GoRemoveTagsDialog::GoRemoveTagsDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::GoRemoveTagsDialog)
{
    ui->setupUi(this);
    connect(ui->clearAllTagsRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments()));
    connect(ui->clearAllOptionsRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments()));

    connect(ui->removeJsonTagRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments()));
    connect(ui->removeXmlOptionRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments()));
    connect(ui->removeCustomTagRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments()));

    connect(ui->removeJsonOptionRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments()));
    connect(ui->removeXmlOptionRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments()));
    connect(ui->removeCustomOptionRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments()));

    connect(ui->customTaglineEdit,SIGNAL(textChanged(QString)),this,SLOT(updateArguments()));
    connect(ui->jsonOptionLineEdit,SIGNAL(textChanged(QString)),this,SLOT(updateArguments()));
    connect(ui->xmlOptionLineEdit,SIGNAL(textChanged(QString)),this,SLOT(updateArguments()));
    connect(ui->customOptionLineEdit,SIGNAL(textChanged(QString)),this,SLOT(updateArguments()));
}

GoRemoveTagsDialog::~GoRemoveTagsDialog()
{
    delete ui;
}

void GoRemoveTagsDialog::setInfo(const QString &info)
{
    ui->infoLabel->setText(info);
}

QString GoRemoveTagsDialog::arguments() const
{
    return ui->argumentsEdit->toPlainText().trimmed();
}

static QString removeHead(const QString &text, const QString &head)
{
    if (text.startsWith(head)) {
        return text.mid(head.length());
    }
    return text;
}

void GoRemoveTagsDialog::updateArguments()
{
    QString args;
    if (ui->clearAllTagsRadioButton->isChecked()) {
        args = "-clear-tags";
    } else if (ui->clearAllOptionsRadioButton->isChecked()) {
        args = "-clear-options";
    } else if (ui->removeJsonTagRadioButton->isChecked()) {
        args = "-remove-tags json";
    } else if (ui->removeXmlTagRadioButton->isChecked()) {
        args = "-remove-tags xml";
    } else if (ui->removeCustomTagRadioButton->isChecked()) {
        QString tag = ui->customTaglineEdit->text().trimmed();
        if (!tag.isEmpty()) {
            args = "-remove-tags "+tag;
        }
    } else if (ui->removeJsonOptionRadioButton->isChecked()) {
        QStringList optList = ui->jsonOptionLineEdit->text().trimmed().split(",",QString::SkipEmptyParts);
        QStringList options;
        foreach (QString opt, optList) {
            options << "json="+opt;
        }
        if (!options.isEmpty()) {
            args = "-remove-options "+options.join(",");
        }
    } else if (ui->removeXmlOptionRadioButton->isChecked()) {
        QStringList optList = ui->xmlOptionLineEdit->text().trimmed().split(",",QString::SkipEmptyParts);
        QStringList options;
        foreach (QString opt, optList) {
            options << "xml="+opt;
        }
        if (!options.isEmpty()) {
            args = "-remove-options "+options.join(",");
        }
    } else if(ui->removeCustomOptionRadioButton->isChecked()) {
        QString opt = ui->customOptionLineEdit->text().trimmed();
        if (opt == ui->customOptionLineEdit->placeholderText()) {
            if (ui->customOptionLineEdit->cursorPosition() == 0) {
                opt.clear();
            }
        }
        if (opt.contains("=")) {
            args = "-remove-options "+opt;
        }
    }

    ui->argumentsEdit->setPlainText(args);
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014-2016 Kartik Kumar, Dinamica Srl (me@kartikkumar.com)
 * Distributed under the MIT License.
 * See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT
 */

#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>

#include <gsl/gsl_multiroots.h>

#ifndef ATOM_PRINT_FUNCTIONS_HPP
#define ATOM_PRINT_FUNCTIONS_HPP

namespace atom
{

//! Print Cartesian-state-to-TLE converter solver summary table header.
/*!
 * Prints header to string for table containing summary of status of non-linear solver used to
 * convert a Cartesian state to a TLE.
 *
 * @sa convertCartesianStateToTwoLineElements
 * @return String containing table header for non-linear solver status.
 */
inline std::string printCartesianToTleSolverStateTableHeader( );

//! Print summary of current state of non-linear solver for Cartesian-state-to-TLE converter.
/*!
 * Prints current state of non-linear solver used to convert a Cartesian state to a TLE, as row
 * for a summary table.
 *
 * @sa convertCartesianStateToTwoLineElements
 * @param  iteration Current iteration of solver
 * @param  solver    Pointer to GSL solver
 * @return           String containing row-data for non-linear solver status summary table
 */
inline std::string printCartesianToTleSolverState(
  const int iteration, gsl_multiroot_fsolver* solver );

//! Print Atom solver summary table header.
/*!
 * Prints header to string for table containing summary of status of non-linear solver used to
 * execute Atom solver.
 *
 * @sa executeAtomSolver
 * @return String containing table header for non-linear solver status.
 */
inline std::string printAtomSolverStateTableHeader( );

//! Print summary of current state of non-linear solver for Atom solver.
/*!
 * Prints current state of non-linear solver used to execute Atom solver, as row for a summary
 * table.
 *
 * @sa executeAtomSolver
 * @param  iteration Current iteration of solver
 * @param  solver    Pointer to GSL solver
 * @return           String containing row-data for non-linear solver status summary table
 */
inline std::string printAtomSolverState(
  const int iteration, gsl_multiroot_fsolver* solver );

//! Print data element to console.
/*!
 * Prints a specified data element to string, given a specified width and a filler character.
 * This function is auxilliary to the print-functions used to the print the state of the non-linear
 * solver.
 *
 * @sa printSolverStateTableHeader, printSolverState
 * @tparam DataType  Type for specified data element
 * @param  datum     Specified data element to print
 * @param  width     Width of datum printed to console, in terms of number of characters
 * @param  filler    Character used to fill fixed-width, [default: ' ']
 * @return           String containing printed data element
 */
template< typename DataType >
inline std::string printElement( const DataType datum, const int width, const char filler = ' ' );

//! Print Cartesian-state-to-TLE converter solver summary table header.
inline std::string printCartesianToTleSolverStateTableHeader( )
{
    std::ostringstream headerBuffer;
    headerBuffer << printElement( "#", 3, ' ' )
                 << printElement( "a", 15, ' ' )
                 << printElement( "e", 15, ' ' )
                 << printElement( "i", 15, ' ' )
                 << printElement( "AoP", 15, ' ' )
                 << printElement( "RAAN", 15, ' ' )
                 << printElement( "TA", 15, ' ' )
                 << printElement( "f1", 15, ' ' )
                 << printElement( "f2", 15, ' ' )
                 << printElement( "f3", 15, ' ' )
                 << printElement( "f4", 15, ' ' )
                 << printElement( "f5", 15, ' ' )
                 << printElement( "f6", 15, ' ' )
                 << std::endl;
    return headerBuffer.str( );
}

//! Print summary of current state of non-linear solver for Cartesian-state-to-TLE converter.
inline std::string printCartesianToTleSolverState(
  const int iteration, gsl_multiroot_fsolver* solver )
{
    std::ostringstream buffer;
    buffer << printElement( iteration, 3, ' ' )
           << printElement( gsl_vector_get( solver->x, 0 ), 15, ' ' )
           << printElement( gsl_vector_get( solver->x, 1 ), 15, ' ' )
           << printElement( gsl_vector_get( solver->x, 2 ), 15, ' ' )
           << printElement( gsl_vector_get( solver->x, 3 ), 15, ' ' )
           << printElement( gsl_vector_get( solver->x, 4 ), 15, ' ' )
           << printElement( gsl_vector_get( solver->x, 5 ), 15, ' ' )
           << printElement( gsl_vector_get( solver->f, 0 ), 15, ' ' )
           << printElement( gsl_vector_get( solver->f, 1 ), 15, ' ' )
           << printElement( gsl_vector_get( solver->f, 2 ), 15, ' ' )
           << printElement( gsl_vector_get( solver->f, 3 ), 15, ' ' )
           << printElement( gsl_vector_get( solver->f, 4 ), 15, ' ' )
           << printElement( gsl_vector_get( solver->f, 5 ), 15, ' ' )
           << std::endl;
    return buffer.str( );
}

//! Print Atom solver summary table header.
inline std::string printAtomSolverStateTableHeader( )
{
    std::ostringstream headerBuffer;
    headerBuffer << printElement( "#", 3, ' ' )
                 << printElement( "v1_x", 15, ' ' )
                 << printElement( "v1_y", 15, ' ' )
                 << printElement( "v1_z", 15, ' ' )
                 << printElement( "f1", 15, ' ' )
                 << printElement( "f2", 15, ' ' )
                 << printElement( "f3", 15, ' ' )
                 << std::endl;
    return headerBuffer.str( );
}

//! Print summary of current state of non-linear solver for Atom solver.
inline std::string printAtomSolverState(
  const int iteration, gsl_multiroot_fsolver* solver )
{
    std::ostringstream buffer;
    buffer << printElement( iteration, 3, ' ' )
           << printElement( gsl_vector_get( solver->x, 0 ), 15, ' ' )
           << printElement( gsl_vector_get( solver->x, 1 ), 15, ' ' )
           << printElement( gsl_vector_get( solver->x, 2 ), 15, ' ' )
           << printElement( gsl_vector_get( solver->f, 0 ), 15, ' ' )
           << printElement( gsl_vector_get( solver->f, 1 ), 15, ' ' )
           << printElement( gsl_vector_get( solver->f, 2 ), 15, ' ' )
           << std::endl;
    return buffer.str( );
}

//! Print data element to console.
template< typename DataType >
inline std::string printElement( const DataType datum, const int width, const char filler )
{
    std::ostringstream buffer;
    buffer << std::left << std::setw( width ) << std::setfill( filler ) << datum;
    return buffer.str( );
}

} // namespace atom

#endif // ATOM_PRINT_FUNCTIONS_HPP
<commit_msg>Move header include guard above include statements in print functions header.<commit_after>/*
 * Copyright (c) 2014-2016 Kartik Kumar, Dinamica Srl (me@kartikkumar.com)
 * Distributed under the MIT License.
 * See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT
 */

#ifndef ATOM_PRINT_FUNCTIONS_HPP
#define ATOM_PRINT_FUNCTIONS_HPP

#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>

#include <gsl/gsl_multiroots.h>

namespace atom
{

//! Print Cartesian-state-to-TLE converter solver summary table header.
/*!
 * Prints header to string for table containing summary of status of non-linear solver used to
 * convert a Cartesian state to a TLE.
 *
 * @sa convertCartesianStateToTwoLineElements
 * @return String containing table header for non-linear solver status.
 */
inline std::string printCartesianToTleSolverStateTableHeader( );

//! Print summary of current state of non-linear solver for Cartesian-state-to-TLE converter.
/*!
 * Prints current state of non-linear solver used to convert a Cartesian state to a TLE, as row
 * for a summary table.
 *
 * @sa convertCartesianStateToTwoLineElements
 * @param  iteration Current iteration of solver
 * @param  solver    Pointer to GSL solver
 * @return           String containing row-data for non-linear solver status summary table
 */
inline std::string printCartesianToTleSolverState(
  const int iteration, gsl_multiroot_fsolver* solver );

//! Print Atom solver summary table header.
/*!
 * Prints header to string for table containing summary of status of non-linear solver used to
 * execute Atom solver.
 *
 * @sa executeAtomSolver
 * @return String containing table header for non-linear solver status.
 */
inline std::string printAtomSolverStateTableHeader( );

//! Print summary of current state of non-linear solver for Atom solver.
/*!
 * Prints current state of non-linear solver used to execute Atom solver, as row for a summary
 * table.
 *
 * @sa executeAtomSolver
 * @param  iteration Current iteration of solver
 * @param  solver    Pointer to GSL solver
 * @return           String containing row-data for non-linear solver status summary table
 */
inline std::string printAtomSolverState(
  const int iteration, gsl_multiroot_fsolver* solver );

//! Print data element to console.
/*!
 * Prints a specified data element to string, given a specified width and a filler character.
 * This function is auxilliary to the print-functions used to the print the state of the non-linear
 * solver.
 *
 * @sa printSolverStateTableHeader, printSolverState
 * @tparam DataType  Type for specified data element
 * @param  datum     Specified data element to print
 * @param  width     Width of datum printed to console, in terms of number of characters
 * @param  filler    Character used to fill fixed-width, [default: ' ']
 * @return           String containing printed data element
 */
template< typename DataType >
inline std::string printElement( const DataType datum, const int width, const char filler = ' ' );

//! Print Cartesian-state-to-TLE converter solver summary table header.
inline std::string printCartesianToTleSolverStateTableHeader( )
{
    std::ostringstream headerBuffer;
    headerBuffer << printElement( "#", 3, ' ' )
                 << printElement( "a", 15, ' ' )
                 << printElement( "e", 15, ' ' )
                 << printElement( "i", 15, ' ' )
                 << printElement( "AoP", 15, ' ' )
                 << printElement( "RAAN", 15, ' ' )
                 << printElement( "TA", 15, ' ' )
                 << printElement( "f1", 15, ' ' )
                 << printElement( "f2", 15, ' ' )
                 << printElement( "f3", 15, ' ' )
                 << printElement( "f4", 15, ' ' )
                 << printElement( "f5", 15, ' ' )
                 << printElement( "f6", 15, ' ' )
                 << std::endl;
    return headerBuffer.str( );
}

//! Print summary of current state of non-linear solver for Cartesian-state-to-TLE converter.
inline std::string printCartesianToTleSolverState(
  const int iteration, gsl_multiroot_fsolver* solver )
{
    std::ostringstream buffer;
    buffer << printElement( iteration, 3, ' ' )
           << printElement( gsl_vector_get( solver->x, 0 ), 15, ' ' )
           << printElement( gsl_vector_get( solver->x, 1 ), 15, ' ' )
           << printElement( gsl_vector_get( solver->x, 2 ), 15, ' ' )
           << printElement( gsl_vector_get( solver->x, 3 ), 15, ' ' )
           << printElement( gsl_vector_get( solver->x, 4 ), 15, ' ' )
           << printElement( gsl_vector_get( solver->x, 5 ), 15, ' ' )
           << printElement( gsl_vector_get( solver->f, 0 ), 15, ' ' )
           << printElement( gsl_vector_get( solver->f, 1 ), 15, ' ' )
           << printElement( gsl_vector_get( solver->f, 2 ), 15, ' ' )
           << printElement( gsl_vector_get( solver->f, 3 ), 15, ' ' )
           << printElement( gsl_vector_get( solver->f, 4 ), 15, ' ' )
           << printElement( gsl_vector_get( solver->f, 5 ), 15, ' ' )
           << std::endl;
    return buffer.str( );
}

//! Print Atom solver summary table header.
inline std::string printAtomSolverStateTableHeader( )
{
    std::ostringstream headerBuffer;
    headerBuffer << printElement( "#", 3, ' ' )
                 << printElement( "v1_x", 15, ' ' )
                 << printElement( "v1_y", 15, ' ' )
                 << printElement( "v1_z", 15, ' ' )
                 << printElement( "f1", 15, ' ' )
                 << printElement( "f2", 15, ' ' )
                 << printElement( "f3", 15, ' ' )
                 << std::endl;
    return headerBuffer.str( );
}

//! Print summary of current state of non-linear solver for Atom solver.
inline std::string printAtomSolverState(
  const int iteration, gsl_multiroot_fsolver* solver )
{
    std::ostringstream buffer;
    buffer << printElement( iteration, 3, ' ' )
           << printElement( gsl_vector_get( solver->x, 0 ), 15, ' ' )
           << printElement( gsl_vector_get( solver->x, 1 ), 15, ' ' )
           << printElement( gsl_vector_get( solver->x, 2 ), 15, ' ' )
           << printElement( gsl_vector_get( solver->f, 0 ), 15, ' ' )
           << printElement( gsl_vector_get( solver->f, 1 ), 15, ' ' )
           << printElement( gsl_vector_get( solver->f, 2 ), 15, ' ' )
           << std::endl;
    return buffer.str( );
}

//! Print data element to console.
template< typename DataType >
inline std::string printElement( const DataType datum, const int width, const char filler )
{
    std::ostringstream buffer;
    buffer << std::left << std::setw( width ) << std::setfill( filler ) << datum;
    return buffer.str( );
}

} // namespace atom

#endif // ATOM_PRINT_FUNCTIONS_HPP
<|endoftext|>


<commit_before>#pragma once

#ifndef RAZ_MATERIAL_HPP
#define RAZ_MATERIAL_HPP

#include <unordered_map>

#include "RaZ/Math/Vector.hpp"
#include "RaZ/Render/Shader.hpp"
#include "RaZ/Render/ShaderProgram.hpp"
#include "RaZ/Render/Texture.hpp"

namespace Raz {

enum class MaterialType {
  MATERIAL_TYPE_STANDARD = 0,
  MATERIAL_TYPE_COOK_TORRANCE
};

enum class MaterialPreset {
  CHARCOAL, GRASS, SAND, ICE, SNOW,                                                   // Dielectric presets
  IRON, SILVER, ALUMINIUM, GOLD, COPPER, CHROMIUM, NICKEL, TITANIUM, COBALT, PLATINUM // Metallic presets
};

class MaterialCookTorrance;

class Material {
public:
  Material(const Material&) = default;

  virtual MaterialType getType() const = 0;

  static std::unique_ptr<MaterialCookTorrance> recoverMaterial(MaterialPreset preset, float roughnessFactor);
  virtual std::unique_ptr<Material> clone() const = 0;
  virtual void initTextures(const ShaderProgram& program) const = 0;
  virtual void bindAttributes(const ShaderProgram& program) const = 0;

  virtual ~Material() = default;

protected:
  Material() = default;
};

using MaterialPtr = std::unique_ptr<Material>;

class MaterialStandard : public Material {
public:
  MaterialStandard() = default;
  explicit MaterialStandard(TexturePtr diffuseMap) : m_diffuseMap{ std::move(diffuseMap) } {}
  explicit MaterialStandard(const std::string& fileName) { m_diffuseMap = std::make_shared<Texture>(fileName); }

  MaterialType getType() const override { return MaterialType::MATERIAL_TYPE_STANDARD; }
  const Vec3f& getAmbient() const { return m_ambient; }
  const Vec3f& getDiffuse() const { return m_diffuse; }
  const Vec3f& getSpecular() const { return m_specular; }
  const Vec3f& getEmissive() const { return m_emissive; }
  float getTransparency() const { return m_transparency; }

  const TexturePtr& getAmbientMap() const { return m_ambientMap; }
  const TexturePtr& getDiffuseMap() const { return m_diffuseMap; }
  const TexturePtr& getSpecularMap() const { return m_specularMap; }
  const TexturePtr& getEmissiveMap() const { return m_emissiveMap; }
  const TexturePtr& getTransparencyMap() const { return m_transparencyMap; }
  const TexturePtr& getBumpMap() const { return m_bumpMap; }

  void setDiffuse(float red, float green, float blue) { setDiffuse(Vec3f({ red, green, blue })); }
  void setDiffuse(const Vec3f& val) { m_diffuse = val; }
  void setAmbient(float red, float green, float blue) { setAmbient(Vec3f({ red, green, blue })); }
  void setAmbient(const Vec3f& val) { m_ambient = val; }
  void setSpecular(float red, float green, float blue) { setSpecular(Vec3f({ red, green, blue })); }
  void setSpecular(const Vec3f& val) { m_specular = val; }
  void setEmissive(float red, float green, float blue) { setEmissive(Vec3f({ red, green, blue })); }
  void setEmissive(const Vec3f& val) { m_emissive = val; }
  void setTransparency(float transparency) { m_transparency = transparency; }

  void setAmbientMap(const TexturePtr& ambientMap) { m_ambientMap = ambientMap; }
  void setDiffuseMap(const TexturePtr& diffuseMap) { m_diffuseMap = diffuseMap; }
  void setSpecularMap(const TexturePtr& specularMap) { m_specularMap = specularMap; }
  void setEmissiveMap(const TexturePtr& emissiveMap) { m_emissiveMap = emissiveMap; }
  void setTransparencyMap(const TexturePtr& transparencyMap) { m_transparencyMap = transparencyMap; }
  void setBumpMap(const TexturePtr& bumpMap) { m_bumpMap = bumpMap; }

  void loadAmbientMap(const std::string& fileName) { m_ambientMap = std::make_shared<Texture>(fileName); }
  void loadDiffuseMap(const std::string& fileName) { m_diffuseMap = std::make_shared<Texture>(fileName); }
  void loadSpecularMap(const std::string& fileName) { m_specularMap = std::make_shared<Texture>(fileName); }
  void loadEmissiveMap(const std::string& fileName) { m_emissiveMap = std::make_shared<Texture>(fileName); }
  void loadTransparencyMap(const std::string& fileName) { m_transparencyMap = std::make_shared<Texture>(fileName); }
  void loadBumpMap(const std::string& fileName) { m_bumpMap = std::make_shared<Texture>(fileName); }

  std::unique_ptr<Material> clone() const override { return std::make_unique<MaterialStandard>(*this); }
  void initTextures(const ShaderProgram& program) const override;
  void bindAttributes(const ShaderProgram& program) const override;

private:
  Vec3f m_ambient      = Vec3f(1.f);
  Vec3f m_diffuse      = Vec3f(1.f);
  Vec3f m_specular     = Vec3f(1.f);
  Vec3f m_emissive     = Vec3f(1.f);
  float m_transparency = 1.f;

  TexturePtr m_ambientMap      = Texture::recoverTexture(TexturePreset::WHITE);
  TexturePtr m_diffuseMap      = Texture::recoverTexture(TexturePreset::WHITE);
  TexturePtr m_specularMap     = Texture::recoverTexture(TexturePreset::WHITE);
  TexturePtr m_emissiveMap     = Texture::recoverTexture(TexturePreset::WHITE);
  TexturePtr m_transparencyMap = Texture::recoverTexture(TexturePreset::WHITE);
  TexturePtr m_bumpMap         = Texture::recoverTexture(TexturePreset::WHITE);
};

class MaterialCookTorrance : public Material {
public:
  MaterialCookTorrance() = default;
  explicit MaterialCookTorrance(TexturePtr albedoMap) : m_albedoMap{ std::move(albedoMap) } {}
  explicit MaterialCookTorrance(const std::string& fileName) { m_albedoMap = std::make_shared<Texture>(fileName); }
  MaterialCookTorrance(const Vec3f& baseColor, float metallicFactor, float roughnessFactor)
    : m_baseColor{ baseColor }, m_metallicFactor{ metallicFactor }, m_roughnessFactor{ roughnessFactor } {}

  MaterialType getType() const override { return MaterialType::MATERIAL_TYPE_COOK_TORRANCE; }
  const Vec3f& getBaseColor() const { return m_baseColor; }
  float getMetallicFactor() const { return m_metallicFactor; }
  float getRoughnessFactor() const { return m_roughnessFactor; }

  const TexturePtr& getAlbedoMap() const { return m_albedoMap; }
  const TexturePtr& getMetallicMap() const { return m_metallicMap; }
  const TexturePtr& getNormalMap() const { return m_normalMap; }
  const TexturePtr& getRoughnessMap() const { return m_roughnessMap; }
  const TexturePtr& getAmbientOcclusionMap() const { return m_ambientOcclusionMap; }

  void setBaseColor(float red, float green, float blue) { setBaseColor(Vec3f({ red, green, blue })); }
  void setBaseColor(const Vec3f& color) { m_baseColor = color; }
  void setMetallicFactor(float metallicFactor) { m_metallicFactor = metallicFactor; }
  void setRoughnessFactor(float roughnessFactor) { m_roughnessFactor = roughnessFactor; }

  void setAlbedoMap(const TexturePtr& albedoMap) { m_albedoMap = albedoMap; }
  void setNormalMap(const TexturePtr& normalMap) { m_normalMap = normalMap; }
  void setMetallicMap(const TexturePtr& metallicMap) { m_metallicMap = metallicMap; }
  void setRoughnessMap(const TexturePtr& roughnessMap) { m_roughnessMap = roughnessMap; }
  void setAmbientOcclusionMap(const TexturePtr& ambientOcclusionMap) { m_ambientOcclusionMap = ambientOcclusionMap; }

  void loadAlbedoMap(const std::string& fileName) { m_albedoMap = std::make_shared<Texture>(fileName); }
  void loadNormalMap(const std::string& fileName) { m_normalMap = std::make_shared<Texture>(fileName); }
  void loadMetallicMap(const std::string& fileName) { m_metallicMap = std::make_shared<Texture>(fileName); }
  void loadRoughnessMap(const std::string& fileName) { m_roughnessMap = std::make_shared<Texture>(fileName); }
  void loadAmbientOcclusionMap(const std::string& fileName) { m_ambientOcclusionMap = std::make_shared<Texture>(fileName); }

  std::unique_ptr<Material> clone() const override { return std::make_unique<MaterialCookTorrance>(*this); }
  void initTextures(const ShaderProgram& program) const override;
  void bindAttributes(const ShaderProgram& program) const override;

private:
  Vec3f m_baseColor       = Vec3f(1.f);
  float m_metallicFactor  = 1.f;
  float m_roughnessFactor = 1.f;

  TexturePtr m_albedoMap           = Texture::recoverTexture(TexturePreset::WHITE);
  TexturePtr m_normalMap           = Texture::recoverTexture(TexturePreset::WHITE);
  TexturePtr m_metallicMap         = Texture::recoverTexture(TexturePreset::WHITE);
  TexturePtr m_roughnessMap        = Texture::recoverTexture(TexturePreset::WHITE);
  TexturePtr m_ambientOcclusionMap = Texture::recoverTexture(TexturePreset::WHITE);
};

} // namespace Raz

#endif // RAZ_MATERIAL_HPP
<commit_msg>[Update] Standard material's emissive factor is now defaulted to 0<commit_after>#pragma once

#ifndef RAZ_MATERIAL_HPP
#define RAZ_MATERIAL_HPP

#include <unordered_map>

#include "RaZ/Math/Vector.hpp"
#include "RaZ/Render/Shader.hpp"
#include "RaZ/Render/ShaderProgram.hpp"
#include "RaZ/Render/Texture.hpp"

namespace Raz {

enum class MaterialType {
  MATERIAL_TYPE_STANDARD = 0,
  MATERIAL_TYPE_COOK_TORRANCE
};

enum class MaterialPreset {
  CHARCOAL, GRASS, SAND, ICE, SNOW,                                                   // Dielectric presets
  IRON, SILVER, ALUMINIUM, GOLD, COPPER, CHROMIUM, NICKEL, TITANIUM, COBALT, PLATINUM // Metallic presets
};

class MaterialCookTorrance;

class Material {
public:
  Material(const Material&) = default;

  virtual MaterialType getType() const = 0;

  static std::unique_ptr<MaterialCookTorrance> recoverMaterial(MaterialPreset preset, float roughnessFactor);
  virtual std::unique_ptr<Material> clone() const = 0;
  virtual void initTextures(const ShaderProgram& program) const = 0;
  virtual void bindAttributes(const ShaderProgram& program) const = 0;

  virtual ~Material() = default;

protected:
  Material() = default;
};

using MaterialPtr = std::unique_ptr<Material>;

class MaterialStandard : public Material {
public:
  MaterialStandard() = default;
  explicit MaterialStandard(TexturePtr diffuseMap) : m_diffuseMap{ std::move(diffuseMap) } {}
  explicit MaterialStandard(const std::string& fileName) { m_diffuseMap = std::make_shared<Texture>(fileName); }

  MaterialType getType() const override { return MaterialType::MATERIAL_TYPE_STANDARD; }
  const Vec3f& getAmbient() const { return m_ambient; }
  const Vec3f& getDiffuse() const { return m_diffuse; }
  const Vec3f& getSpecular() const { return m_specular; }
  const Vec3f& getEmissive() const { return m_emissive; }
  float getTransparency() const { return m_transparency; }

  const TexturePtr& getAmbientMap() const { return m_ambientMap; }
  const TexturePtr& getDiffuseMap() const { return m_diffuseMap; }
  const TexturePtr& getSpecularMap() const { return m_specularMap; }
  const TexturePtr& getEmissiveMap() const { return m_emissiveMap; }
  const TexturePtr& getTransparencyMap() const { return m_transparencyMap; }
  const TexturePtr& getBumpMap() const { return m_bumpMap; }

  void setDiffuse(float red, float green, float blue) { setDiffuse(Vec3f({ red, green, blue })); }
  void setDiffuse(const Vec3f& val) { m_diffuse = val; }
  void setAmbient(float red, float green, float blue) { setAmbient(Vec3f({ red, green, blue })); }
  void setAmbient(const Vec3f& val) { m_ambient = val; }
  void setSpecular(float red, float green, float blue) { setSpecular(Vec3f({ red, green, blue })); }
  void setSpecular(const Vec3f& val) { m_specular = val; }
  void setEmissive(float red, float green, float blue) { setEmissive(Vec3f({ red, green, blue })); }
  void setEmissive(const Vec3f& val) { m_emissive = val; }
  void setTransparency(float transparency) { m_transparency = transparency; }

  void setAmbientMap(const TexturePtr& ambientMap) { m_ambientMap = ambientMap; }
  void setDiffuseMap(const TexturePtr& diffuseMap) { m_diffuseMap = diffuseMap; }
  void setSpecularMap(const TexturePtr& specularMap) { m_specularMap = specularMap; }
  void setEmissiveMap(const TexturePtr& emissiveMap) { m_emissiveMap = emissiveMap; }
  void setTransparencyMap(const TexturePtr& transparencyMap) { m_transparencyMap = transparencyMap; }
  void setBumpMap(const TexturePtr& bumpMap) { m_bumpMap = bumpMap; }

  void loadAmbientMap(const std::string& fileName) { m_ambientMap = std::make_shared<Texture>(fileName); }
  void loadDiffuseMap(const std::string& fileName) { m_diffuseMap = std::make_shared<Texture>(fileName); }
  void loadSpecularMap(const std::string& fileName) { m_specularMap = std::make_shared<Texture>(fileName); }
  void loadEmissiveMap(const std::string& fileName) { m_emissiveMap = std::make_shared<Texture>(fileName); }
  void loadTransparencyMap(const std::string& fileName) { m_transparencyMap = std::make_shared<Texture>(fileName); }
  void loadBumpMap(const std::string& fileName) { m_bumpMap = std::make_shared<Texture>(fileName); }

  std::unique_ptr<Material> clone() const override { return std::make_unique<MaterialStandard>(*this); }
  void initTextures(const ShaderProgram& program) const override;
  void bindAttributes(const ShaderProgram& program) const override;

private:
  Vec3f m_ambient      = Vec3f(1.f);
  Vec3f m_diffuse      = Vec3f(1.f);
  Vec3f m_specular     = Vec3f(1.f);
  Vec3f m_emissive     = Vec3f(0.f);
  float m_transparency = 1.f;

  TexturePtr m_ambientMap      = Texture::recoverTexture(TexturePreset::WHITE);
  TexturePtr m_diffuseMap      = Texture::recoverTexture(TexturePreset::WHITE);
  TexturePtr m_specularMap     = Texture::recoverTexture(TexturePreset::WHITE);
  TexturePtr m_emissiveMap     = Texture::recoverTexture(TexturePreset::WHITE);
  TexturePtr m_transparencyMap = Texture::recoverTexture(TexturePreset::WHITE);
  TexturePtr m_bumpMap         = Texture::recoverTexture(TexturePreset::WHITE);
};

class MaterialCookTorrance : public Material {
public:
  MaterialCookTorrance() = default;
  explicit MaterialCookTorrance(TexturePtr albedoMap) : m_albedoMap{ std::move(albedoMap) } {}
  explicit MaterialCookTorrance(const std::string& fileName) { m_albedoMap = std::make_shared<Texture>(fileName); }
  MaterialCookTorrance(const Vec3f& baseColor, float metallicFactor, float roughnessFactor)
    : m_baseColor{ baseColor }, m_metallicFactor{ metallicFactor }, m_roughnessFactor{ roughnessFactor } {}

  MaterialType getType() const override { return MaterialType::MATERIAL_TYPE_COOK_TORRANCE; }
  const Vec3f& getBaseColor() const { return m_baseColor; }
  float getMetallicFactor() const { return m_metallicFactor; }
  float getRoughnessFactor() const { return m_roughnessFactor; }

  const TexturePtr& getAlbedoMap() const { return m_albedoMap; }
  const TexturePtr& getMetallicMap() const { return m_metallicMap; }
  const TexturePtr& getNormalMap() const { return m_normalMap; }
  const TexturePtr& getRoughnessMap() const { return m_roughnessMap; }
  const TexturePtr& getAmbientOcclusionMap() const { return m_ambientOcclusionMap; }

  void setBaseColor(float red, float green, float blue) { setBaseColor(Vec3f({ red, green, blue })); }
  void setBaseColor(const Vec3f& color) { m_baseColor = color; }
  void setMetallicFactor(float metallicFactor) { m_metallicFactor = metallicFactor; }
  void setRoughnessFactor(float roughnessFactor) { m_roughnessFactor = roughnessFactor; }

  void setAlbedoMap(const TexturePtr& albedoMap) { m_albedoMap = albedoMap; }
  void setNormalMap(const TexturePtr& normalMap) { m_normalMap = normalMap; }
  void setMetallicMap(const TexturePtr& metallicMap) { m_metallicMap = metallicMap; }
  void setRoughnessMap(const TexturePtr& roughnessMap) { m_roughnessMap = roughnessMap; }
  void setAmbientOcclusionMap(const TexturePtr& ambientOcclusionMap) { m_ambientOcclusionMap = ambientOcclusionMap; }

  void loadAlbedoMap(const std::string& fileName) { m_albedoMap = std::make_shared<Texture>(fileName); }
  void loadNormalMap(const std::string& fileName) { m_normalMap = std::make_shared<Texture>(fileName); }
  void loadMetallicMap(const std::string& fileName) { m_metallicMap = std::make_shared<Texture>(fileName); }
  void loadRoughnessMap(const std::string& fileName) { m_roughnessMap = std::make_shared<Texture>(fileName); }
  void loadAmbientOcclusionMap(const std::string& fileName) { m_ambientOcclusionMap = std::make_shared<Texture>(fileName); }

  std::unique_ptr<Material> clone() const override { return std::make_unique<MaterialCookTorrance>(*this); }
  void initTextures(const ShaderProgram& program) const override;
  void bindAttributes(const ShaderProgram& program) const override;

private:
  Vec3f m_baseColor       = Vec3f(1.f);
  float m_metallicFactor  = 1.f;
  float m_roughnessFactor = 1.f;

  TexturePtr m_albedoMap           = Texture::recoverTexture(TexturePreset::WHITE);
  TexturePtr m_normalMap           = Texture::recoverTexture(TexturePreset::WHITE);
  TexturePtr m_metallicMap         = Texture::recoverTexture(TexturePreset::WHITE);
  TexturePtr m_roughnessMap        = Texture::recoverTexture(TexturePreset::WHITE);
  TexturePtr m_ambientOcclusionMap = Texture::recoverTexture(TexturePreset::WHITE);
};

} // namespace Raz

#endif // RAZ_MATERIAL_HPP
<|endoftext|>


<commit_before>//
// embed.hpp
// *********
//
// Copyright (c) 2018 Sharon W (sharon at aegis dot gg)
//
// Distributed under the MIT License. (See accompanying file LICENSE)
//

#pragma once

#include "aegis/config.hpp"
#include "aegis/snowflake.hpp"
#include "field.hpp"
#include "footer.hpp"
#include "image.hpp"
#include "thumbnail.hpp"
#include "video.hpp"
#include "provider.hpp"
#include <nlohmann/json.hpp>
#include <string>
#include <vector>

namespace aegis
{

namespace gateway
{

namespace objects
{

/**\todo Needs documentation
 */
class embed
{
public:
    /// Adds a new embed field
    /**
     * @param name Name of the field
     * @param value Text to be shown within field
     * @param is_inline Sets whether the field is inline
     */
    void add_field(const std::string & name, const std::string & value, bool is_inline = false)
    {
        fields.emplace_back(name, value, is_inline);
    }
    /// Sets the title of the embed
    /**
     * @param str Title to set
     */
    void set_title(const std::string & str)
    {
        title = str;
    }
    /// Sets the footer of the embed
    /**
     * @param str Footer to set
     */
    void set_footer(const footer ftr)
    {
        footer_ = ftr;
    }
    /// Sets the description of the embed
    /**
     * @param str Description to set
     */
    void set_description(const std::string & str)
    {
        description = str;
    }
    /// Sets the url of the embed
    /**
     * @param str Url to set
     */
    void set_url(const std::string & str)
    {
        url = str;
    }
    /// Sets the timestamp of the embed
    /**
     * @param str Timestamp to set
     */
    void set_timestamp(const std::string & str)
    {
        timestamp = str;
    }
    /// Sets the color of the embed
    /**
     * @param clr Color to set
     */
    void set_color(const int32_t clr)
    {
        color = clr;
    }
    // Combined Limit: 6000
    std::string title; /**<\todo Needs documentation */ // Limit: 256
    std::string type; /**<\todo Needs documentation */
    std::string description; /**<\todo Needs documentation */ // Limit: 2048
    std::string url; /**<\todo Needs documentation */
    std::string timestamp; /**<\todo Needs documentation */
    int32_t color = 0; /**<\todo Needs documentation */
    footer footer_; /**<\todo Needs documentation */ // Limit: 2048
    image image_; /**<\todo Needs documentation */
    thumbnail thumbnail_; /**<\todo Needs documentation */
    video video_; /**<\todo Needs documentation */
    provider provider_; /**<\todo Needs documentation */
    std::vector<field> fields; /**<\todo Needs documentation */ // Limit: 25 name:256 value:1024
};

/// \cond TEMPLATES
inline void from_json(const nlohmann::json& j, embed& m)
{
    if (j.count("title") && !j["title"].is_null())
        m.title = j["title"];
    if (j.count("type"))
        m.type = j["type"];
    if (j.count("description") && !j["description"].is_null())
        m.description = j["description"];
    if (j.count("url") && !j["url"].is_null())
        m.url = j["url"];
    if (j.count("timestamp") && !j["timestamp"].is_null())
        m.timestamp = j["timestamp"];
    if (j.count("color") && !j["color"].is_null())
        m.color = j["color"];
    if (j.count("footer") && !j["footer"].is_null())
        m.footer_ = j["footer"];
    if (j.count("image") && !j["image"].is_null())
        m.image_ = j["image"];
    if (j.count("thumbnail") && !j["thumbnail"].is_null())
        m.thumbnail_ = j["thumbnail"];
    if (j.count("video") && !j["video"].is_null())
        m.video_ = j["video"];
    if (j.count("provider") && !j["provider"].is_null())
        m.provider_ = j["provider"];
    if (j.count("fields") && !j["fields"].is_null())
        for (const auto & _field : j["fields"])
            m.fields.push_back(_field);
}
/// \endcond

/// \cond TEMPLATES
inline void to_json(nlohmann::json& j, const embed& m)
{
    j["title"] = m.title;
    j["type"] = m.type;
    j["description"] = m.description;
    j["url"] = m.url;
    j["timestamp"] = m.timestamp;
    j["color"] = m.color;
    j["footer"] = m.footer_;
    j["image"] = m.image_;
    j["thumbnail"] = m.thumbnail_;
    j["video"] = m.video_;
    j["provider"] = m.provider_;
    for (const auto & _field : m.fields)
        j["fields"].push_back(_field);
}
/// \endcond

}

}

}
<commit_msg>Changed embed to fluent-style interface<commit_after>//
// embed.hpp
// *********
//
// Copyright (c) 2018 Sharon W (sharon at aegis dot gg)
//
// Distributed under the MIT License. (See accompanying file LICENSE)
//

#pragma once

#include "aegis/config.hpp"
#include "aegis/snowflake.hpp"
#include "field.hpp"
#include "footer.hpp"
#include "image.hpp"
#include "thumbnail.hpp"
#include "video.hpp"
#include "provider.hpp"
#include <nlohmann/json.hpp>
#include <string>
#include <vector>

namespace aegis
{

namespace gateway
{

namespace objects
{

/**\todo Needs documentation
 */
class embed
{
public:
    /// Adds a new embed field
    /**
     * @param name Name of the field
     * @param value Text to be shown within field
     * @param is_inline Sets whether the field is inline
     */
    embed & fields(std::vector<objects::field> flds)
    {
        _fields = flds;
        return *this;
    }
    /// Sets the title of the embed
    /**
     * @param str Title to set
     */
    embed & title(const std::string & str)
    {
        _title = str;
        return *this;
    }
    /// Sets the footer of the embed
    /**
     * @param str Footer to set
     */
    embed & footer(const footer ftr)
    {
        _footer = ftr;
        return *this;
    }
    /// Sets the description of the embed
    /**
     * @param str Description to set
     */
    embed & description(const std::string & str)
    {
        _description = str;
        return *this;
    }
    /// Sets the url of the embed
    /**
     * @param str Url to set
     */
    embed & url(std::string & str)
    {
        _url = str;
        return *this;
    }
    /// Sets the timestamp of the embed
    /**
     * @param str Timestamp to set
     */
    embed & timestamp(const std::string & str)
    {
        _timestamp = str;
        return *this;
    }
    /// Sets the color of the embed
    /**
     * @param clr Color to set
     */
    embed & color(const int32_t clr)
    {
        _color = clr;
        return *this;
    }
    // Combined Limit: 6000
    std::string _title; /**<\todo Needs documentation */ // Limit: 256
    std::string _type; /**<\todo Needs documentation */
    std::string _description; /**<\todo Needs documentation */ // Limit: 2048
    std::string _url; /**<\todo Needs documentation */
    std::string _timestamp; /**<\todo Needs documentation */
    int32_t _color = 0; /**<\todo Needs documentation */
    objects::footer _footer; /**<\todo Needs documentation */ // Limit: 2048
    objects::image _image; /**<\todo Needs documentation */
    objects::thumbnail _thumbnail; /**<\todo Needs documentation */
    objects::video _video; /**<\todo Needs documentation */
    objects::provider _provider; /**<\todo Needs documentation */
    std::vector<objects::field> _fields; /**<\todo Needs documentation */ // Limit: 25 name:256 value:1024
    friend void from_json(const nlohmann::json& j, embed& m);
    friend void to_json(nlohmann::json& j, const embed& m);
};

/// \cond TEMPLATES
inline void from_json(const nlohmann::json& j, embed& m)
{
    if (j.count("title") && !j["title"].is_null())
        m._title = j["title"].get<std::string>();
    if (j.count("type"))
        m._type = j["type"].get<std::string>();
    if (j.count("description") && !j["description"].is_null())
        m._description = j["description"].get<std::string>();
    if (j.count("url") && !j["url"].is_null())
        m._url = j["url"].get<std::string>();
    if (j.count("timestamp") && !j["timestamp"].is_null())
        m._timestamp = j["timestamp"].get<std::string>();
    if (j.count("color") && !j["color"].is_null())
        m._color = j["color"];
    if (j.count("footer") && !j["footer"].is_null())
        m._footer = j["footer"];
    if (j.count("image") && !j["image"].is_null())
        m._image = j["image"];
    if (j.count("thumbnail") && !j["thumbnail"].is_null())
        m._thumbnail = j["thumbnail"];
    if (j.count("video") && !j["video"].is_null())
        m._video = j["video"];
    if (j.count("provider") && !j["provider"].is_null())
        m._provider = j["provider"];
    if (j.count("fields") && !j["fields"].is_null())
        for (const auto & _field : j["fields"])
            m._fields.push_back(_field);
}
/// \endcond

/// \cond TEMPLATES
inline void to_json(nlohmann::json& j, const embed& m)
{
    j["title"] = m._title;
    j["type"] = m._type;
    j["description"] = m._description;
    j["url"] = m._url;
    j["timestamp"] = m._timestamp;
    j["color"] = m._color;
    j["footer"] = m._footer;
    j["image"] = m._image;
    j["thumbnail"] = m._thumbnail;
    j["video"] = m._video;
    j["provider"] = m._provider;
    for (const auto & _field : m._fields)
        j["fields"].push_back(_field);
}
/// \endcond

}

}

}
<|endoftext|>


<commit_before>#pragma once
#include <array>
#include <baka/variadic.hpp>
#include <cstddef>
#include <ffi.h>
#include <functional>
#include <type_traits>
#include <utility>
#include <vector>

namespace baka {
    namespace detail {
        template<typename T>
        ffi_type* type();

        template<>
        ffi_type* type<int>() {
            return &ffi_type_sint;
        }
    }

    template<typename T>
    class bound_function;

    template<typename Ret, typename... Args>
    class bound_function<Ret(Args...)> {
        using fptr_t = Ret(*)(Args...);

    public:
        template<typename F>
        explicit bound_function(F&& function_)
            : function(std::forward<F>(function_)) {
            return_type = detail::type<Ret>();
            argument_types = { detail::type<Args>()... };
            ffi_prep_cif(&cif, FFI_DEFAULT_ABI, argument_types.size(), return_type, argument_types.data());

            closure = ffi_closure_alloc(sizeof(ffi_closure), &thunk);
            ffi_prep_closure_loc(static_cast<ffi_closure*>(closure), &cif, &call, this, reinterpret_cast<void*>(thunk));
        }

        operator fptr_t() const {
            return reinterpret_cast<fptr_t>(thunk);
        }

    private:
        static void call(ffi_cif*, void* ret, void** args, void* self_void) {
            auto self = static_cast<bound_function*>(self_void);
            self->template call_<0>(static_cast<Ret*>(ret), args);
        }

        template<std::size_t N, typename... CallArgs>
        typename std::enable_if<N != sizeof...(Args)>::type
        call_(Ret* ret, void** args, CallArgs&&... call_args) {
            call_<N + 1>(ret, args, std::forward<CallArgs>(call_args)..., *static_cast<NthType<N, Args...>*>(args[N]));
        }

        template<std::size_t N, typename... CallArgs>
        typename std::enable_if<N == sizeof...(Args)>::type
        call_(Ret* ret, void**, CallArgs&&... call_args) {
            *ret = function(std::forward<CallArgs>(call_args)...);
        }

        std::function<Ret(Args...)> function;
        ffi_cif cif;
        ffi_type* return_type;
        std::vector<ffi_type*> argument_types;
        void* closure;
        void* thunk;
    };
}
<commit_msg>Free closure when bound_function is destroyed<commit_after>#pragma once
#include <array>
#include <baka/variadic.hpp>
#include <cstddef>
#include <ffi.h>
#include <functional>
#include <memory>
#include <type_traits>
#include <utility>
#include <vector>

namespace baka {
    namespace detail {
        template<typename T>
        ffi_type* type();

        template<>
        ffi_type* type<int>() {
            return &::ffi_type_sint;
        }
    }

    template<typename T>
    class bound_function;

    template<typename Ret, typename... Args>
    class bound_function<Ret(Args...)> {
        using fptr_t = Ret(*)(Args...);

    public:
        template<typename F>
        explicit bound_function(F&& function_)
            : function(std::forward<F>(function_))
            , closure(nullptr, &::ffi_closure_free) {
            return_type = detail::type<Ret>();
            argument_types = { detail::type<Args>()... };
            ::ffi_prep_cif(&cif, FFI_DEFAULT_ABI, argument_types.size(), return_type, argument_types.data());

            closure.reset(static_cast<::ffi_closure*>(::ffi_closure_alloc(sizeof(::ffi_closure), &thunk)));
            ::ffi_prep_closure_loc(closure.get(), &cif, &call, this, reinterpret_cast<void*>(thunk));
        }

        operator fptr_t() const {
            return reinterpret_cast<fptr_t>(thunk);
        }

    private:
        static void call(ffi_cif*, void* ret, void** args, void* self_void) {
            auto self = static_cast<bound_function*>(self_void);
            self->template call_<0>(static_cast<Ret*>(ret), args);
        }

        template<std::size_t N, typename... CallArgs>
        typename std::enable_if<N != sizeof...(Args)>::type
        call_(Ret* ret, void** args, CallArgs&&... call_args) {
            call_<N + 1>(ret, args, std::forward<CallArgs>(call_args)..., *static_cast<NthType<N, Args...>*>(args[N]));
        }

        template<std::size_t N, typename... CallArgs>
        typename std::enable_if<N == sizeof...(Args)>::type
        call_(Ret* ret, void**, CallArgs&&... call_args) {
            *ret = function(std::forward<CallArgs>(call_args)...);
        }

        std::function<Ret(Args...)> function;
        ::ffi_cif cif;
        ::ffi_type* return_type;
        std::vector<::ffi_type*> argument_types;
        std::unique_ptr<::ffi_closure, decltype(&::ffi_closure_free)> closure;
        void* thunk; // freed by ::ffi_closure_free
    };
}
<|endoftext|>


<commit_before><commit_msg>the variable is only available on linux<commit_after><|endoftext|>