node-editor.cpp 93.8 KB
Newer Older
1
2
3
4
// Copyright (c) 2020 INRA Distributed under the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

Gauthier Quesnel's avatar
Gauthier Quesnel committed
5
6
7
8
9
#ifdef _WIN32
#define NOMINMAX
#define WINDOWS_LEAN_AND_MEAN
#endif

10
#include "node-editor.hpp"
Gauthier Quesnel's avatar
Gauthier Quesnel committed
11
12
#include "gui.hpp"
#include "imnodes.hpp"
13
#include "implot.h"
Gauthier Quesnel's avatar
Gauthier Quesnel committed
14

15
#include <fstream>
Gauthier Quesnel's avatar
Gauthier Quesnel committed
16
#include <string>
17

18
#include <fmt/format.h>
19
#include <irritator/core.hpp>
Gauthier Quesnel's avatar
Gauthier Quesnel committed
20
#include <irritator/io.hpp>
21
22
23

namespace irt {

Gauthier Quesnel's avatar
Gauthier Quesnel committed
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
static int kernel_model_cache = 1024;
static int kernel_message_cache = 32768;

static int gui_node_cache = 1024;
static ImVec4 gui_model_color{ .27f, .27f, .54f, 1.f };
static ImVec4 gui_cluster_color{ .27f, .54f, .27f, 1.f };

static ImU32 gui_hovered_model_color;
static ImU32 gui_hovered_cluster_color;
static ImU32 gui_selected_model_color;
static ImU32 gui_selected_cluster_color;

static int automatic_layout_iteration_limit = 200;
static auto automatic_layout_x_distance = 350.f;
static auto automatic_layout_y_distance = 350.f;
static auto grid_layout_x_distance = 250.f;
static auto grid_layout_y_distance = 250.f;

Gauthier Quesnel's avatar
Gauthier Quesnel committed
42
43
static ImVec4
operator*(const ImVec4& lhs, const float rhs) noexcept
Gauthier Quesnel's avatar
Gauthier Quesnel committed
44
45
46
47
{
    return ImVec4(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs, lhs.w * rhs);
}

Gauthier Quesnel's avatar
Gauthier Quesnel committed
48
49
static void
compute_color() noexcept
Gauthier Quesnel's avatar
Gauthier Quesnel committed
50
51
52
53
54
55
56
57
58
59
60
61
{
    gui_hovered_model_color =
      ImGui::ColorConvertFloat4ToU32(gui_model_color * 1.25f);
    gui_selected_model_color =
      ImGui::ColorConvertFloat4ToU32(gui_model_color * 1.5f);

    gui_hovered_cluster_color =
      ImGui::ColorConvertFloat4ToU32(gui_cluster_color * 1.25f);
    gui_selected_cluster_color =
      ImGui::ColorConvertFloat4ToU32(gui_cluster_color * 1.5f);
}

62
63
64
template<size_t N, typename... Args>
void
format(small_string<N>& str, const char* fmt, const Args&... args)
65
{
66
67
    auto ret = fmt::format_to_n(str.begin(), N, fmt, args...);
    str.size(ret.size);
68
69
}

70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
template<typename DataArray, typename Container, typename Function>
void
for_each(DataArray& d_array, Container& container, Function f) noexcept
{
    using identifier_type = typename DataArray::identifier_type;

    static_assert(
      std::is_same<identifier_type, typename Container::value_type>::value,
      "Container must store same identifier_type as DataArray");

    auto first = std::begin(container);
    [[maybe_unused]] auto previous = first;
    auto last = std::end(container);

    while (first != last) {
        if (auto* ptr = d_array.try_to_get(*first); ptr) {
            f(*ptr, *first);

            if constexpr (std::is_same_v<std::vector<identifier_type>,
                                         std::remove_cvref_t<Container>>) {
                ++first;
            } else if constexpr (std::is_same_v<
                                   flat_list<identifier_type>,
                                   std::remove_cvref_t<Container>>) {
                previous = first++;
            } else {
                abort();
            }
        } else {
            if constexpr (std::is_same_v<std::vector<identifier_type>,
                                         std::remove_cvref_t<Container>>) {
                std::swap(*first, container.back());
                container.pop_back();
                last = std::end(container);
            } else if constexpr (std::is_same_v<
                                   flat_list<identifier_type>,
                                   std::remove_cvref_t<Container>>) {
                if (previous == first) {
                    container.pop_front();
                    first = container.begin();
                    previous = first;
                } else {
                    first = container.erase_after(previous);
                }
            } else {
                abort();
            }
        }
    }
}

121
122
static window_logger log_w;
static data_array<editor, editor_id> editors;
123
124
125
126
127
128
129
130
131

static void
observation_output_initialize(const irt::observer& obs,
                              const irt::time t) noexcept
{
    if (!obs.user_data)
        return;

    auto* output = reinterpret_cast<observation_output*>(obs.user_data);
132
133
134
135
136
    if (match(output->observation_type,
              observation_output::type::multiplot,
              observation_output::type::both)) {
        std::fill_n(output->xs.data(), output->xs.size(), 0.f);
        std::fill_n(output->ys.data(), output->ys.size(), 0.f);
137
138
139
140
141
142
        output->tl = t;
        output->min = -1.f;
        output->max = +1.f;
        output->id = 0;
    }

143
144
145
    if (match(output->observation_type,
              observation_output::type::file,
              observation_output::type::both)) {
146
147
        if (!output->ofs.is_open()) {
            if (output->observation_type == observation_output::type::both)
148
                output->observation_type = observation_output::type::multiplot;
149
150
151
152
153
            else
                output->observation_type = observation_output::type::none;
        } else
            output->ofs << "t," << output->name << '\n';
    }
154
155
156
157
158
159
160
161
162
163
164
}

static void
observation_output_observe(const irt::observer& obs,
                           const irt::time t,
                           const irt::message& msg) noexcept
{
    if (!obs.user_data)
        return;

    auto* output = reinterpret_cast<observation_output*>(obs.user_data);
165
    const auto value = static_cast<float>(msg[0]);
166

167
168
169
    if (match(output->observation_type,
              observation_output::type::multiplot,
              observation_output::type::both)) {
170
171
        output->min = std::min(output->min, value);
        output->max = std::max(output->max, value);
172

173
174
175
176
177
178
179
180
        for (double to_fill = output->tl; to_fill < t;
             to_fill += obs.time_step) {
            if (static_cast<size_t>(output->id) < output->xs.size()) {
                output->ys[output->id] = value;
                output->xs[output->id] = static_cast<float>(t);
                ++output->id;
            }
        }
181
182
    }

183
184
185
    if (match(output->observation_type,
              observation_output::type::file,
              observation_output::type::both)) {
186
187
        output->ofs << t << ',' << value << '\n';
    }
188
189
190
191

    output->tl = t;
}

192
static void
193
194
observation_output_free(const irt::observer& obs,
                        const irt::time /*t*/) noexcept
195
196
197
198
199
200
{
    if (!obs.user_data)
        return;

    auto* output = reinterpret_cast<observation_output*>(obs.user_data);

201
202
203
    if (match(output->observation_type,
              observation_output::type::file,
              observation_output::type::both)) {
204
205
206
207
        output->ofs.close();
    }
}

208
209
210
211
212
213
static void
run_simulation(simulation& sim,
               double begin,
               double end,
               double& current,
               simulation_status& st,
Gauthier Quesnel's avatar
Gauthier Quesnel committed
214
               const bool& stop) noexcept
215
{
216
    current = begin;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
217
    if (auto ret = sim.initialize(current); irt::is_bad(ret)) {
218
219
        log_w.log(3,
                  "Simulation initialization failure (%s)\n",
Gauthier Quesnel's avatar
Gauthier Quesnel committed
220
                  irt::status_string(ret));
Gauthier Quesnel's avatar
Gauthier Quesnel committed
221
        st = simulation_status::success;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
222
223
        return;
    }
224
225

    do {
Gauthier Quesnel's avatar
Gauthier Quesnel committed
226
        if (auto ret = sim.run(current); irt::is_bad(ret)) {
Gauthier Quesnel's avatar
Gauthier Quesnel committed
227
            log_w.log(3, "Simulation failure (%s)\n", irt::status_string(ret));
Gauthier Quesnel's avatar
Gauthier Quesnel committed
228
            st = simulation_status::success;
229
230
            return;
        }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
231
    } while (current < end && !stop);
232

233
234
    sim.clean();

Gauthier Quesnel's avatar
Gauthier Quesnel committed
235
    st = simulation_status::running_once_need_join;
236
}
237

238
239
void
editor::clear() noexcept
240
{
241
242
243
    observation_outputs.clear();
    observation_types.clear();
    observation_directory.clear();
244

245
246
    clusters.clear();
    sim.clear();
247

248
249
250
    std::fill(std::begin(clusters_mapper),
              std::end(clusters_mapper),
              undefined<cluster_id>());
251

252
253
254
    std::fill(std::begin(models_mapper),
              std::end(models_mapper),
              undefined<cluster_id>());
255

256
257
    top.clear();
}
258

259
260
cluster_id
editor::ancestor(const child_id child) const noexcept
261
{
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
    if (child.index() == 0) {
        const auto mdl_id = std::get<model_id>(child);
        auto parent = models_mapper[get_index(mdl_id)];
        auto ret = parent;

        while (parent != undefined<cluster_id>()) {
            ret = parent;
            parent = clusters_mapper[get_index(parent)];
        }

        return ret;
    } else {
        const auto gp_id = std::get<cluster_id>(child);
        auto parent = clusters_mapper[get_index(gp_id)];
        auto ret = parent;
277

278
279
280
281
282
283
284
        while (parent != undefined<cluster_id>()) {
            ret = parent;
            parent = clusters_mapper[get_index(parent)];
        }

        return ret;
    }
285
}
286

287
288
int
editor::get_top_group_ref(const child_id child) const noexcept
289
{
290
291
292
293
294
    const auto top_ref = ancestor(child);

    return top_ref == undefined<cluster_id>() ? top.get_index(child)
                                              : top.get_index(top_ref);
}
295

296
297
298
299
bool
editor::is_in_hierarchy(const cluster& group,
                        const cluster_id group_to_search) const noexcept
{
300
301
302
    if (clusters.get_id(group) == group_to_search) {
        log_w.log(7, "clusters.get_id(group) == group_to_search\n");
        return true;
303
304
    }

305
306
307
308
    // TODO: Derecursive this part of the function.
    for (const auto elem : group.children) {
        if (elem.index() == 1) {
            const auto id = std::get<cluster_id>(elem);
309

310
311
312
313
            if (id == group_to_search) {
                log_w.log(7, "id == group_to_search\n");
                return true;
            }
314

315
            if (const auto* gp = clusters.try_to_get(id); gp) {
316
                if (is_in_hierarchy(*gp, group_to_search)) {
317
318
319
320
321
                    log_w.log(7, "is_in_hierarchy = true\n");
                    return true;
                }
            }
        }
322
323
    }

324
325
    return false;
}
326

327
328
329
330
331
332
void
editor::group(const ImVector<int>& nodes) noexcept
{
    if (!clusters.can_alloc(1)) {
        log_w.log(5, "Fail to allocate a new group.");
        return;
333
334
    }

335
336
    /* First, move children models and groups from the current cluster into the
       newly allocated cluster. */
337

338
339
340
341
    auto& new_cluster = clusters.alloc();
    auto new_cluster_id = clusters.get_id(new_cluster);
    format(new_cluster.name, "Group {}", new_cluster_id);
    parent(new_cluster_id, undefined<cluster_id>());
342

343
344
    for (int i = 0, e = nodes.size(); i != e; ++i) {
        if (auto index = top.get_index(nodes[i]); index != not_found) {
345
            new_cluster.children.push_back(top.children[index].first);
346
            top.pop(index);
347
348
        }
    }
349

350
    top.emplace_back(new_cluster_id);
351

352
353
354
355
356
357
358
359
360
    for (const auto child : new_cluster.children) {
        if (child.index() == 0) {
            const auto id = std::get<model_id>(child);
            parent(id, new_cluster_id);
        } else {
            const auto id = std::get<cluster_id>(child);
            parent(id, new_cluster_id);
        }
    }
361

362
363
364
365
366
    /* For all input and output ports of the remaining models in the current
       cluster, we try to detect if the corresponding model is or is not in the
       same cluster. */

    for (const auto child : top.children) {
367
368
        if (child.first.index() == 0) {
            const auto child_id = std::get<model_id>(child.first);
369
370
371

            if (auto* model = sim.models.try_to_get(child_id); model) {
                sim.for_all_input_port(
372
373
374
                  *model,
                  [this, &new_cluster](const input_port& port,
                                       input_port_id /*pid*/) {
375
376
377
                      for (const auto id : port.connections) {
                          if (auto* p = this->sim.output_ports.try_to_get(id);
                              p)
378
                              if (is_in_hierarchy(new_cluster,
379
380
381
382
383
384
                                                  this->parent(p->model)))
                                  new_cluster.output_ports.emplace_back(id);
                      }
                  });

                sim.for_all_output_port(
385
386
387
                  *model,
                  [this, &new_cluster](const output_port& port,
                                       output_port_id /*pid*/) {
388
389
                      for (const auto id : port.connections) {
                          if (auto* p = this->sim.input_ports.try_to_get(id); p)
390
                              if (is_in_hierarchy(new_cluster,
391
392
393
394
395
396
                                                  this->parent(p->model)))
                                  new_cluster.input_ports.emplace_back(id);
                      }
                  });
            }
        } else {
397
            const auto child_id = std::get<cluster_id>(child.first);
398
399
400
401
402
403
404

            if (auto* group = clusters.try_to_get(child_id); group) {
                for (const auto id : group->input_ports) {
                    if (auto* p = sim.input_ports.try_to_get(id); p) {
                        for (const auto d_id : p->connections) {
                            if (auto* d_p = sim.output_ports.try_to_get(d_id);
                                d_p) {
405
                                if (is_in_hierarchy(new_cluster,
406
407
408
409
                                                    this->parent(d_p->model)))
                                    new_cluster.output_ports.emplace_back(d_id);
                            }
                        }
410
411
412
                    }
                }

413
414
415
416
417
                for (const auto id : group->output_ports) {
                    if (auto* p = sim.output_ports.try_to_get(id); p) {
                        for (const auto d_id : p->connections) {
                            if (auto* d_p = sim.input_ports.try_to_get(d_id);
                                d_p) {
418
                                if (is_in_hierarchy(new_cluster,
419
420
421
422
423
                                                    this->parent(d_p->model)))
                                    new_cluster.input_ports.emplace_back(d_id);
                            }
                        }
                    }
424
                }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
425
            }
426
        }
427
428
    }
}
429

430
431
432
433
void
editor::ungroup(const int node) noexcept
{
    const auto index = top.get_index(node);
434

435
436
437
438
    if (index == not_found) {
        log_w.log(5, "ungroup model not in top\n");
        return;
    }
439

440
    if (top.children[index].first.index() == 0) {
441
442
443
        log_w.log(5, "node is not a group\n");
        return;
    }
444

445
    auto* group =
446
      clusters.try_to_get(std::get<cluster_id>(top.children[index].first));
447
448
449
450
    if (!group) {
        log_w.log(5, "group does not exist\n");
        return;
    }
451

452
453
    const auto group_id = clusters.get_id(*group);
    top.pop(index);
454

455
456
457
    for (size_t i = 0, e = group->children.size(); i != e; ++i) {
        if (group->children[i].index() == 0) {
            const auto id = std::get<model_id>(group->children[i]);
458
            if (auto* mdl = sim.models.try_to_get(id); mdl) {
459
460
461
462
463
                parent(id, undefined<cluster_id>());
                top.emplace_back(group->children[i]);
            }
        } else {
            auto id = std::get<cluster_id>(group->children[i]);
464
            if (auto* gp = clusters.try_to_get(id); gp) {
465
466
467
468
469
                parent(id, undefined<cluster_id>());
                top.emplace_back(group->children[i]);
            }
        }
    }
470

471
472
473
    clusters.free(*group);
    parent(group_id, undefined<cluster_id>());
}
474

475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
void
editor::free_group(cluster& group) noexcept
{
    const auto group_id = clusters.get_id(group);

    for (const auto child : group.children) {
        if (child.index() == 0) {
            auto id = std::get<model_id>(child);
            models_mapper[get_index(id)] = undefined<cluster_id>();
            if (auto* mdl = sim.models.try_to_get(id); mdl) {
                log_w.log(7, "delete model %s\n", mdl->name.c_str());
                sim.deallocate(id);
            }
        } else {
            auto id = std::get<cluster_id>(child);
            clusters_mapper[get_index(id)] = undefined<cluster_id>();
            if (auto* gp = clusters.try_to_get(id); gp) {
                log_w.log(7, "delete group %s\n", gp->name.c_str());
                free_group(*gp);
            }
        }
    }
497

498
499
500
    parent(group_id, undefined<cluster_id>());
    clusters.free(group);
}
501

502
void
503
504
505
506
507
508
509
510
511
editor::free_children(const ImVector<int>& nodes) noexcept
{
    for (int i = 0, e = nodes.size(); i != e; ++i) {
        const auto index = top.get_index(nodes[i]);
        if (index == not_found)
            continue;

        const auto child = top.children[index];

512
513
        if (child.first.index() == 0) {
            const auto id = std::get<model_id>(child.first);
514
515
516
517
518
            if (auto* mdl = sim.models.try_to_get(id); mdl) {
                models_mapper[get_index(id)] = undefined<cluster_id>();
                log_w.log(7, "delete %s\n", mdl->name.c_str());
                parent(id, undefined<cluster_id>());
                sim.deallocate(id);
519
520
            }
        } else {
521
            const auto id = std::get<cluster_id>(child.first);
522
523
524
525
526
527
            if (auto* gp = clusters.try_to_get(id); gp) {
                clusters_mapper[get_index(id)] = undefined<cluster_id>();
                log_w.log(7, "delete group %s\n", gp->name.c_str());
                free_group(*gp);
            }
        }
528

529
530
531
        top.pop(index);
    }
}
532

533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
struct copier
{
    struct copy_model
    {
        copy_model() = default;

        copy_model(const model_id src_, const model_id dst_) noexcept
          : src(src_)
          , dst(dst_)
        {}

        model_id src, dst;
    };

    struct copy_cluster
    {
        copy_cluster() = default;

        copy_cluster(const cluster_id src_, const cluster_id dst_) noexcept
          : src(src_)
          , dst(dst_)
        {}

        cluster_id src, dst;
    };

    struct copy_input_port
    {
        copy_input_port() = default;

        copy_input_port(const input_port_id src_,
                        const input_port_id dst_) noexcept
          : src(src_)
          , dst(dst_)
        {}

        input_port_id src, dst;
    };

    struct copy_output_port
    {
        copy_output_port() = default;

        copy_output_port(const output_port_id src_,
                         const output_port_id dst_) noexcept
          : src(src_)
          , dst(dst_)
        {}

        output_port_id src, dst;
    };

    std::vector<copy_model> c_models;
    std::vector<copy_cluster> c_clusters;
    std::vector<copy_input_port> c_input_ports;
    std::vector<copy_output_port> c_output_ports;

    void sort() noexcept
    {
        std::sort(std::begin(c_models),
                  std::end(c_models),
                  [](const auto left, const auto right) {
                      return static_cast<u64>(left.src) <
                             static_cast<u64>(right.src);
                  });

        std::sort(std::begin(c_clusters),
                  std::end(c_clusters),
                  [](const auto left, const auto right) {
                      return static_cast<u64>(left.src) <
                             static_cast<u64>(right.src);
                  });

        std::sort(std::begin(c_input_ports),
                  std::end(c_input_ports),
                  [](const auto left, const auto right) {
                      return static_cast<u64>(left.src) <
                             static_cast<u64>(right.src);
                  });

        std::sort(std::begin(c_output_ports),
                  std::end(c_output_ports),
                  [](const auto left, const auto right) {
                      return static_cast<u64>(left.src) <
                             static_cast<u64>(right.src);
                  });
    }

    template<typename Container, typename T>
    static int get(const Container& c, const T src) noexcept
    {
        const typename Container::value_type val = { src, undefined<T>() };

        auto it = std::lower_bound(std::begin(c),
                                   std::end(c),
                                   val,
                                   [](const auto& left, const auto& right) {
                                       return static_cast<u64>(left.src) <
                                              static_cast<u64>(right.src);
                                   });

        return (it != std::end(c) &&
                static_cast<u64>(src) == static_cast<u64>(it->src))
                 ? static_cast<int>(std::distance(std::begin(c), it))
                 : not_found;
    }

    int get_model(const model_id src) const noexcept
    {
        return get(c_models, src);
    }

    int get_cluster(const cluster_id src) const noexcept
    {
        return get(c_clusters, src);
    }

    int get_input_port(const input_port_id src) const noexcept
    {
        return get(c_input_ports, src);
    }

    int get_output_port(const output_port_id src) const noexcept
    {
        return get(c_output_ports, src);
    }

    status copy(editor& ed,
                const size_t models_to_merge_with_top,
                const size_t clusters_to_merge_with_top)
    {
        auto& sim = ed.sim;

        for (size_t i = 0, e = std::size(c_models); i != e; ++i) {
            auto* mdl = sim.models.try_to_get(c_models[i].src);
            auto* mdl_id_dst = &c_models[i].dst;

            auto ret = sim.dispatch(
              mdl->type,
Gauthier Quesnel's avatar
Gauthier Quesnel committed
672
673
674
              [this, &sim, mdl, &mdl_id_dst]<typename DynamicsM>(
                DynamicsM& dynamics_models) -> status {
                  using Dynamics = typename DynamicsM::value_type;
675

Gauthier Quesnel's avatar
Gauthier Quesnel committed
676
677
                  irt_return_if_fail(dynamics_models.can_alloc(1),
                                     status::dynamics_not_enough_memory);
678

Gauthier Quesnel's avatar
Gauthier Quesnel committed
679
680
                  auto* dyn_ptr = dynamics_models.try_to_get(mdl->id);
                  irt_return_if_fail(dyn_ptr, status::dynamics_unknown_id);
681

Gauthier Quesnel's avatar
Gauthier Quesnel committed
682
683
                  auto& new_dyn = dynamics_models.alloc(*dyn_ptr);
                  auto new_dyn_id = dynamics_models.get_id(new_dyn);
684

Gauthier Quesnel's avatar
Gauthier Quesnel committed
685
686
687
688
                  if constexpr (is_detected_v<has_input_port_t, Dynamics>)
                      std::fill_n(new_dyn.x,
                                  std::size(new_dyn.x),
                                  static_cast<input_port_id>(0));
689

Gauthier Quesnel's avatar
Gauthier Quesnel committed
690
691
692
693
                  if constexpr (is_detected_v<has_output_port_t, Dynamics>)
                      std::fill_n(new_dyn.y,
                                  std::size(new_dyn.y),
                                  static_cast<output_port_id>(0));
694

Gauthier Quesnel's avatar
Gauthier Quesnel committed
695
696
                  irt_return_if_bad(
                    sim.alloc(new_dyn, new_dyn_id, mdl->name.c_str()));
697

Gauthier Quesnel's avatar
Gauthier Quesnel committed
698
                  *mdl_id_dst = new_dyn.id;
699

Gauthier Quesnel's avatar
Gauthier Quesnel committed
700
701
702
703
704
                  if constexpr (is_detected_v<has_input_port_t, Dynamics>)
                      for (size_t j = 0, ej = std::size(new_dyn.x); j != ej;
                           ++j)
                          this->c_input_ports.emplace_back(dyn_ptr->x[j],
                                                           new_dyn.x[j]);
705

Gauthier Quesnel's avatar
Gauthier Quesnel committed
706
707
708
709
710
                  if constexpr (is_detected_v<has_output_port_t, Dynamics>)
                      for (size_t j = 0, ej = std::size(new_dyn.y); j != ej;
                           ++j)
                          this->c_output_ports.emplace_back(dyn_ptr->y[j],
                                                            new_dyn.y[j]);
711

Gauthier Quesnel's avatar
Gauthier Quesnel committed
712
713
                  return status::success;
              });
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814

            irt_return_if_bad(ret);
        }

        for (size_t i = 0, e = std::size(c_clusters); i != e; ++i) {
            auto* gp_src = ed.clusters.try_to_get(c_clusters[i].src);
            auto& gp_dst = ed.clusters.alloc(*gp_src);
            c_clusters[i].dst = ed.clusters.get_id(gp_dst);
        }

        sort();

        for (size_t i = 0, e = std::size(c_clusters); i != e; ++i) {
            auto* gp_src = ed.clusters.try_to_get(c_clusters[i].src);
            auto* gp_dst = ed.clusters.try_to_get(c_clusters[i].dst);

            for (size_t j = 0, ej = gp_src->children.size(); j != ej; ++j) {
                if (gp_src->children[j].index() == 0) {
                    const auto id = std::get<model_id>(gp_src->children[j]);
                    const auto index = get_model(id);
                    gp_dst->children[j] = c_models[index].dst;
                } else {
                    const auto id = std::get<cluster_id>(gp_src->children[j]);
                    const auto index = get_cluster(id);
                    gp_dst->children[j] = c_clusters[index].dst;
                }
            }

            for (size_t j = 0, ej = gp_src->input_ports.size(); j != ej; ++j) {
                const auto index = get_input_port(gp_src->input_ports[j]);
                gp_dst->input_ports[j] = c_input_ports[index].dst;
            }

            for (size_t j = 0, ej = gp_src->output_ports.size(); j != ej; ++j) {
                const auto index = get_output_port(gp_src->output_ports[j]);
                gp_dst->output_ports[j] = c_output_ports[index].dst;
            }
        }

        for (size_t i = 0, e = std::size(c_input_ports); i != e; ++i) {
            const auto* src = sim.input_ports.try_to_get(c_input_ports[i].src);
            auto* dst = sim.input_ports.try_to_get(c_input_ports[i].dst);

            assert(dst->connections.empty());

            for (const auto port : src->connections) {
                const auto index = get_output_port(port);
                dst->connections.emplace_front(c_output_ports[index].dst);
            }
        }

        for (size_t i = 0, e = std::size(c_output_ports); i != e; ++i) {
            const auto* src =
              sim.output_ports.try_to_get(c_output_ports[i].src);
            auto* dst = sim.output_ports.try_to_get(c_output_ports[i].dst);

            assert(dst->connections.empty());

            for (const auto port : src->connections) {
                const auto index = get_input_port(port);
                dst->connections.emplace_front(c_input_ports[index].dst);
            }
        }

        for (size_t i = 0, e = std::size(c_models); i != e; ++i) {
            const auto parent_src = ed.parent(c_models[i].src);
            const auto index = get_cluster(parent_src);

            if (index == not_found)
                ed.parent(c_models[i].dst, parent_src);
            else
                ed.parent(c_models[i].dst, c_clusters[index].dst);
        }

        for (size_t i = 0, e = std::size(c_clusters); i != e; ++i) {
            const auto parent_src = ed.parent(c_clusters[i].src);
            const auto index = get_cluster(parent_src);

            if (index == not_found)
                ed.parent(c_models[i].dst, parent_src);
            else
                ed.parent(c_models[i].dst, c_clusters[index].dst);
        }

        /* Finally, merge clusters and models from user selection into the
           editor.top structure. */

        for (size_t i = 0; i != models_to_merge_with_top; ++i) {
            ed.top.emplace_back(c_models[i].dst);
            ed.parent(c_models[i].dst, undefined<cluster_id>());
        }

        for (size_t i = 0; i != clusters_to_merge_with_top; ++i) {
            ed.top.emplace_back(c_clusters[i].dst);
            ed.parent(c_clusters[i].dst, undefined<cluster_id>());
        }

        return status::success;
    }
};

815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
static void
compute_connection_distance(output_port& port, editor& ed, const float k)
{
    for_each(ed.sim.input_ports,
             port.connections,
             [&](const auto& i_port, const auto /*i_id*/) {
                 const auto v = ed.get_top_group_ref(port.model);
                 const auto u = ed.get_top_group_ref(i_port.model);

                 const float dx = ed.positions[v].x - ed.positions[u].x;
                 const float dy = ed.positions[v].y - ed.positions[u].y;
                 if (dx && dy) {
                     const float d2 = dx * dx / dy * dy;
                     const float coeff = std::sqrt(d2) / k;

                     ed.displacements[v].x -= dx * coeff;
                     ed.displacements[v].y -= dy * coeff;
                     ed.displacements[u].x += dx * coeff;
                     ed.displacements[u].y += dy * coeff;
                 }
             });
}

void
839
editor::compute_grid_layout() noexcept
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
{
    const auto size = length(top.children);
    const auto tmp = std::sqrt(size);
    const auto column = static_cast<int>(tmp);
    auto line = column;
    auto remaining = size - (column * line);

    while (remaining > column) {
        ++line;
        remaining -= column;
    }

    const auto panning = imnodes::EditorContextGetPanning();
    auto new_pos = panning;

    int elem = 0;

    for (int i = 0; i < column; ++i) {
Gauthier Quesnel's avatar
Gauthier Quesnel committed
858
        new_pos.y = panning.y + static_cast<float>(i) * grid_layout_y_distance;
859
        for (int j = 0; j < line; ++j) {
Gauthier Quesnel's avatar
Gauthier Quesnel committed
860
861
            new_pos.x =
              panning.x + static_cast<float>(j) * grid_layout_x_distance;
862
863
864
865
866
867
868
869
            imnodes::SetNodeScreenSpacePos(top.children[elem].second, new_pos);
            positions[elem].x = new_pos.x;
            positions[elem].y = new_pos.y;
            ++elem;
        }
    }

    new_pos.x = panning.x;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
870
    new_pos.y = panning.y + static_cast<float>(column) * grid_layout_y_distance;
871
    for (int j = 0; j < remaining; ++j) {
Gauthier Quesnel's avatar
Gauthier Quesnel committed
872
        new_pos.x = panning.x + static_cast<float>(j) * grid_layout_x_distance;
873
874
875
876
877
        imnodes::SetNodeScreenSpacePos(top.children[elem].second, new_pos);
        positions[elem].x = new_pos.x;
        positions[elem].y = new_pos.y;
        ++elem;
    }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
878
}
879

Gauthier Quesnel's avatar
Gauthier Quesnel committed
880
void
881
editor::compute_automatic_layout() noexcept
Gauthier Quesnel's avatar
Gauthier Quesnel committed
882
{
883
884
    /* See. Graph drawing by Forced-directed Placement by Thomas M. J.
       Fruchterman and Edward M. Reingold in Software--Pratice and
Gauthier Quesnel's avatar
Gauthier Quesnel committed
885
886
887
888
889
890
891
892
893
894
895
896
897
       Experience, Vol. 21(1 1), 1129-1164 (november 1991).
       */

    const auto size = length(top.children);
    const auto tmp = std::sqrt(size);
    const auto column = static_cast<int>(tmp);
    auto line = column;
    auto remaining = size - (column * line);

    while (remaining > column) {
        ++line;
        remaining -= column;
    }
898

Gauthier Quesnel's avatar
Gauthier Quesnel committed
899
900
    const float W = static_cast<float>(column) * automatic_layout_x_distance;
    const float L = line + (remaining > 0) ? automatic_layout_y_distance : 0.f;
901
902
903
904
    const float area = W * L;
    const float k_square = area / static_cast<float>(top.children.size());
    const float k = std::sqrt(k_square);

Gauthier Quesnel's avatar
Gauthier Quesnel committed
905
906
907
908
909
    // float t = 1.f - static_cast<float>(iteration) /
    //                   static_cast<float>(automatic_layout_iteration_limit);
    // t *= t;

    float t = 1.f - 1.f / static_cast<float>(automatic_layout_iteration_limit);
910

911
912
913
914
    for (int iteration = 0; iteration < automatic_layout_iteration_limit;
         ++iteration) {
        for (int i_v = 0; i_v < size; ++i_v) {
            const int v = i_v;
915

916
            displacements[v].x = displacements[v].y = 0.f;
917

918
919
            for (int i_u = 0; i_u < size; ++i_u) {
                const int u = i_u;
920

921
922
923
                if (u != v) {
                    const ImVec2 delta{ positions[v].x - positions[u].x,
                                        positions[v].y - positions[u].y };
924

925
926
927
                    if (delta.x && delta.y) {
                        const float d2 = delta.x * delta.x + delta.y * delta.y;
                        const float coeff = k_square / d2;
928

929
930
931
                        displacements[v].x += coeff * delta.x;
                        displacements[v].y += coeff * delta.y;
                    }
932
933
934
                }
            }
        }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
935

936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
        for (size_t i = 0, e = top.children.size(); i != e; ++i) {
            if (top.children[i].first.index() == 0) {
                const auto id = std::get<model_id>(top.children[i].first);
                if (const auto* mdl = sim.models.try_to_get(id); mdl) {
                    sim.for_all_output_port(
                      *mdl,
                      [this, k](output_port& port, output_port_id /*id*/) {
                          compute_connection_distance(port, *this, k);
                      });
                }
            } else {
                const auto id = std::get<cluster_id>(top.children[i].first);
                if (auto* gp = clusters.try_to_get(id); gp) {
                    for_each(
                      sim.output_ports,
                      gp->output_ports,
                      [this, k](output_port& port, output_port_id /*id*/) {
                          compute_connection_distance(port, *this, k);
                      });
                }
956
957
958
            }
        }

959
960
961
        auto sum = 0.f;
        for (int i_v = 0; i_v < size; ++i_v) {
            const int v = i_v;
962

963
964
965
            const float d2 = displacements[v].x * displacements[v].x +
                             displacements[v].y * displacements[v].y;
            const float d = std::sqrt(d2);
966

967
968
969
970
971
972
973
974
            if (d > t) {
                const float coeff = t / d;
                displacements[v].x *= coeff;
                displacements[v].y *= coeff;
                sum += t;
            } else {
                sum += d;
            }
975

976
977
            positions[v].x += displacements[v].x;
            positions[v].y += displacements[v].y;
978

979
980
            imnodes::SetNodeGridSpacePos(top.children[v].second, positions[v]);
        }
981
982
983
    }
}

984
985
status
editor::copy(const ImVector<int>& nodes) noexcept
986
{
987
988
989
990
991
992
993
994
995
996
997
    copier cp;

    std::vector<cluster_id> copy_stack;

    for (int i = 0, e = nodes.size(); i != e; ++i) {
        const auto index = top.get_index(nodes[i]);
        if (index == not_found)
            continue;

        const auto child = top.children[index];

998
999
        if (child.first.index() == 0) {
            const auto id = std::get<model_id>(child.first);
1000
1001
1002
            if (auto* mdl = sim.models.try_to_get(id); mdl)
                cp.c_models.emplace_back(id, undefined<model_id>());
        } else {
1003
            const auto id = std::get<cluster_id>(child.first);
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
            if (auto* gp = clusters.try_to_get(id); gp) {
                cp.c_clusters.emplace_back(id, undefined<cluster_id>());
                copy_stack.emplace_back(id);
            }
        }
    }

    const auto models_to_merge_with_top = std::size(cp.c_models);
    const auto clusters_to_merge_with_top = std::size(cp.c_clusters);

    while (!copy_stack.empty()) {
        const auto gp_id = copy_stack.back();
        copy_stack.pop_back();

        if (auto* gp = clusters.try_to_get(gp_id); gp) {
            for (const auto child : gp->children) {
                if (child.index() == 0) {
                    const auto id = std::get<model_id>(child);
                    if (auto* mdl = sim.models.try_to_get(id); mdl)
                        cp.c_models.emplace_back(id, undefined<model_id>());
                } else {
                    const auto id = std::get<cluster_id>(child);
                    if (auto* gp = clusters.try_to_get(id); gp) {
                        cp.c_clusters.emplace_back(id, undefined<cluster_id>());
                        copy_stack.emplace_back(id);
                    }
                }
            }
        }
    }

    return cp.copy(*this, models_to_merge_with_top, clusters_to_merge_with_top);
1036
}
1037

1038
1039
1040
status
editor::initialize(u32 id) noexcept
{
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1041
1042
    if (is_bad(sim.init(static_cast<unsigned>(kernel_model_cache),
                        static_cast<unsigned>(kernel_message_cache))) ||
1043
1044
1045
1046
        is_bad(observation_outputs.init(sim.models.capacity())) ||
        is_bad(observation_types.init(sim.models.capacity())) ||
        is_bad(clusters.init(sim.models.capacity())) ||
        is_bad(models_mapper.init(sim.models.capacity())) ||
1047
        is_bad(clusters_mapper.init(sim.models.capacity())) ||
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1048
        is_bad(top.init(static_cast<unsigned>(gui_node_cache))))
1049
        return status::gui_not_enough_memory;
1050

1051
1052
1053
1054
    positions.resize(sim.models.capacity() + clusters.capacity());
    displacements.resize(sim.models.capacity() + clusters.capacity(),
                         ImVec2{ 0.f, 0.f });

1055
    format(name, "Editor {}", id);
1056

1057
    initialized = true;
1058

1059
1060
    return status::success;
}
1061

1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
status
editor::add_lotka_volterra() noexcept
{
    if (!sim.adder_2_models.can_alloc(2) || !sim.mult_2_models.can_alloc(2) ||
        !sim.integrator_models.can_alloc(2) ||
        !sim.quantifier_models.can_alloc(2) || !sim.models.can_alloc(10))
        return status::simulation_not_enough_model;

    auto& sum_a = sim.adder_2_models.alloc();
    auto& sum_b = sim.adder_2_models.alloc();
    auto& product = sim.mult_2_models.alloc();
    auto& integrator_a = sim.integrator_models.alloc();
    auto& integrator_b = sim.integrator_models.alloc();
    auto& quantifier_a = sim.quantifier_models.alloc();
    auto& quantifier_b = sim.quantifier_models.alloc();

    integrator_a.default_current_value = 18.0;

    quantifier_a.default_adapt_state = irt::quantifier::adapt_state::possible;
    quantifier_a.default_zero_init_offset = true;
    quantifier_a.default_step_size = 0.01;
    quantifier_a.default_past_length = 3;

    integrator_b.default_current_value = 7.0;

    quantifier_b.default_adapt_state = irt::quantifier::adapt_state::possible;
    quantifier_b.default_zero_init_offset = true;
    quantifier_b.default_step_size = 0.01;
    quantifier_b.default_past_length = 3;

    product.default_input_coeffs[0] = 1.0;
    product.default_input_coeffs[1] = 1.0;
    sum_a.default_input_coeffs[0] = 2.0;
    sum_a.default_input_coeffs[1] = -0.4;
    sum_b.default_input_coeffs[0] = -1.0;
    sum_b.default_input_coeffs[1] = 0.1;

    irt_return_if_bad(
      sim.alloc(sum_a, sim.adder_2_models.get_id(sum_a), "sum_a"));
    irt_return_if_bad(
      sim.alloc(sum_b, sim.adder_2_models.get_id(sum_b), "sum_b"));
    irt_return_if_bad(
      sim.alloc(product, sim.mult_2_models.get_id(product), "prod"));
    irt_return_if_bad(sim.alloc(
      integrator_a, sim.integrator_models.get_id(integrator_a), "int_a"));
    irt_return_if_bad(sim.alloc(
      integrator_b, sim.integrator_models.get_id(integrator_b), "int_b"));
    irt_return_if_bad(sim.alloc(
      quantifier_a, sim.quantifier_models.get_id(quantifier_a), "qua_a"));
    irt_return_if_bad(sim.alloc(
      quantifier_b, sim.quantifier_models.get_id(quantifier_b), "qua_b"));

    irt_return_if_bad(sim.connect(sum_a.y[0], integrator_a.x[1]));
    irt_return_if_bad(sim.connect(sum_b.y[0], integrator_b.x[1]));

    irt_return_if_bad(sim.connect(integrator_a.y[0], sum_a.x[0]));
    irt_return_if_bad(sim.connect(integrator_b.y[0], sum_b.x[0]));

    irt_return_if_bad(sim.connect(integrator_a.y[0], product.x[0]));
    irt_return_if_bad(sim.connect(integrator_b.y[0], product.x[1]));

    irt_return_if_bad(sim.connect(product.y[0], sum_a.x[1]));
    irt_return_if_bad(sim.connect(product.y[0], sum_b.x[1]));

    irt_return_if_bad(sim.connect(quantifier_a.y[0], integrator_a.x[0]));
    irt_return_if_bad(sim.connect(quantifier_b.y[0], integrator_b.x[0]));
    irt_return_if_bad(sim.connect(integrator_a.y[0], quantifier_a.x[0]));
    irt_return_if_bad(sim.connect(integrator_b.y[0], quantifier_b.x[0]));

    top.emplace_back(sum_a.id);
    top.emplace_back(sum_b.id);
    top.emplace_back(product.id);
    top.emplace_back(integrator_a.id);
    top.emplace_back(integrator_b.id);
    top.emplace_back(quantifier_a.id);
    top.emplace_back(quantifier_b.id);

    parent(sum_a.id, undefined<cluster_id>());
    parent(sum_b.id, undefined<cluster_id>());
    parent(product.id, undefined<cluster_id>());
    parent(integrator_a.id, undefined<cluster_id>());
    parent(integrator_b.id, undefined<cluster_id>());
    parent(quantifier_a.id, undefined<cluster_id>());
    parent(quantifier_b.id, undefined<cluster_id>());

    return status::success;
}
1149

1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
status
editor::add_izhikevitch() noexcept
{
    if (!sim.constant_models.can_alloc(3) || !sim.adder_2_models.can_alloc(3) ||
        !sim.adder_4_models.can_alloc(1) || !sim.mult_2_models.can_alloc(1) ||
        !sim.integrator_models.can_alloc(2) ||
        !sim.quantifier_models.can_alloc(2) || !sim.cross_models.can_alloc(2) ||
        !sim.models.can_alloc(14))
        return status::simulation_not_enough_model;

    auto& constant = sim.constant_models.alloc();
    auto& constant2 = sim.constant_models.alloc();
    auto& constant3 = sim.constant_models.alloc();
    auto& sum_a = sim.adder_2_models.alloc();
    auto& sum_b = sim.adder_2_models.alloc();
    auto& sum_c = sim.adder_4_models.alloc();
    auto& sum_d = sim.adder_2_models.alloc();
    auto& product = sim.mult_2_models.alloc();
    auto& integrator_a = sim.integrator_models.alloc();
    auto& integrator_b = sim.integrator_models.alloc();
    auto& quantifier_a = sim.quantifier_models.alloc();
    auto& quantifier_b = sim.quantifier_models.alloc();
    auto& cross = sim.cross_models.alloc();
    auto& cross2 = sim.cross_models.alloc();

    double a = 0.2;
    double b = 2.0;
    double c = -56.0;
    double d = -16.0;
    double I = -99.0;
    double vt = 30.0;

    constant.default_value = 1.0;
    constant2.default_value = c;
    constant3.default_value = I;

    cross.default_threshold = vt;
    cross2.default_threshold = vt;

    integrator_a.default_current_value = 0.0;

    quantifier_a.default_adapt_state = irt::quantifier::adapt_state::possible;
    quantifier_a.default_zero_init_offset = true;
    quantifier_a.default_step_size = 0.01;
    quantifier_a.default_past_length = 3;

    integrator_b.default_current_value = 0.0;

    quantifier_b.default_adapt_state = irt::quantifier::adapt_state::possible;
    quantifier_b.default_zero_init_offset = true;
    quantifier_b.default_step_size = 0.01;
    quantifier_b.default_past_length = 3;

    product.default_input_coeffs[0] = 1.0;
    product.default_input_coeffs[1] = 1.0;

    sum_a.default_input_coeffs[0] = 1.0;
    sum_a.default_input_coeffs[1] = -1.0;
    sum_b.default_input_coeffs[0] = -a;
    sum_b.default_input_coeffs[1] = a * b;
    sum_c.default_input_coeffs[0] = 0.04;
    sum_c.default_input_coeffs[1] = 5.0;
    sum_c.default_input_coeffs[2] = 140.0;
    sum_c.default_input_coeffs[3] = 1.0;
    sum_d.default_input_coeffs[0] = 1.0;
    sum_d.default_input_coeffs[1] = d;

    irt_return_if_bad(
      sim.alloc(constant3, sim.constant_models.get_id(constant3), "tfun"));
    irt_return_if_bad(
      sim.alloc(constant, sim.constant_models.get_id(constant), "1.0"));
    irt_return_if_bad(
      sim.alloc(constant2, sim.constant_models.get_id(constant2), "-56.0"));

    irt_return_if_bad(
      sim.alloc(sum_a, sim.adder_2_models.get_id(sum_a), "sum_a"));
    irt_return_if_bad(
      sim.alloc(sum_b, sim.adder_2_models.get_id(sum_b), "sum_b"));
    irt_return_if_bad(
      sim.alloc(sum_c, sim.adder_4_models.get_id(sum_c), "sum_c"));
    irt_return_if_bad(
      sim.alloc(sum_d, sim.adder_2_models.get_id(sum_d), "sum_d"));

    irt_return_if_bad(
      sim.alloc(product, sim.mult_2_models.get_id(product), "prod"));
    irt_return_if_bad(sim.alloc(
      integrator_a, sim.integrator_models.get_id(integrator_a), "int_a"));
    irt_return_if_bad(sim.alloc(
      integrator_b, sim.integrator_models.get_id(integrator_b), "int_b"));
    irt_return_if_bad(sim.alloc(
      quantifier_a, sim.quantifier_models.get_id(quantifier_a), "qua_a"));
    irt_return_if_bad(sim.alloc(
      quantifier_b, sim.quantifier_models.get_id(quantifier_b), "qua_b"));
    irt_return_if_bad(
      sim.alloc(cross, sim.cross_models.get_id(cross), "cross"));
    irt_return_if_bad(
      sim.alloc(cross2, sim.cross_models.get_id(cross2), "cross2"));

    irt_return_if_bad(sim.connect(integrator_a.y[0], cross.x[0]));
    irt_return_if_bad(sim.connect(constant2.y[0], cross.x[1]));
    irt_return_if_bad(sim.connect(integrator_a.y[0], cross.x[2]));

    irt_return_if_bad(sim.connect(cross.y[0], quantifier_a.x[0]));
    irt_return_if_bad(sim.connect(cross.y[0], product.x[0]));
    irt_return_if_bad(sim.connect(cross.y[0], product.x[1]));
    irt_return_if_bad(sim.connect(product.y[0], sum_c.x[0]));
    irt_return_if_bad(sim.connect(cross.y[0], sum_c.x[1]));
    irt_return_if_bad(sim.connect(cross.y[0], sum_b.x[1]));

    irt_return_if_bad(sim.connect(constant.y[0], sum_c.x[2]));
    irt_return_if_bad(sim.connect(constant3.y[0], sum_c.x[3]));

    irt_return_if_bad(sim.connect(sum_c.y[0], sum_a.x[0]));
    irt_return_if_bad(sim.connect(integrator_b.y[0], sum_a.x[1]));
    irt_return_if_bad(sim.connect(cross2.y[0], sum_a.x[1]));
    irt_return_if_bad(sim.connect(sum_a.y[0], integrator_a.x[1]));
    irt_return_if_bad(sim.connect(cross.y[0], integrator_a.x[2]));
    irt_return_if_bad(sim.connect(quantifier_a.y[0], integrator_a.x[0]));

    irt_return_if_bad(sim.connect(cross2.y[0], quantifier_b.x[0]));
    irt_return_if_bad(sim.connect(cross2.y[0], sum_b.x[0]));
    irt_return_if_bad(sim.connect(quantifier_b.y[0], integrator_b.x[0]));
    irt_return_if_bad(sim.connect(sum_b.y[0], integrator_b.x[1]));

    irt_return_if_bad(sim.connect(cross2.y[0], integrator_b.x[2]));
    irt_return_if_bad(sim.connect(integrator_a.y[0], cross2.x[0]));
    irt_return_if_bad(sim.connect(integrator_b.y[0], cross2.x[2]));
    irt_return_if_bad(sim.connect(sum_d.y[0], cross2.x[1]));
    irt_return_if_bad(sim.connect(integrator_b.y[0], sum_d.x[0]));
    irt_return_if_bad(sim.connect(constant.y[0], sum_d.x[1]));

    top.emplace_back(constant.id);
    top.emplace_back(constant2.id);
    top.emplace_back(constant3.id);
    top.emplace_back(sum_a.id);
    top.emplace_back(sum_b.id);
    top.emplace_back(sum_c.id);
    top.emplace_back(sum_d.id);
    top.emplace_back(product.id);
    top.emplace_back(integrator_a.id);
    top.emplace_back(integrator_b.id);
    top.emplace_back(quantifier_a.id);
    top.emplace_back(quantifier_b.id);
    top.emplace_back(cross.id);
    top.emplace_back(cross2.id);

    parent(constant.id, undefined<cluster_id>());
    parent(constant2.id, undefined<cluster_id>());
    parent(constant3.id, undefined<cluster_id>());
    parent(sum_a.id, undefined<cluster_id>());
    parent(sum_b.id, undefined<cluster_id>());
    parent(sum_c.id, undefined<cluster_id>());
    parent(sum_d.id, undefined<cluster_id>());
    parent(product.id, undefined<cluster_id>());
    parent(integrator_a.id, undefined<cluster_id>());
    parent(integrator_b.id, undefined<cluster_id>());
    parent(quantifier_a.id, undefined<cluster_id>());
    parent(quantifier_b.id, undefined<cluster_id>());
    parent(cross.id, undefined<cluster_id>());
    parent(cross2.id, undefined<cluster_id>());

    return status::success;
}
1313

1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
static int
show_connection(output_port& port,
                output_port_id id,
                data_array<input_port, input_port_id>& input_ports,
                int connection_id)
{
    for_each(input_ports,
             port.connections,
             [&connection_id, id](const auto& /*i_port*/, const auto i_id) {
                 imnodes::Link(
                   connection_id++, editor::get_out(id), editor::get_in(i_id));
             });

    return connection_id;
}

1330
1331
1332
1333
1334
1335
void
editor::show_connections() noexcept
{
    int connection_id = 0;

    for (size_t i = 0, e = top.children.size(); i != e; ++i) {
1336
1337
        if (top.children[i].first.index() == 0) {
            const auto id = std::get<model_id>(top.children[i].first);
1338
1339
            if (const auto* mdl = sim.models.try_to_get(id); mdl) {
                sim.for_all_output_port(
1340
1341
1342
1343
1344
1345
1346
1347
                  *mdl,
                  [this, &connection_id](output_port& port,
                                         output_port_id /*id*/) {
                      connection_id =
                        show_connection(port,
                                        this->sim.output_ports.get_id(port),
                                        this->sim.input_ports,
                                        connection_id);
1348
1349
                  });
            }
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
        } else {
            const auto id = std::get<cluster_id>(top.children[i].first);
            if (auto* gp = clusters.try_to_get(id); gp) {
                for_each(sim.output_ports,
                         gp->output_ports,
                         [this, &connection_id](output_port& port,
                                                output_port_id /*id*/) {
                             connection_id = show_connection(
                               port,
                               this->sim.output_ports.get_id(port),
                               this->sim.input_ports,
                               connection_id);
                         });
            }
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
        }
    }
}

void
editor::show_model_cluster(cluster& mdl) noexcept
{
    {
        auto it = mdl.input_ports.begin();
        auto end = mdl.input_ports.end();
1374

1375
1376
1377
1378
        while (it != end) {
            if (auto* port = sim.input_ports.try_to_get(*it); port) {
                imnodes::BeginInputAttribute(get_in(*it));
                ImGui::TextUnformatted(port->name.c_str());
1379
                imnodes::EndAttribute();