average.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /* average.cpp - universal average node
  2. * Copyright (C) 2017 caryoscelus
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. #include <core/node_info.h>
  18. #include <core/node/proxy_node.h>
  19. #include <core/all_types.h>
  20. #include <core/context.h>
  21. namespace rainynite::core::nodes {
  22. namespace detail {
  23. using std::declval;
  24. template <typename A, typename B>
  25. using can_be_summed_t = decltype(declval<A&>() + declval<B&>());
  26. template <typename A, typename B>
  27. using can_be_multiplied_t = decltype(declval<A&>() * declval<B&>());
  28. }
  29. using std::experimental::is_detected_v;
  30. template <typename A, typename B>
  31. constexpr bool can_be_summed = is_detected_v<detail::can_be_summed_t, A, B>;
  32. template <typename A, typename B>
  33. constexpr bool can_be_multiplied = is_detected_v<detail::can_be_multiplied_t, A, B>;
  34. template <class T>
  35. class WeightedAverage : public Node<T> {
  36. DOC_STRING(
  37. "Weighted average value\n"
  38. "\n"
  39. "Works with any type that can be summed with itself"
  40. "and multiplied by Real."
  41. )
  42. public:
  43. WeightedAverage() {
  44. this->template init<T>(a, {});
  45. this->template init<T>(b, {});
  46. this->template init<double>(progress, {});
  47. }
  48. T get(shared_ptr<Context> ctx) const override {
  49. if constexpr (can_be_summed<T, T> && can_be_multiplied<T, double>) {
  50. auto p = get_progress()->get(ctx);
  51. return get_a()->get(ctx)*(1.0-p) + get_b()->get(ctx)*p;
  52. } else {
  53. throw std::logic_error("WeightedAverage on unsupported type");
  54. }
  55. }
  56. private:
  57. NODE_PROPERTY(a, T);
  58. NODE_PROPERTY(b, T);
  59. NODE_PROPERTY(progress, double);
  60. };
  61. NODE_INFO_TEMPLATE(WeightedAverage, WeightedAverage<T>, T);
  62. TYPE_INSTANCES(WeightedAverageNodeInfo)
  63. } // namespace rainynite::core::nodes