node-editor.cpp 96.3 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
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 };
Gauthier Quesnel's avatar
Gauthier Quesnel committed
29
static ImVec4 gui_model_transition_color{ .27f, .54f, .54f, 1.f };
Gauthier Quesnel's avatar
Gauthier Quesnel committed
30
31
32
33
static ImVec4 gui_cluster_color{ .27f, .54f, .27f, 1.f };

static ImU32 gui_hovered_model_color;
static ImU32 gui_selected_model_color;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
34
35
36
static ImU32 gui_hovered_model_transition_color;
static ImU32 gui_selected_model_transition_color;
static ImU32 gui_hovered_cluster_color;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
37
38
39
40
41
42
43
44
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
45
46
static ImVec4
operator*(const ImVec4& lhs, const float rhs) noexcept
Gauthier Quesnel's avatar
Gauthier Quesnel committed
47
48
49
50
{
    return ImVec4(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs, lhs.w * rhs);
}

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

Gauthier Quesnel's avatar
Gauthier Quesnel committed
59
60
61
62
63
    gui_hovered_model_transition_color =
      ImGui::ColorConvertFloat4ToU32(gui_model_transition_color * 1.25f);
    gui_selected_model_transition_color =
      ImGui::ColorConvertFloat4ToU32(gui_model_transition_color * 1.5f);

Gauthier Quesnel's avatar
Gauthier Quesnel committed
64
65
66
67
68
69
    gui_hovered_cluster_color =
      ImGui::ColorConvertFloat4ToU32(gui_cluster_color * 1.25f);
    gui_selected_cluster_color =
      ImGui::ColorConvertFloat4ToU32(gui_cluster_color * 1.5f);
}

70
71
72
template<size_t N, typename... Args>
void
format(small_string<N>& str, const char* fmt, const Args&... args)
73
{
74
75
    auto ret = fmt::format_to_n(str.begin(), N, fmt, args...);
    str.size(ret.size);
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
121
122
123
124
125
126
127
128
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();
            }
        }
    }
}

129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
static const char* dynamics_type_names[] = { "none",
                                             "qss1_integrator",
                                             "qss1_multiplier",
                                             "qss1_cross",
                                             "qss1_power",
                                             "qss1_square",
                                             "qss1_sum_2",
                                             "qss1_sum_3",
                                             "qss1_sum_4",
                                             "qss1_wsum_2",
                                             "qss1_wsum_3",
                                             "qss1_wsum_4",
                                             "qss2_integrator",
                                             "qss2_multiplier",
                                             "qss2_cross",
                                             "qss2_power",
                                             "qss2_square",
                                             "qss2_sum_2",
                                             "qss2_sum_3",
                                             "qss2_sum_4",
                                             "qss2_wsum_2",
                                             "qss2_wsum_3",
                                             "qss2_wsum_4",
                                             "qss3_integrator",
                                             "qss3_multiplier",
                                             "qss3_cross",
                                             "qss3_power",
                                             "qss3_square",
                                             "qss3_sum_2",
                                             "qss3_sum_3",
                                             "qss3_sum_4",
                                             "qss3_wsum_2",
                                             "qss3_wsum_3",
                                             "qss3_wsum_4",
                                             "integrator",
                                             "quantifier",
                                             "adder_2",
                                             "adder_3",
                                             "adder_4",
                                             "mult_2",
                                             "mult_3",
                                             "mult_4",
                                             "counter",
                                             "generator",
                                             "constant",
                                             "cross",
                                             "time_func",
                                             "accumulator_2",
                                             "flow" };

179
180
static_assert(std::size(dynamics_type_names) ==
              static_cast<sz>(dynamics_type_size()));
181

182
183
static window_logger log_w;
static data_array<editor, editor_id> editors;
184

185
186
void
editor::clear() noexcept
187
{
188
189
190
    observation_outputs.clear();
    observation_types.clear();
    observation_directory.clear();
191

192
193
    clusters.clear();
    sim.clear();
194

195
196
197
    std::fill(std::begin(clusters_mapper),
              std::end(clusters_mapper),
              undefined<cluster_id>());
198

199
200
201
    std::fill(std::begin(models_mapper),
              std::end(models_mapper),
              undefined<cluster_id>());
202

203
204
    top.clear();
}
205

206
207
cluster_id
editor::ancestor(const child_id child) const noexcept
208
{
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
    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;
224

225
226
227
228
229
230
231
        while (parent != undefined<cluster_id>()) {
            ret = parent;
            parent = clusters_mapper[get_index(parent)];
        }

        return ret;
    }
232
}
233

234
235
int
editor::get_top_group_ref(const child_id child) const noexcept
236
{
237
238
239
240
241
    const auto top_ref = ancestor(child);

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

243
244
245
246
bool
editor::is_in_hierarchy(const cluster& group,
                        const cluster_id group_to_search) const noexcept
{
247
248
249
    if (clusters.get_id(group) == group_to_search) {
        log_w.log(7, "clusters.get_id(group) == group_to_search\n");
        return true;
250
251
    }

252
253
254
255
    // 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);
256

257
258
259
260
            if (id == group_to_search) {
                log_w.log(7, "id == group_to_search\n");
                return true;
            }
261

262
            if (const auto* gp = clusters.try_to_get(id); gp) {
263
                if (is_in_hierarchy(*gp, group_to_search)) {
264
265
266
267
268
                    log_w.log(7, "is_in_hierarchy = true\n");
                    return true;
                }
            }
        }
269
270
    }

271
272
    return false;
}
273

274
275
276
277
278
279
void
editor::group(const ImVector<int>& nodes) noexcept
{
    if (!clusters.can_alloc(1)) {
        log_w.log(5, "Fail to allocate a new group.");
        return;
280
281
    }

282
283
    /* First, move children models and groups from the current cluster into the
       newly allocated cluster. */
284

285
286
287
288
    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>());
289

290
291
    for (int i = 0, e = nodes.size(); i != e; ++i) {
        if (auto index = top.get_index(nodes[i]); index != not_found) {
292
            new_cluster.children.push_back(top.children[index].first);
293
            top.pop(index);
294
295
        }
    }
296

297
    top.emplace_back(new_cluster_id);
298

299
300
301
302
303
304
305
306
307
    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);
        }
    }
308

309
310
311
312
313
    /* 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) {
314
315
        if (child.first.index() == 0) {
            const auto child_id = std::get<model_id>(child.first);
316
317
318

            if (auto* model = sim.models.try_to_get(child_id); model) {
                sim.for_all_input_port(
319
320
321
                  *model,
                  [this, &new_cluster](const input_port& port,
                                       input_port_id /*pid*/) {
322
323
324
                      for (const auto id : port.connections) {
                          if (auto* p = this->sim.output_ports.try_to_get(id);
                              p)
325
                              if (is_in_hierarchy(new_cluster,
326
327
328
329
330
331
                                                  this->parent(p->model)))
                                  new_cluster.output_ports.emplace_back(id);
                      }
                  });

                sim.for_all_output_port(
332
333
334
                  *model,
                  [this, &new_cluster](const output_port& port,
                                       output_port_id /*pid*/) {
335
336
                      for (const auto id : port.connections) {
                          if (auto* p = this->sim.input_ports.try_to_get(id); p)
337
                              if (is_in_hierarchy(new_cluster,
338
339
340
341
342
343
                                                  this->parent(p->model)))
                                  new_cluster.input_ports.emplace_back(id);
                      }
                  });
            }
        } else {
344
            const auto child_id = std::get<cluster_id>(child.first);
345
346
347
348
349
350
351

            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) {
352
                                if (is_in_hierarchy(new_cluster,
353
354
355
356
                                                    this->parent(d_p->model)))
                                    new_cluster.output_ports.emplace_back(d_id);
                            }
                        }
357
358
359
                    }
                }

360
361
362
363
364
                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) {
365
                                if (is_in_hierarchy(new_cluster,
366
367
368
369
370
                                                    this->parent(d_p->model)))
                                    new_cluster.input_ports.emplace_back(d_id);
                            }
                        }
                    }
371
                }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
372
            }
373
        }
374
375
    }
}
376

377
378
379
380
void
editor::ungroup(const int node) noexcept
{
    const auto index = top.get_index(node);
381

382
383
384
385
    if (index == not_found) {
        log_w.log(5, "ungroup model not in top\n");
        return;
    }
386

387
    if (top.children[index].first.index() == 0) {
388
389
390
        log_w.log(5, "node is not a group\n");
        return;
    }
391

392
    auto* group =
393
      clusters.try_to_get(std::get<cluster_id>(top.children[index].first));
394
395
396
397
    if (!group) {
        log_w.log(5, "group does not exist\n");
        return;
    }
398

399
400
    const auto group_id = clusters.get_id(*group);
    top.pop(index);
401

402
403
404
    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]);
405
            if (auto* mdl = sim.models.try_to_get(id); mdl) {
406
407
408
409
410
                parent(id, undefined<cluster_id>());
                top.emplace_back(group->children[i]);
            }
        } else {
            auto id = std::get<cluster_id>(group->children[i]);
411
            if (auto* gp = clusters.try_to_get(id); gp) {
412
413
414
415
416
                parent(id, undefined<cluster_id>());
                top.emplace_back(group->children[i]);
            }
        }
    }
417

418
419
420
    clusters.free(*group);
    parent(group_id, undefined<cluster_id>());
}
421

422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
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);
            }
        }
    }
444

445
446
447
    parent(group_id, undefined<cluster_id>());
    clusters.free(group);
}
448

449
void
450
451
452
453
454
455
456
457
458
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];

459
460
        if (child.first.index() == 0) {
            const auto id = std::get<model_id>(child.first);
461
462
463
464
465
            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);
466
467
            }
        } else {
468
            const auto id = std::get<cluster_id>(child.first);
469
470
471
472
473
474
            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);
            }
        }
475

476
477
478
        top.pop(index);
    }
}
479

480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
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
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
619
620
621
              [this, &sim, mdl, &mdl_id_dst]<typename DynamicsM>(
                DynamicsM& dynamics_models) -> status {
                  using Dynamics = typename DynamicsM::value_type;
622

Gauthier Quesnel's avatar
Gauthier Quesnel committed
623
624
                  irt_return_if_fail(dynamics_models.can_alloc(1),
                                     status::dynamics_not_enough_memory);
625

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

Gauthier Quesnel's avatar
Gauthier Quesnel committed
629
630
                  auto& new_dyn = dynamics_models.alloc(*dyn_ptr);
                  auto new_dyn_id = dynamics_models.get_id(new_dyn);
631

Gauthier Quesnel's avatar
Gauthier Quesnel committed
632
633
634
635
                  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));
636

Gauthier Quesnel's avatar
Gauthier Quesnel committed
637
638
639
640
                  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));
641

Gauthier Quesnel's avatar
Gauthier Quesnel committed
642
643
                  irt_return_if_bad(
                    sim.alloc(new_dyn, new_dyn_id, mdl->name.c_str()));
644

Gauthier Quesnel's avatar
Gauthier Quesnel committed
645
                  *mdl_id_dst = new_dyn.id;
646

Gauthier Quesnel's avatar
Gauthier Quesnel committed
647
648
649
650
651
                  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]);
652

Gauthier Quesnel's avatar
Gauthier Quesnel committed
653
654
655
656
657
                  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]);
658

Gauthier Quesnel's avatar
Gauthier Quesnel committed
659
660
                  return status::success;
              });
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
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

            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;
    }
};

762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
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
786
editor::compute_grid_layout() noexcept
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
{
    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
805
        new_pos.y = panning.y + static_cast<float>(i) * grid_layout_y_distance;
806
        for (int j = 0; j < line; ++j) {
Gauthier Quesnel's avatar
Gauthier Quesnel committed
807
808
            new_pos.x =
              panning.x + static_cast<float>(j) * grid_layout_x_distance;
809
810
811
812
813
814
815
816
            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
817
    new_pos.y = panning.y + static_cast<float>(column) * grid_layout_y_distance;
818
    for (int j = 0; j < remaining; ++j) {
Gauthier Quesnel's avatar
Gauthier Quesnel committed
819
        new_pos.x = panning.x + static_cast<float>(j) * grid_layout_x_distance;
820
821
822
823
824
        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
825
}
826

Gauthier Quesnel's avatar
Gauthier Quesnel committed
827
void
828
editor::compute_automatic_layout() noexcept
Gauthier Quesnel's avatar
Gauthier Quesnel committed
829
{
830
831
    /* 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
832
833
834
835
836
837
838
839
840
841
842
843
844
       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;
    }
845

Gauthier Quesnel's avatar
Gauthier Quesnel committed
846
847
    const float W = static_cast<float>(column) * automatic_layout_x_distance;
    const float L = line + (remaining > 0) ? automatic_layout_y_distance : 0.f;
848
849
850
851
    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
852
853
854
855
856
    // 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);
857

858
859
860
861
    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;
862

863
            displacements[v].x = displacements[v].y = 0.f;
864

865
866
            for (int i_u = 0; i_u < size; ++i_u) {
                const int u = i_u;
867

868
869
870
                if (u != v) {
                    const ImVec2 delta{ positions[v].x - positions[u].x,
                                        positions[v].y - positions[u].y };
871

872
873
874
                    if (delta.x && delta.y) {
                        const float d2 = delta.x * delta.x + delta.y * delta.y;
                        const float coeff = k_square / d2;
875

876
877
878
                        displacements[v].x += coeff * delta.x;
                        displacements[v].y += coeff * delta.y;
                    }
879
880
881
                }
            }
        }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
882

883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
        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);
                      });
                }
903
904
905
            }
        }

906
907
908
        auto sum = 0.f;
        for (int i_v = 0; i_v < size; ++i_v) {
            const int v = i_v;
909

910
911
912
            const float d2 = displacements[v].x * displacements[v].x +
                             displacements[v].y * displacements[v].y;
            const float d = std::sqrt(d2);
913

914
915
916
917
918
919
920
921
            if (d > t) {
                const float coeff = t / d;
                displacements[v].x *= coeff;
                displacements[v].y *= coeff;
                sum += t;
            } else {
                sum += d;
            }
922

923
924
            positions[v].x += displacements[v].x;
            positions[v].y += displacements[v].y;
925

926
927
            imnodes::SetNodeGridSpacePos(top.children[v].second, positions[v]);
        }
928
929
930
    }
}

931
932
status
editor::copy(const ImVector<int>& nodes) noexcept
933
{
934
935
936
937
938
939
940
941
942
943
944
    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];

945
946
        if (child.first.index() == 0) {
            const auto id = std::get<model_id>(child.first);
947
948
949
            if (auto* mdl = sim.models.try_to_get(id); mdl)
                cp.c_models.emplace_back(id, undefined<model_id>());
        } else {
950
            const auto id = std::get<cluster_id>(child.first);
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
            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);
983
}
984

985
986
987
status
editor::initialize(u32 id) noexcept
{
Gauthier Quesnel's avatar
Gauthier Quesnel committed
988
989
    if (is_bad(sim.init(static_cast<unsigned>(kernel_model_cache),
                        static_cast<unsigned>(kernel_message_cache))) ||
990
991
992
993
        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())) ||
994
        is_bad(clusters_mapper.init(sim.models.capacity())) ||
Gauthier Quesnel's avatar
Gauthier Quesnel committed
995
        is_bad(models_make_transition.init(sim.models.capacity())) ||
Gauthier Quesnel's avatar
Gauthier Quesnel committed
996
        is_bad(top.init(static_cast<unsigned>(gui_node_cache))))
997
        return status::gui_not_enough_memory;
998

999
1000
1001
1002
    positions.resize(sim.models.capacity() + clusters.capacity());
    displacements.resize(sim.models.capacity() + clusters.capacity(),
                         ImVec2{ 0.f, 0.f });

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1003
1004
    std::fill_n(models_make_transition.data(), sim.models.capacity(), false);

1005
    format(name, "Editor {}", id);
1006

1007
    initialized = true;
1008

1009
1010
    return status::success;
}
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
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
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
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;
}
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
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
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;
}
1263

1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
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;
}

1280
1281
1282
1283
1284
1285
void
editor::show_connections() noexcept
{
    int connection_id = 0;

    for (size_t i = 0, e = top.children.size(); i != e; ++i) {
1286
1287
        if (top.children[i].first.index() == 0) {
            const auto id = std::get<model_id>(top.children[i].first);
1288
1289
            if (const auto* mdl = sim.models.try_to_get(id); mdl) {
                sim.for_all_output_port(
1290
1291
1292
1293
1294
1295
1296
1297
                  *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);
1298
1299
                  });
            }
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
        } 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);
                         });
            }
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
        }
    }
}

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

1325
1326
1327
1328
        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());
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1329
                imnodes::EndInputAttribute();
1330
1331
1332
                ++it;
            } else {
                it = mdl.input_ports.erase(it);
1333
            }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1334
        }
1335
1336
    }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1337
    {
1338
1339
        auto it = mdl.output_ports.begin();
        auto end = mdl.output_ports.end();
1340

1341
1342
1343
1344
        while (it != end) {
            if (auto* port = sim.output_ports.try_to_get(*it); port) {
                imnodes::BeginOutputAttribute(get_out(*it));
                ImGui::TextUnformatted(port->name.c_str());
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1345
                imnodes::EndOutputAttribute();
1346
1347
1348
1349
                ++it;
            } else {
                it = mdl.output_ports.erase(it);
            }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1350
        }
1351
1352
    }
}
1353

1354
static const char* str_error[] = { "Error" };
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1355
1356
1357
1358
1359
1360
1361
static const char* str_empty[] = { "" };
static const char* str_integrator[] = { "x-dot", "reset" };
static const char* str_adaptative_integrator[] = { "quanta", "x-dot", "reset" };
static const char* str_in_1[] = { "in" };
static const char* str_in_2[] = { "in-1", "in-2" };
static const char* str_in_3[] = { "in-1", "in-2", "in-3" };
static const char* str_in_4[] = { "in-1", "in-2", "in-3", "in-4" };
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1362
static const char* str_value_if_else[] = { "value", "if", "else", "threshold" };
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1363
1364
1365
1366
1367
static const char* str_in_2_nb_2[] = { "in-1", "in-2", "nb-1", "nb-2" };

template<typename Dynamics>
static constexpr const char**
get_input_port_names()
1368
{
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1369
1370
    if constexpr (std::is_same_v<Dynamics, none>)
        return str_empty;
1371
1372

    if constexpr (std::is_same_v<Dynamics, qss1_integrator> ||
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1373
1374
                  std::is_same_v<Dynamics, qss2_integrator> ||
                  std::is_same_v<Dynamics, qss3_integrator>)
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1375
        return str_integrator;
1376

1377
    if constexpr (std::is_same_v<Dynamics, qss1_multiplier> ||
1378
1379
1380
1381
1382
                  std::is_same_v<Dynamics, qss1_sum_2> ||
                  std::is_same_v<Dynamics, qss1_wsum_2> ||
                  std::is_same_v<Dynamics, qss2_multiplier> ||
                  std::is_same_v<Dynamics, qss2_sum_2> ||
                  std::is_same_v<Dynamics, qss2_wsum_2> ||
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1383
1384
1385
                  std::is_same_v<Dynamics, qss3_multiplier> ||
                  std::is_same_v<Dynamics, qss3_sum_2> ||
                  std::is_same_v<Dynamics, qss3_wsum_2> ||
1386
1387
                  std::is_same_v<Dynamics, adder_2> ||
                  std::is_same_v<Dynamics, mult_2>)
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1388
        return str_in_2;
1389
1390
1391