-
Notifications
You must be signed in to change notification settings - Fork 297
/
Visualization.cpp
1940 lines (1689 loc) · 77.2 KB
/
Visualization.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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
121
122
123
124
125
126
127
128
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
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
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
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
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
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
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
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of OpenModelica.
*
* Copyright (c) 1998-CurrentYear, Open Source Modelica Consortium (OSMC),
* c/o Linköpings universitet, Department of Computer and Information Science,
* SE-58183 Linköping, Sweden.
*
* All rights reserved.
*
* THIS PROGRAM IS PROVIDED UNDER THE TERMS OF GPL VERSION 3 LICENSE OR
* THIS OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2.
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3,
* ACCORDING TO RECIPIENTS CHOICE.
*
* The OpenModelica software and the Open Source Modelica
* Consortium (OSMC) Public License (OSMC-PL) are obtained
* from OSMC, either from the above address,
* from the URLs: http://www.ida.liu.se/projects/OpenModelica or
* http://www.openmodelica.org, and in the OpenModelica distribution.
* GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html.
*
* This program is distributed WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH
* IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL.
*
* See the full OSMC Public License conditions for more details.
*
*/
/*
* @author Volker Waurich <volker.waurich@tu-dresden.de>
*/
#include "Visualization.h"
#if (QT_VERSION < QT_VERSION_CHECK(5, 2, 0))
#include <QGLWidget>
#endif
#include <QOpenGLContext> // must be included before OSG headers
#include <osg/GL> // for having direct access to glClear()
#include <osg/Array>
#include <osg/Drawable>
#include <osg/Shape>
#include <osg/ShapeDrawable>
#include <osg/StateAttribute>
#include <osg/Texture2D>
#include <osgDB/Options>
#include <osgDB/ReadFile>
#include <osgGA/OrbitManipulator>
#include <osgUtil/CullVisitor>
#include <OpenThreads/ScopedLock>
#include <algorithm>
#include <cstdint>
#include <cstring>
#include <functional>
#include <limits>
#include <map>
#include <unordered_map>
#include <vector>
// Specializations required for std::map and std::unordered_map to work with const std::reference_wrapper as keys
template<typename T>
struct std::hash<const std::reference_wrapper<T>> {
std::size_t operator()(const std::reference_wrapper<T>& ref) const {
return reinterpret_cast<std::uintptr_t>(&ref.get());
}
};
template<typename T>
struct std::less<const std::reference_wrapper<T>> {
bool operator()(const std::reference_wrapper<T>& lhs, const std::reference_wrapper<T>& rhs) const {
return &lhs.get() < &rhs.get();
}
};
template<typename T>
struct std::equal_to<const std::reference_wrapper<T>> {
bool operator()(const std::reference_wrapper<T>& lhs, const std::reference_wrapper<T>& rhs) const {
return &lhs.get() == &rhs.get();
}
};
// Definition required for static constexpr members being ODR-used
constexpr char VectorObject::kAutoScaleRenderBinName[];
OMVisualBase::OMVisualBase(VisualizationAbstract* visualization, const std::string& modelFile, const std::string& path)
: _modelFile(modelFile),
_path(path),
_xmlFileName(assembleXMLFileName(modelFile, path)),
_updateVisitor(),
_visualization(visualization),
_shapes(),
_vectors()
{
}
const std::string OMVisualBase::getModelFile() const
{
return _modelFile;
}
const std::string OMVisualBase::getPath() const
{
return _path;
}
const std::string OMVisualBase::getXMLFileName() const
{
return _xmlFileName;
}
/*!
* \brief OMVisualBase::getVisualizerObjects
* get a container of AbstractVisualizerObject
* \return all the visualizers
*/
std::vector<std::reference_wrapper<AbstractVisualizerObject>> OMVisualBase::getVisualizerObjects()
{
std::vector<std::reference_wrapper<AbstractVisualizerObject>> visualizers;
visualizers.reserve(_shapes.size() + _vectors.size());
for (ShapeObject& shape : _shapes) {
visualizers.push_back(shape);
}
for (VectorObject& vector : _vectors) {
visualizers.push_back(vector);
}
return visualizers;
}
/*!
* \brief OMVisualBase::getVisualizerObjectByIdx
* get the AbstractVisualizerObject with the same visualizerIdx
* \param the index of the visualizer
* \return the selected visualizer
*/
AbstractVisualizerObject* OMVisualBase::getVisualizerObjectByIdx(const std::size_t visualizerIdx)
{
std::vector<std::reference_wrapper<AbstractVisualizerObject>> visualizers = getVisualizerObjects();
if (visualizerIdx < visualizers.size()) {
return &visualizers.at(visualizerIdx).get();
}
return nullptr;
}
/*!
* \brief OMVisualBase::getVisualizerObjectByID
* get the AbstractVisualizerObject with the same visualizerID
* \param the name of the visualizer
* \return the selected visualizer
*/
AbstractVisualizerObject* OMVisualBase::getVisualizerObjectByID(const std::string& visualizerID)
{
for (AbstractVisualizerObject& visualizer : getVisualizerObjects()) {
if (visualizer._id == visualizerID) {
return &visualizer;
}
}
return nullptr;
}
/*!
* \brief OMVisualBase::getVisualizerObjectIndexByID
* get the index of the AbstractVisualizerObject with the same visualizerID
* \param the name of the visualizer
* \return the selected visualizer index
*/
int OMVisualBase::getVisualizerObjectIndexByID(const std::string& visualizerID)
{
int i = 0;
for (AbstractVisualizerObject& visualizer : getVisualizerObjects()) {
if (visualizer._id == visualizerID) {
return i;
}
i++;
}
return -1;
}
void OMVisualBase::updateVisualizer(const std::string& visualizerName, const bool changeMaterialProperties)
{
int visualizerIdx = getVisualizerObjectIndexByID(visualizerName);
AbstractVisualizerObject* visualizer = getVisualizerObjectByID(visualizerName);
osg::ref_ptr<osg::Node> child = _visualization->getOMVisScene()->getScene().getRootNode()->getChild(visualizerIdx);
_updateVisitor._visualizer = visualizer;
_updateVisitor._changeMaterialProperties = changeMaterialProperties;
child->accept(_updateVisitor);
}
void OMVisualBase::modifyVisualizer(const std::string& visualizerName, const bool changeMaterialProperties)
{
int visualizerIdx = getVisualizerObjectIndexByID(visualizerName);
AbstractVisualizerObject* visualizer = getVisualizerObjectByID(visualizerName);
osg::ref_ptr<osg::Node> child = _visualization->getOMVisScene()->getScene().getRootNode()->getChild(visualizerIdx);
_updateVisitor._visualizer = visualizer;
_updateVisitor._changeMaterialProperties = changeMaterialProperties;
visualizer->setStateSetAction(StateSetAction::modify);
child->accept(_updateVisitor);
visualizer->setStateSetAction(StateSetAction::update);
}
void OMVisualBase::updateVisualizer(AbstractVisualizerObject* visualizer, const bool changeMaterialProperties) {
_updateVisitor._visualizer = visualizer;
_updateVisitor._changeMaterialProperties = changeMaterialProperties;
visualizer->getTransformNode()->accept(_updateVisitor);
}
void OMVisualBase::modifyVisualizer(AbstractVisualizerObject* visualizer, const bool changeMaterialProperties) {
_updateVisitor._visualizer = visualizer;
_updateVisitor._changeMaterialProperties = changeMaterialProperties;
visualizer->setStateSetAction(StateSetAction::modify);
visualizer->getTransformNode()->accept(_updateVisitor);
visualizer->setStateSetAction(StateSetAction::update);
}
void OMVisualBase::updateVisualizer(AbstractVisualizerObject& visualizer, const bool changeMaterialProperties) {
_updateVisitor._visualizer = &visualizer;
_updateVisitor._changeMaterialProperties = changeMaterialProperties;
visualizer.getTransformNode()->accept(_updateVisitor);
}
void OMVisualBase::modifyVisualizer(AbstractVisualizerObject& visualizer, const bool changeMaterialProperties) {
_updateVisitor._visualizer = &visualizer;
_updateVisitor._changeMaterialProperties = changeMaterialProperties;
visualizer.setStateSetAction(StateSetAction::modify);
visualizer.getTransformNode()->accept(_updateVisitor);
visualizer.setStateSetAction(StateSetAction::update);
}
void OMVisualBase::initVisObjects()
{
if (!fileExists(_xmlFileName)) {
MessagesWidget::instance()->addGUIMessage(MessageItem(MessageItem::Modelica,
QString(QObject::tr("Could not find the visual XML file %1."))
.arg(_xmlFileName.c_str()),
Helper::scriptingKind, Helper::errorLevel));
return;
}
QFile file(QString::fromStdString(_xmlFileName));
if (!file.open(QIODevice::ReadOnly)) {
MessagesWidget::instance()->addGUIMessage(MessageItem(MessageItem::Modelica,
QString(QObject::tr("Could not open the visual XML file %1."))
.arg(_xmlFileName.c_str()),
Helper::scriptingKind, Helper::errorLevel));
return;
}
QByteArray buffer = file.readAll();
file.close();
rapidxml::xml_document<> xmlDoc;
xmlDoc.parse<0>(buffer.data());
rapidxml::xml_node<>* rootNode = xmlDoc.first_node();
rapidxml::xml_node<>* expNode;
for (rapidxml::xml_node<>* shapeNode = rootNode->first_node("shape"); shapeNode; shapeNode = shapeNode->next_sibling("shape"))
{
ShapeObject shape; // Create a new object for each node to ensure that all attributes are reset to default values
expNode = shapeNode->first_node("ident")->first_node();
shape._id = std::string(expNode->value());
//std::cout<<"id "<<shape._id<<std::endl;
expNode = shapeNode->first_node("T")->first_node();
shape._T[0] = getVisualizerAttributeForNode(expNode);
expNode = expNode->next_sibling();
shape._T[1] = getVisualizerAttributeForNode(expNode);
expNode = expNode->next_sibling();
shape._T[2] = getVisualizerAttributeForNode(expNode);
expNode = expNode->next_sibling();
shape._T[3] = getVisualizerAttributeForNode(expNode);
expNode = expNode->next_sibling();
shape._T[4] = getVisualizerAttributeForNode(expNode);
expNode = expNode->next_sibling();
shape._T[5] = getVisualizerAttributeForNode(expNode);
expNode = expNode->next_sibling();
shape._T[6] = getVisualizerAttributeForNode(expNode);
expNode = expNode->next_sibling();
shape._T[7] = getVisualizerAttributeForNode(expNode);
expNode = expNode->next_sibling();
shape._T[8] = getVisualizerAttributeForNode(expNode);
expNode = shapeNode->first_node("r")->first_node();
shape._r[0] = getVisualizerAttributeForNode(expNode);
expNode = expNode->next_sibling();
shape._r[1] = getVisualizerAttributeForNode(expNode);
expNode = expNode->next_sibling();
shape._r[2] = getVisualizerAttributeForNode(expNode);
expNode = shapeNode->first_node("color")->first_node();
shape._color[0] = getVisualizerAttributeForNode(expNode);
expNode = expNode->next_sibling();
shape._color[1] = getVisualizerAttributeForNode(expNode);
expNode = expNode->next_sibling();
shape._color[2] = getVisualizerAttributeForNode(expNode);
expNode = shapeNode->first_node("specCoeff")->first_node();
shape._specCoeff = getVisualizerAttributeForNode(expNode);
expNode = shapeNode->first_node("type")->first_node();
if (!expNode) {
MessagesWidget::instance()->addGUIMessage(MessageItem(MessageItem::Modelica,
QString(QObject::tr("The type of %1 is not supported right in the visxml file."))
.arg(shape._id.c_str()),
Helper::scriptingKind, Helper::errorLevel));
continue;
}
shape._type = std::string(expNode->value());
if (isCADFile(shape._type))
{
shape._fileName = extractCADFilename(shape._type);
if (!fileExists(shape._fileName)) {
MessagesWidget::instance()->addGUIMessage(MessageItem(MessageItem::Modelica,
QString(QObject::tr("Could not find the file %1."))
.arg(shape._fileName.c_str()),
Helper::scriptingKind, Helper::errorLevel));
continue;
}
if (isDXFFile(shape._fileName)) {
shape._type = "DXF";
} else if (isSTLFile(shape._fileName)) {
shape._type = "STL";
} else if (isOBJFile(shape._fileName)) {
shape._type = "OBJ";
} else if (is3DSFile(shape._fileName)) {
shape._type = "3DS";
}
}
//std::cout<<"type "<<shape._type<<std::endl;
expNode = shapeNode->first_node("r_shape")->first_node();
shape._rShape[0] = getVisualizerAttributeForNode(expNode);
expNode = expNode->next_sibling();
shape._rShape[1] = getVisualizerAttributeForNode(expNode);
expNode = expNode->next_sibling();
shape._rShape[2] = getVisualizerAttributeForNode(expNode);
expNode = shapeNode->first_node("lengthDir")->first_node();
shape._lDir[0] = getVisualizerAttributeForNode(expNode);
expNode = expNode->next_sibling();
shape._lDir[1] = getVisualizerAttributeForNode(expNode);
expNode = expNode->next_sibling();
shape._lDir[2] = getVisualizerAttributeForNode(expNode);
expNode = shapeNode->first_node("widthDir")->first_node();
shape._wDir[0] = getVisualizerAttributeForNode(expNode);
expNode = expNode->next_sibling();
shape._wDir[1] = getVisualizerAttributeForNode(expNode);
expNode = expNode->next_sibling();
shape._wDir[2] = getVisualizerAttributeForNode(expNode);
expNode = shapeNode->first_node("length")->first_node();
shape._length = getVisualizerAttributeForNode(expNode);
expNode = shapeNode->first_node("width")->first_node();
shape._width = getVisualizerAttributeForNode(expNode);
expNode = shapeNode->first_node("height")->first_node();
shape._height = getVisualizerAttributeForNode(expNode);
expNode = shapeNode->first_node("extra")->first_node();
shape._extra = getVisualizerAttributeForNode(expNode);
_shapes.push_back(shape);
}
for (rapidxml::xml_node<>* vectorNode = rootNode->first_node("vector"); vectorNode; vectorNode = vectorNode->next_sibling("vector"))
{
VectorObject vector; // Create a new object for each node to ensure that all attributes are reset to default values
expNode = vectorNode->first_node("ident")->first_node();
vector._id = std::string(expNode->value());
//std::cout<<"id "<<vector._id<<std::endl;
expNode = vectorNode->first_node("T")->first_node();
vector._T[0] = getVisualizerAttributeForNode(expNode);
expNode = expNode->next_sibling();
vector._T[1] = getVisualizerAttributeForNode(expNode);
expNode = expNode->next_sibling();
vector._T[2] = getVisualizerAttributeForNode(expNode);
expNode = expNode->next_sibling();
vector._T[3] = getVisualizerAttributeForNode(expNode);
expNode = expNode->next_sibling();
vector._T[4] = getVisualizerAttributeForNode(expNode);
expNode = expNode->next_sibling();
vector._T[5] = getVisualizerAttributeForNode(expNode);
expNode = expNode->next_sibling();
vector._T[6] = getVisualizerAttributeForNode(expNode);
expNode = expNode->next_sibling();
vector._T[7] = getVisualizerAttributeForNode(expNode);
expNode = expNode->next_sibling();
vector._T[8] = getVisualizerAttributeForNode(expNode);
expNode = vectorNode->first_node("r")->first_node();
vector._r[0] = getVisualizerAttributeForNode(expNode);
expNode = expNode->next_sibling();
vector._r[1] = getVisualizerAttributeForNode(expNode);
expNode = expNode->next_sibling();
vector._r[2] = getVisualizerAttributeForNode(expNode);
expNode = vectorNode->first_node("color")->first_node();
vector._color[0] = getVisualizerAttributeForNode(expNode);
expNode = expNode->next_sibling();
vector._color[1] = getVisualizerAttributeForNode(expNode);
expNode = expNode->next_sibling();
vector._color[2] = getVisualizerAttributeForNode(expNode);
expNode = vectorNode->first_node("specCoeff")->first_node();
vector._specCoeff = getVisualizerAttributeForNode(expNode);
expNode = vectorNode->first_node("coordinates")->first_node();
vector._coords[0] = getVisualizerAttributeForNode(expNode);
expNode = expNode->next_sibling();
vector._coords[1] = getVisualizerAttributeForNode(expNode);
expNode = expNode->next_sibling();
vector._coords[2] = getVisualizerAttributeForNode(expNode);
expNode = vectorNode->first_node("quantity")->first_node();
vector._quantity = getVisualizerAttributeForNode(expNode);
expNode = vectorNode->first_node("headAtOrigin")->first_node();
vector._headAtOrigin = getVisualizerAttributeForNode(expNode);
expNode = vectorNode->first_node("twoHeadedArrow")->first_node();
vector._twoHeadedArrow = getVisualizerAttributeForNode(expNode);
_vectors.push_back(vector);
}
}
void OMVisualBase::setFmuVarRefInVisObjects()
{
try
{
for (ShapeObject& shape : _shapes)
{
//std::cout<<"shape "<<shape._id <<std::endl;
shape._T[0].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(shape._T[0]);
shape._T[1].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(shape._T[1]);
shape._T[2].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(shape._T[2]);
shape._T[3].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(shape._T[3]);
shape._T[4].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(shape._T[4]);
shape._T[5].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(shape._T[5]);
shape._T[6].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(shape._T[6]);
shape._T[7].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(shape._T[7]);
shape._T[8].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(shape._T[8]);
shape._r[0].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(shape._r[0]);
shape._r[1].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(shape._r[1]);
shape._r[2].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(shape._r[2]);
shape._color[0].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(shape._color[0]);
shape._color[1].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(shape._color[1]);
shape._color[2].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(shape._color[2]);
shape._specCoeff.fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(shape._specCoeff);
shape._rShape[0].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(shape._rShape[0]);
shape._rShape[1].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(shape._rShape[1]);
shape._rShape[2].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(shape._rShape[2]);
shape._lDir[0].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(shape._lDir[0]);
shape._lDir[1].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(shape._lDir[1]);
shape._lDir[2].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(shape._lDir[2]);
shape._wDir[0].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(shape._wDir[0]);
shape._wDir[1].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(shape._wDir[1]);
shape._wDir[2].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(shape._wDir[2]);
shape._length.fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(shape._length);
shape._width.fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(shape._width);
shape._height.fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(shape._height);
shape._extra.fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(shape._extra);
//shape.dumpVisualizerAttributes();
}
for (VectorObject& vector : _vectors)
{
//std::cout<<"vector "<<vector._id <<std::endl;
vector._T[0].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(vector._T[0]);
vector._T[1].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(vector._T[1]);
vector._T[2].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(vector._T[2]);
vector._T[3].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(vector._T[3]);
vector._T[4].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(vector._T[4]);
vector._T[5].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(vector._T[5]);
vector._T[6].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(vector._T[6]);
vector._T[7].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(vector._T[7]);
vector._T[8].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(vector._T[8]);
vector._r[0].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(vector._r[0]);
vector._r[1].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(vector._r[1]);
vector._r[2].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(vector._r[2]);
vector._color[0].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(vector._color[0]);
vector._color[1].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(vector._color[1]);
vector._color[2].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(vector._color[2]);
vector._specCoeff.fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(vector._specCoeff);
vector._coords[0].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(vector._coords[0]);
vector._coords[1].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(vector._coords[1]);
vector._coords[2].fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(vector._coords[2]);
vector._quantity.fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(vector._quantity);
vector._headAtOrigin.fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(vector._headAtOrigin);
vector._twoHeadedArrow.fmuValueRef = _visualization->getFmuVariableReferenceForVisualizerAttribute(vector._twoHeadedArrow);
//vector.dumpVisualizerAttributes();
}
}
catch (std::exception& ex)
{
QString msg = QString(QObject::tr("Something went wrong in OMVisualBase::setFmuVarRefInVisObjects:\n%1."))
.arg(ex.what());
MessagesWidget::instance()->addGUIMessage(MessageItem(MessageItem::Modelica, msg, Helper::scriptingKind, Helper::errorLevel));
throw(msg.toStdString());
}
}
void OMVisualBase::updateVisObjects(const double time)
{
// Update all visualizers
//std::cout<<"updateVisObjects at "<<time <<std::endl;
try
{
for (ShapeObject& shape : _shapes)
{
// Get the values for the scene graph objects
//std::cout<<"shape "<<shape._id <<std::endl;
_visualization->updateVisualizerAttribute(shape._T[0], time);
_visualization->updateVisualizerAttribute(shape._T[1], time);
_visualization->updateVisualizerAttribute(shape._T[2], time);
_visualization->updateVisualizerAttribute(shape._T[3], time);
_visualization->updateVisualizerAttribute(shape._T[4], time);
_visualization->updateVisualizerAttribute(shape._T[5], time);
_visualization->updateVisualizerAttribute(shape._T[6], time);
_visualization->updateVisualizerAttribute(shape._T[7], time);
_visualization->updateVisualizerAttribute(shape._T[8], time);
_visualization->updateVisualizerAttribute(shape._r[0], time);
_visualization->updateVisualizerAttribute(shape._r[1], time);
_visualization->updateVisualizerAttribute(shape._r[2], time);
_visualization->updateVisualizerAttribute(shape._color[0], time);
_visualization->updateVisualizerAttribute(shape._color[1], time);
_visualization->updateVisualizerAttribute(shape._color[2], time);
_visualization->updateVisualizerAttribute(shape._specCoeff, time);
_visualization->updateVisualizerAttribute(shape._rShape[0], time);
_visualization->updateVisualizerAttribute(shape._rShape[1], time);
_visualization->updateVisualizerAttribute(shape._rShape[2], time);
_visualization->updateVisualizerAttribute(shape._lDir[0], time);
_visualization->updateVisualizerAttribute(shape._lDir[1], time);
_visualization->updateVisualizerAttribute(shape._lDir[2], time);
_visualization->updateVisualizerAttribute(shape._wDir[0], time);
_visualization->updateVisualizerAttribute(shape._wDir[1], time);
_visualization->updateVisualizerAttribute(shape._wDir[2], time);
_visualization->updateVisualizerAttribute(shape._length, time);
_visualization->updateVisualizerAttribute(shape._width, time);
_visualization->updateVisualizerAttribute(shape._height, time);
_visualization->updateVisualizerAttribute(shape._extra, time);
rAndT rT = rotateModelica2OSG(
osg::Matrix3(shape._T[0].exp, shape._T[1].exp, shape._T[2].exp,
shape._T[3].exp, shape._T[4].exp, shape._T[5].exp,
shape._T[6].exp, shape._T[7].exp, shape._T[8].exp),
osg::Vec3f(shape._r[0].exp, shape._r[1].exp, shape._r[2].exp),
osg::Vec3f(shape._rShape[0].exp, shape._rShape[1].exp, shape._rShape[2].exp),
osg::Vec3f(shape._lDir[0].exp, shape._lDir[1].exp, shape._lDir[2].exp),
osg::Vec3f(shape._wDir[0].exp, shape._wDir[1].exp, shape._wDir[2].exp),
shape._type);
assemblePokeMatrix(shape._mat, rT._T, rT._r);
// Update the shapes
updateVisualizer(shape, true);
//shape.dumpVisualizerAttributes();
}
for (VectorObject& vector : _vectors)
{
// Get the values for the scene graph objects
//std::cout<<"vector "<<vector._id <<std::endl;
_visualization->updateVisualizerAttribute(vector._T[0], time);
_visualization->updateVisualizerAttribute(vector._T[1], time);
_visualization->updateVisualizerAttribute(vector._T[2], time);
_visualization->updateVisualizerAttribute(vector._T[3], time);
_visualization->updateVisualizerAttribute(vector._T[4], time);
_visualization->updateVisualizerAttribute(vector._T[5], time);
_visualization->updateVisualizerAttribute(vector._T[6], time);
_visualization->updateVisualizerAttribute(vector._T[7], time);
_visualization->updateVisualizerAttribute(vector._T[8], time);
_visualization->updateVisualizerAttribute(vector._r[0], time);
_visualization->updateVisualizerAttribute(vector._r[1], time);
_visualization->updateVisualizerAttribute(vector._r[2], time);
_visualization->updateVisualizerAttribute(vector._color[0], time);
_visualization->updateVisualizerAttribute(vector._color[1], time);
_visualization->updateVisualizerAttribute(vector._color[2], time);
_visualization->updateVisualizerAttribute(vector._specCoeff, time);
_visualization->updateVisualizerAttribute(vector._coords[0], time);
_visualization->updateVisualizerAttribute(vector._coords[1], time);
_visualization->updateVisualizerAttribute(vector._coords[2], time);
_visualization->updateVisualizerAttribute(vector._quantity, time);
_visualization->updateVisualizerAttribute(vector._headAtOrigin, time);
_visualization->updateVisualizerAttribute(vector._twoHeadedArrow, time);
rAndT rT = rotateModelica2OSG(
osg::Matrix3(vector._T[0].exp, vector._T[1].exp, vector._T[2].exp,
vector._T[3].exp, vector._T[4].exp, vector._T[5].exp,
vector._T[6].exp, vector._T[7].exp, vector._T[8].exp),
osg::Vec3f(vector._r[0].exp, vector._r[1].exp, vector._r[2].exp),
osg::Vec3f(vector._coords[0].exp, vector._coords[1].exp, vector._coords[2].exp));
assemblePokeMatrix(vector._mat, rT._T, rT._r);
// Update the vectors
updateVisualizer(vector, true);
//vector.dumpVisualizerAttributes();
}
}
catch (std::exception& ex)
{
QString msg = QString(QObject::tr("Error in OMVisualBase::updateVisObjects at time point %1\n%2."))
.arg(QString::number(time), ex.what());
MessagesWidget::instance()->addGUIMessage(MessageItem(MessageItem::Modelica, msg, Helper::scriptingKind, Helper::errorLevel));
throw(msg.toStdString());
}
}
void OMVisualBase::setUpScene()
{
// Build scene graph
_visualization->getOMVisScene()->getScene().setUpScene(_shapes);
_visualization->getOMVisScene()->getScene().setUpScene(_vectors);
}
void OMVisualBase::updateVectorCoords(VectorObject& vector, const double time)
{
_visualization->updateVisualizerAttribute(vector._coords[0], time);
_visualization->updateVisualizerAttribute(vector._coords[1], time);
_visualization->updateVisualizerAttribute(vector._coords[2], time);
}
/*!
* \brief Adjust scaling of vector visualizers.
* \details Choose suitable scales for the radius and the length of vector visualizers.
* Scaling is completely decoupled for radius and length.
* Only adjustable-radius vectors will have their radius adjusted, as well as
* only adjustable-length vectors will have their length adjusted.
* <hr>
* Adjustment of the radius scale is implemented as a heuristic
* that makes the radius of adjustable-radius vectors
* equal to the median value of
* - the radii of fixed-radius vectors and
* - the radii of relevant shapes,
* plus or minus some constant factor (default: -10%).
* <hr>
* Adjustment of the length scale is implemented as a heuristic
* that adjusts the length of adjustable-length vectors
* for each vector quantity independently
* (all adjustable-length vectors of the same vector quantity
* will see their length scaled with the same factor for consistent comparison)
* by performing a binary search (dichotomy), the aim of which is to
* increase the lengths as much as possible for vectors to be clearly visible,
* while ensuring that the following two constraints are satisfied,
* the first one having priority over the second one:
* - the vector lengths must be greater than that of their respective heads,
* plus or minus some constant margin (default: +10%),
* so that all the shaft lengths are guaranteed to be greater than zero;
* - the final camera distance to the focal center must not be greater than
* the initial distance obtained without drawing adjustable-length vectors,
* plus or minus some constant margin (default: +10%),
* so that the model size (and thus its first appearance) remains similar.
* The model size is computed from the bounding spheres of all the nodes in the model,
* and the home position of the camera is defined as a function of the model size.
* <hr>
* Hence, scaling vectors can be seen like scaling bounding spheres, and this explains why
* the radius is scaled before the length as it affects the bounding sphere of the vector.
* <hr>
* Time-varying vector lengths can be handled to some extent and are accounted for by
* sampling the simulation interval with a constant number of time samples (default: 100),
* a value of zero meaning that the criterion on the vector lengths is disregarded.
* Similarly, the check for the camera distance can be constantly enabled (default: true),
* and the heuristic no longer attempts to increase the lengths if the check is disabled,
* unless this is required by the first constraint when the latter is enabled.
* <hr>
* During the binary search, floating-point numbers are treated as integer bit patterns,
* thus considering quantities as if they were given in units in the last place (ULP).
* This allows to stop the search when a constant precision is reached (default: 4096ulp)
* instead of doing comparisons between numbers with a constant floating-point tolerance.
* The value of the length scale is technically bounded from zero to infinity, and
* the initial guess for the search is chosen as the default value provided by the MSL.
* Since this is expected to be a good initial guess in general, for faster convergence
* the search can be reduced to a smaller interval (initial minimum and maximum bounds).
* However, those bounds shall be moved if the optimal value ends up being outside.
* For this purpose, a moving horizon can be constantly enabled (default: true)
* which automatically adapts the bounds such that, starting from an empty interval,
* the search continues either below or above the current value,
* shifting the bounds towards a constant horizon (default: 16777216ulp)
* that is either subtracted from or added to the current value.
* Whenever it moves, the default horizon has the effect of halving or doubling the value.
* \note For debugging purposes, MessagesWidget::addPendingMessage() shall be used
* instead of MessagesWidget::addGUIMessage() when \p mutex is locked.
* \param[in] view OSG view of the scene composed of at least one camera.
* \param[in] mutex OT mutex for synchronization of frame rendering.
* \param[in] frame VW frame function to trigger frame rendering.
*/
void OMVisualBase::chooseVectorScales(osgViewer::View* view, OpenThreads::Mutex* mutex, std::function<void()> frame)
{
/* Return early if there is nothing to do */
if (view == nullptr || _vectors.size() == 0) {
return;
}
/* Constants to be tuned for well-performing heuristics */
constexpr int8_t factorRadius = -10; // Factor for vector radius greater than median of fixed radii in percent [%]
constexpr int8_t marginLength = +10; // Margin for vector length greater than length of its head(s) in percent [%]
constexpr int8_t marginDistance = +10; // Margin for home distance greater than initial home distance in percent [%]
constexpr uint32_t timeSamples = 100; // Number of time samples to be examined for vector lengths {32b}
constexpr bool checkDistance = true; // Whether camera distance to focal center shall be checked {0,1}
constexpr bool movingHorizon = true; // Is moving horizon in units in the last place {0,1}
constexpr uint32_t hulp = 0x01000000; // Move this horizon in units in the last place [ulp]
constexpr uint32_t pulp = 0x00001000; // Minimum precision in units in the last place [ulp]
/* Cancel out transform scales before adjustments begin */
OpenThreads::ScopedPointerLock<OpenThreads::Mutex> lock(mutex); // Wait for any previous frame to complete rendering, and lock until adjustments are finished
for (VectorObject& vector : _vectors) {
vector.setAutoScaleCancellationRequired(true);
}
if (!frame) frame = std::bind(&osgViewer::ViewerBase::frame, view->getViewerBase(), USE_REFERENCE_TIME);
frame(); // Work-around for osg::AutoTransform::computeBound() (see OSG commits 25abad8 & 92092a5 & 5c48904)
/* Adjustable-radius vectors */
{
// Initialize containers of relevant shapes as well as fixed- and adjustable-radius vectors
std::vector<ShapeObject>& relevantShapes = _shapes;
std::vector<std::reference_wrapper<VectorObject>> fixedRadiusVectors;
std::vector<std::reference_wrapper<VectorObject>> adjustableRadiusVectors;
for (VectorObject& vector : _vectors) {
if (vector.isAdjustableRadius() && vector.getRadius() > 0) {
adjustableRadiusVectors.push_back(vector);
} else {
fixedRadiusVectors.push_back(vector);
}
}
// Proceed with scaling adjustable-radius vectors
if (adjustableRadiusVectors.size() > 0) {
float scale = 1;
// Browse radii only if there are any fixed-radius vectors or relevant shapes
if (fixedRadiusVectors.size() > 0 || relevantShapes.size() > 0) {
std::vector<float> radii;
// Store the radius of fixed-radius vectors
for (VectorObject& vector : fixedRadiusVectors) {
const float radius = vector.getRadius();
// Take into account visible vectors only
if (radius > 0) {
radii.push_back(radius);
}
}
// Store the radius of relevant shapes
for (ShapeObject& shape : relevantShapes) {
// Consider OSG shape drawables only
if (isCADType(shape._type)) {
continue;
}
// For the world component, discard axis labels and arrow heads
if (shape._id.rfind("world.", 0) == 0) {
if (shape._id.compare("world.x_arrowLine") != 0 &&
shape._id.compare("world.y_arrowLine") != 0 &&
shape._id.compare("world.z_arrowLine") != 0 &&
shape._id.compare("world.gravityArrowLine") != 0) {
continue;
}
}
// Take the main dimension orthogonal to the principal direction
float radius = shape._width.exp / 2;
if (shape._type == "sphere") {
radius = shape._length.exp / 2;
} else if (shape._type == "spring") {
radius = shape._width.exp;
}
// Take into account visible shapes only
if (radius > 0) {
radii.push_back(radius);
}
}
// Compute the median of the radii (see https://stackoverflow.com/a/34077478)
const size_t s = radii.size();
if (s > 0) {
float median = radii[0];
if (s > 1) {
const size_t n = s / 2;
const std::vector<float>::iterator beg = radii.begin();
const std::vector<float>::iterator end = radii.end();
const std::vector<float>::iterator mid = beg + n;
std::nth_element(beg, mid, end);
if (s & 1) { // Odd-sized container
median = *mid;
} else { // Even-sized container
// Following statement is equivalent to, but on average faster than:
// const std::vector<float>::iterator max = beg;
// std::nth_element(beg, max, mid, std::greater<float>{});
const std::vector<float>::iterator max = std::max_element(beg, mid);
// Average of left & right middle values (avoid overflow)
median = *max + (*mid - *max) * .5f;
}
}
// Scale the default radius
scale = median / VectorObject::kRadius * (1.f + factorRadius / 100.f);
}
}
// Apply the radius scale to all adjustable-radius vectors
for (VectorObject& vector : adjustableRadiusVectors) {
vector.setScaleRadius(scale);
updateVisualizer(vector);
}
// Recompute the home position
view->home();
}
}
/* Adjustable-length vectors */
{
// Initialize a container of adjustable-length vectors
std::vector<std::reference_wrapper<VectorObject>> adjustableLengthVectors;
for (VectorObject& vector : _vectors) {
if (vector.isAdjustableLength() && vector.getLength() > 0) {
adjustableLengthVectors.push_back(vector);
}
}
// Proceed with scaling adjustable-length vectors
if (adjustableLengthVectors.size() > 0) {
// Compute the time increment used to sample between the beginning and the end of the simulation
const double timeStart = _visualization->getTimeManager()->getStartTime();
const double timeStop = _visualization->getTimeManager()->getEndTime();
const double timeIncrement = timeSamples > 1 ? (timeStop - timeStart) / (timeSamples - 1) : 0;
// Initialize a map of numbers of time samples, one for each adjustable-length vector
std::unordered_map<const std::reference_wrapper<VectorObject>, uint32_t> numberOfSamples;
for (VectorObject& vector : adjustableLengthVectors) {
numberOfSamples[vector] = timeSamples > 0 && (timeIncrement <= 0 || vector.areCoordinatesConstant()) ? 1 : timeSamples;
}
// Initialize a map of actual transform scales, one for each adjustable-length vector
std::unordered_map<const std::reference_wrapper<VectorObject>, float> transformScales;
for (VectorObject& vector : adjustableLengthVectors) {
transformScales[vector] = vector.getScaleTransf();
}
// Update the bounds of the whole scene without any adjustable-length vectors
for (VectorObject& vector : adjustableLengthVectors) {
vector.setScaleTransf(0);
updateVisualizer(vector);
}
// Get the initial camera distance to the focal center
view->home();
const osgGA::OrbitManipulator* manipulator = static_cast<osgGA::OrbitManipulator*>(view->getCameraManipulator());
const double initialDistance = manipulator->getDistance();
// Initialize a map of adjustable-length vectors paired with their length scale, and grouped by their respective quantity
std::map<const VectorQuantity, std::pair<float, std::vector<std::reference_wrapper<VectorObject>>>> data;
for (VectorQuantity quantity = VectorQuantity::BEGIN; quantity != VectorQuantity::END; ++quantity) {
float scale = 1;
switch (quantity) {
case VectorQuantity::force:
scale /= VectorObject::kScaleForce;
break;
case VectorQuantity::torque:
scale /= VectorObject::kScaleTorque;
break;
default:
break;
}
for (VectorObject& vector : adjustableLengthVectors) {
if (vector.getQuantity() == quantity) {
data[quantity].first = scale;
data[quantity].second.push_back(vector);
}
}
}
// Iterate over each quantity separately to adjust the related length scale
for (std::pair<const VectorQuantity, std::pair<float, std::vector<std::reference_wrapper<VectorObject>>>>& pair : data) {
float& scale = pair.second.first;
std::vector<std::reference_wrapper<VectorObject>>& vectors = pair.second.second;
// Make the vectors of the current quantity visible again
// (the update is not necessary here because it is done inside and after the while loop in any case)
for (VectorObject& vector : vectors) {
vector.setScaleTransf(transformScales[vector]);
}
// Adjust the length scale for the current quantity as long as the criteria have not been met
constexpr size_t fbytes = sizeof(float);
constexpr size_t ubytes = sizeof(uint32_t);
constexpr size_t bytes = std::min(fbytes, ubytes);
constexpr float fmin = 0.f;
constexpr float fmax = std::numeric_limits<float>::max();
const float fval = scale;
uint32_t umin = 0;
uint32_t umax = 0;
uint32_t uval = 0;
memcpy(&umin, &fmin, bytes);
memcpy(&umax, &fmax, bytes);
memcpy(&uval, &fval, bytes);
uint32_t min = umin;
uint32_t max = umax;
uint32_t val = uval;
bool isMinBelowLimit = false;
bool isMaxAboveLimit = false;
bool movedMinAlready = false;
bool movedMaxAlready = false;
bool squeezedTooMuch = false;
bool unzoomedTooMuch = false;
bool fulfilledWishes = false;
while (!fulfilledWishes) {
memset(&scale, 0x0, fbytes);
memcpy(&scale, &val, bytes);
// Apply the new length scale to the vectors of the current quantity
for (VectorObject& vector : vectors) {
vector.setScaleLength(scale);
updateVisualizer(vector);
}
// Get the new camera distance to the focal center
view->home();
const double distance = manipulator->getDistance();
// Determine if the new length scale has squeezed the vectors too much or unzoomed the scene too much
squeezedTooMuch = false;
if (timeSamples > 0) {
for (VectorObject& vector : vectors) {
float x, y, z;
vector.getCoordinates(&x, &y, &z);
const uint32_t samples = numberOfSamples[vector];
for (uint32_t s = 0; s < samples; s++) {
if (samples > 1) {
updateVectorCoords(vector, s + 1 == samples ? timeStop : timeStart + timeIncrement * s);
}
if (vector.getLength() < vector.getHeadLength() * ((vector.isTwoHeadedArrow() ? 1.5f : 1.f) + marginLength / 100.f)) {
squeezedTooMuch = true;
break;
}
}
vector.setCoordinates(x, y, z);
if (squeezedTooMuch) {
break;
}
}
}
unzoomedTooMuch = checkDistance && distance > initialDistance * (1.f + marginDistance / 100.f);
// Perform a floating-point binary search,
// assuming non-negative as well as non-NaN values,