list.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * list.cpp - list utils
  3. * Copyright (C) 2017 caryoscelus
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #include <core/node_info.h>
  19. #include <core/node/proxy_node.h>
  20. #include <core/node/property.h>
  21. #include <core/all_types.h>
  22. namespace rainynite::core {
  23. class ToUntypedList : public Node<Nothing> {
  24. public:
  25. ToUntypedList() {
  26. init_property("source", {}, make_value<Nothing>());
  27. }
  28. public:
  29. vector<NodeInContext> get_list_links(shared_ptr<Context> ctx) const override {
  30. if (auto list = get_property("source"))
  31. return list->get_list_links(ctx);
  32. return {};
  33. }
  34. Nothing get(shared_ptr<Context> /*ctx*/) const override {
  35. return {};
  36. }
  37. };
  38. REGISTER_NODE(ToUntypedList);
  39. template <typename T>
  40. class ListElement : public ProxyNode<T> {
  41. public:
  42. ListElement() {
  43. this->init_property("source", {}, make_value<Nothing>());
  44. this->template init<double>(n, 0);
  45. }
  46. NodeInContext get_proxy(shared_ptr<Context> ctx) const override {
  47. auto list = this->get_property("source");
  48. auto l = list->get_list_links(ctx);
  49. if (l.size() == 0)
  50. throw NodeAccessError("Requested element of empty list");
  51. size_t n = std::clamp(get_n()->get(ctx), 0.0, l.size()-1.0);
  52. return l[n];
  53. }
  54. private:
  55. NODE_PROPERTY(n, double);
  56. };
  57. NODE_INFO_TEMPLATE(ListElement, ListElement<T>, T);
  58. TYPE_INSTANCES(ListElementNodeInfo)
  59. } // namespace rainynite::core