File: vtkMotionFXCFGReader.cxx

package info (click to toggle)
paraview 5.11.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 497,236 kB
  • sloc: cpp: 3,171,290; ansic: 1,315,072; python: 134,290; xml: 103,324; sql: 65,887; sh: 5,286; javascript: 4,901; yacc: 4,383; java: 3,977; perl: 2,363; lex: 1,909; f90: 1,255; objc: 143; makefile: 119; tcl: 59; pascal: 50; fortran: 29
file content (1525 lines) | stat: -rw-r--r-- 47,087 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
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
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
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkMotionFXCFGReader.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkMotionFXCFGReader.h"

#include "vtkArrayDispatch.h"
#include "vtkAssume.h"
#include "vtkDataArrayRange.h"
#include "vtkDoubleArray.h"
#include "vtkFloatArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkMath.h"
#include "vtkMultiBlockDataSet.h"
#include "vtkObjectFactory.h"
#include "vtkPolyData.h"
#include "vtkSMPTools.h"
#include "vtkSTLReader.h"
#include "vtkSmartPointer.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkTransform.h"
#include "vtkVector.h"
#include "vtkVectorOperators.h"

#include <vtksys/RegularExpression.hxx>
#include <vtksys/SystemTools.hxx>

// Set to 1 to generate debugging trace if grammar match fails.
#include "vtkMotionFXCFGGrammar.h" // grammar

#include <cassert>
#include <cctype>
#include <fstream>
#include <map>
#include <memory>
#include <string>
#include <vector>

//=============================================================================
namespace impl
{
VTK_ABI_NAMESPACE_BEGIN
struct Motion;

using MapOfVectorOfMotions =
  std::map<std::string, std::vector<std::shared_ptr<const impl::Motion>>>;

//------------------------------------------------------------------------------
// this exception is fired to indicate that a required parameter is missing for
// the motion definition.
class MissingParameterError : public std::runtime_error
{
public:
  MissingParameterError(const std::string& what_arg)
    : std::runtime_error(what_arg)
  {
  }
  MissingParameterError(const char* what_arg)
    : std::runtime_error(what_arg)
  {
  }
};

//------------------------------------------------------------------------------
// these are a bunch of convenience methods used in constructors for various
// motion types that read parameter values from a map of params and then sets
// appropriate member variable. If the parameter is missing, then raises
// MissingParameterError exception.
template <typename Value, typename MapType>
void set(Value& ref, const char* pname, const MapType& params);

template <typename MapType>
void set(std::string& ref, const char* pname, const MapType& params)
{
  auto iter = params.find(pname);
  if (iter == params.end() || iter->second.StringValue.empty())
  {
    throw MissingParameterError(pname);
  }
  ref = iter->second.StringValue;
}

template <typename MapType>
void set(vtkVector3d& ref, const char* pname, const MapType& params)
{
  auto iter = params.find(pname);
  if (iter == params.end() || iter->second.DoubleValue.size() != 3)
  {
    throw MissingParameterError(pname);
  }
  ref = vtkVector3d(&iter->second.DoubleValue[0]);
}

template <typename MapType>
void set(double& ref, const char* pname, const MapType& params)
{
  auto iter = params.find(pname);
  if (iter == params.end() || iter->second.DoubleValue.size() != 1)
  {
    throw MissingParameterError(pname);
  }
  ref = iter->second.DoubleValue[0];
}

//------------------------------------------------------------------------------
// this is a variant of set that doesn't raise MissingParameterError exception
// instead set the param to the default value indicated.
template <typename Value, typename MapType>
void set(Value& ref, const char* pname, const MapType& params, const Value& defaultValue)
{
  try
  {
    set(ref, pname, params);
  }
  catch (const MissingParameterError&)
  {
    ref = defaultValue;
  }
}

//------------------------------------------------------------------------------
// Superclass for all motions
// The member variable names match the keyworks in the cfg file and hence are
// left lower-case.
struct Motion
{
  // Starting time of the motion.
  double tstart_prescribe;

  // Ending time of the motion. Note that by changing starting
  //  time and ending time, you can add the motions of a single
  //  phase in order to get a complex motion.
  double tend_prescribe;

  // This specified the period of acceleration time (damping).
  // The motion will start at time tstart_prescribe with 0 velocity and
  // ramp up to the specified value during this time.
  double t_damping;

  // filename for the geometry file.
  std::string stl;

  template <typename MapType>
  Motion(const MapType& params)
  {
    set(this->tstart_prescribe, "tstart_prescribe", params, 0.0);
    set(this->tend_prescribe, "tend_prescribe", params, VTK_DOUBLE_MAX);
    set(this->t_damping, "t_damping", params, 0.0);
    set(this->stl, "stl", params);
  }
  virtual ~Motion() = default;

  virtual bool Move(vtkPoints* pts, double time) const = 0;

protected:
  template <typename Type>
  Type compute_displacement(
    double time, const Type& init_velocity, const Type& acceleration, const Type& velocity) const
  {
    // we don't bother converting freq to angular velocity since it cancels out
    // anyways when we take the final mod.
    Type s(0.0);
    if (this->t_damping > 0)
    {
      // s = u*tA + 0.5 * a * (tA)^2
      const double tA = std::min(time - this->tstart_prescribe, this->t_damping);
      assert(tA >= 0.0);
      const double tA2 = tA * tA;
      s = s + (init_velocity * tA + acceleration * (tA2 / 2.0));
    }

    if (time > (this->tstart_prescribe + this->t_damping))
    {
      // s = v*t
      const double t =
        std::min(time, this->tend_prescribe) - this->tstart_prescribe - this->t_damping;
      s = s + (velocity * t);
    }
    return s;
  }

  // A worker that apply the Transform provided to all points.
  struct ApplyTransform
  {
    vtkSmartPointer<vtkTransform> Transform;
    ApplyTransform(vtkTransform* transform)
      : Transform(transform)
    {
    }

    template <typename InputArrayType>
    void operator()(InputArrayType* darray)
    {
      VTK_ASSUME(darray->GetNumberOfComponents() == 3);
      using ValueType = vtk::GetAPIType<InputArrayType>;

      vtkSMPTools::For(0, darray->GetNumberOfTuples(), [&](vtkIdType begin, vtkIdType end) {
        auto drange = vtk::DataArrayTupleRange(darray, begin, end);
        for (auto tuple : drange)
        {
          vtkVector4<ValueType> in, out;
          in[0] = tuple[0];
          in[1] = tuple[1];
          in[2] = tuple[2];
          in[3] = 1.0;

          this->Transform->MultiplyPoint(in.GetData(), out.GetData());

          out[0] /= out[3];
          out[1] /= out[3];
          out[2] /= out[3];
          tuple.SetTuple(out.GetData());
        }
      });
    }
  };
};

//------------------------------------------------------------------------------
// Move given velocity
struct ImposeVelMotion : public Motion
{
  vtkVector3d impose_vel;      //< Prescribed velocity (vector form).
  vtkVector3d impose_vel_init; //< Prescribed velocity (vector form) at t0 increase to impose_vel
                               // until t_damping.

  vtkVector3d acceleration; // (derived) acceleration during damping time.

  template <typename MapType>
  ImposeVelMotion(const MapType& params)
    : Motion(params)
    , acceleration(0.0)
  {
    std::string motion_type;
    set(motion_type, "motion_type", params);
    assert(motion_type == "IMPOSE_VEL");

    set(this->impose_vel, "impose_vel", params);
    set(this->impose_vel_init, "impose_vel_init", params, this->impose_vel);

    // compute acceleration.
    if (this->t_damping > 0)
    {
      this->acceleration = (this->impose_vel - this->impose_vel_init) * (1.0 / this->t_damping);
    }
  }
  bool Move(vtkPoints* pts, double time) const override
  {
    if (time < this->tstart_prescribe)
    {
      // nothing to do, this motion hasn't been activated yet.
      return false;
    }

    vtkVector3d s =
      this->compute_displacement(time, this->impose_vel_init, this->acceleration, this->impose_vel);
    if (s != vtkVector3d(0.0))
    {
      ApplyDisplacement worker(s);

      // displace points.
      using PointTypes = vtkTypeList::Create<float, double>;
      vtkArrayDispatch::DispatchByValueType<PointTypes>::Execute(pts->GetData(), worker);
      pts->GetData()->Modified();
    }

    return true;
  }

private:
  struct ApplyDisplacement
  {
    const vtkVector3d& Displacement;
    ApplyDisplacement(const vtkVector3d& disp)
      : Displacement(disp)
    {
    }

    template <typename InputArrayType>
    void operator()(InputArrayType* darray)
    {
      using T = vtk::GetAPIType<InputArrayType>;

      vtkSMPTools::For(0, darray->GetNumberOfTuples(), [&](vtkIdType begin, vtkIdType end) {
        for (auto tuple : vtk::DataArrayTupleRange<3>(darray, begin, end))
        {
          tuple[0] += static_cast<T>(this->Displacement[0]);
          tuple[1] += static_cast<T>(this->Displacement[1]);
          tuple[2] += static_cast<T>(this->Displacement[2]);
        }
      });
    }
  };
};

//------------------------------------------------------------------------------
// Rotate around an arbitrary axis.
struct RotateAxisMotion : public Motion
{
  // Center of rotation. This point needs to lie on the same
  // line as the rotation frequency vector if you want co-axial motion,
  // e.g. gear spinning.
  vtkVector3d rot_cntr;

  // Rotation axis vector.
  vtkVector3d rot_axis;

  // Frequency of rotation [rot/s].
  double rot_axis_freq;

  // Frequency of rotation at t0 increase to rot_axis_freq until t_damping [rot/s].
  double rot_axis_freq_init;

  double rot_axis_w;       // (derived)
  double rot_axis_w_init;  // (derived)
  double rot_acceleration; // (derived) acceleration during  t_damping

  template <typename MapType>
  RotateAxisMotion(const MapType& params)
    : Motion(params)
    , rot_acceleration(0)
  {
    std::string motion_type;
    set(motion_type, "motion_type", params);
    assert(motion_type == "ROTATE_AXIS");

    set(this->rot_cntr, "rot_cntr", params);
    set(this->rot_axis, "rot_axis", params);
    set(this->rot_axis_freq, "rot_axis_freq", params);
    set(this->rot_axis_freq_init, "rot_axis_freq_init", params, this->rot_axis_freq);

    this->rot_axis.Normalize();
    this->rot_axis_w = 2 * vtkMath::Pi() * this->rot_axis_freq;
    this->rot_axis_w_init = 2 * vtkMath::Pi() * this->rot_axis_freq_init;

    if (this->t_damping > 0)
    {
      this->rot_acceleration = (this->rot_axis_w - this->rot_axis_w_init) / this->t_damping;
    }
  }

  bool Move(vtkPoints* pts, double time) const override
  {
    if (time < this->tstart_prescribe)
    {
      // nothing to do, this motion hasn't been activated yet.
      return false;
    }

    double theta = this->compute_displacement(
      time, this->rot_axis_w_init, this->rot_acceleration, this->rot_axis_w);

    if (theta != 0.0)
    {
      // theta is in radians.
      // convert to degrees
      theta = vtkMath::DegreesFromRadians(theta);

      vtkNew<vtkTransform> transform;
      transform->Identity();
      transform->Translate(this->rot_cntr.GetData());
      transform->RotateWXYZ(theta, this->rot_axis.GetData());
      transform->Translate(-this->rot_cntr[0], -this->rot_cntr[1], -this->rot_cntr[2]);

      ApplyTransform worker(transform);
      // transform points.
      using PointTypes = vtkTypeList::Create<float, double>;
      vtkArrayDispatch::DispatchByValueType<PointTypes>::Execute(pts->GetData(), worker);
      pts->GetData()->Modified();
    }
    return true;
  }
};

//------------------------------------------------------------------------------
// Rotate around x,y,z coordinate axes.
struct RotateMotion : public Motion
{
  vtkVector3d rot_freq;
  vtkVector3d rot_cntr;
  vtkVector3d rot_freq_init;    // (optional)
  vtkVector3d rot_acceleration; // (derived)
  vtkVector3d rot_w;            // (derived)
  vtkVector3d rot_w_init;       // (derived)

  template <typename MapType>
  RotateMotion(const MapType& params)
    : Motion(params)
    , rot_acceleration(0, 0, 0)
  {
    std::string motion_type;
    set(motion_type, "motion_type", params);
    assert(motion_type == "ROTATE");

    set(this->rot_freq, "rot_freq", params);
    set(this->rot_cntr, "rot_cntr", params);
    set(this->rot_freq_init, "rot_freq_init", params, this->rot_freq);

    this->rot_w = 2 * vtkMath::Pi() * this->rot_freq;
    this->rot_w_init = 2 * vtkMath::Pi() * this->rot_freq_init;

    if (this->t_damping > 0)
    {
      this->rot_acceleration = (this->rot_w - this->rot_w_init) / vtkVector3d(this->t_damping);
    }
  }

  bool Move(vtkPoints* pts, double time) const override
  {
    if (time < this->tstart_prescribe)
    {
      // nothing to do, this motion hasn't been activated yet.
      return false;
    }

    vtkVector3d theta =
      this->compute_displacement(time, this->rot_w_init, this->rot_acceleration, this->rot_w);

    if (theta != vtkVector3d(0.0))
    {
      // remember, theta is in radians.
      vtkNew<vtkTransform> transform;
      transform->Identity();
      transform->Translate(this->rot_cntr.GetData());
      transform->RotateWXYZ(
        vtkMath::DegreesFromRadians(theta.Norm()), theta[0], theta[1], theta[2]);
      transform->Translate(-this->rot_cntr[0], -this->rot_cntr[1], -this->rot_cntr[2]);

      ApplyTransform worker(transform);
      // transform points.
      using PointTypes = vtkTypeList::Create<float, double>;
      vtkArrayDispatch::DispatchByValueType<PointTypes>::Execute(pts->GetData(), worker);
      pts->GetData()->Modified();
    }
    return true;
  }
};

//------------------------------------------------------------------------------
// Planetary motion
struct PlanetaryMotion : public Motion
{
  // Center of the sun gear/carrier.
  vtkVector3d orbit_cntr;

  // The radius of the orbit.
  double orbit_radius;

  // The direction vector of the year rotation axis. Doesn't have to be normalized.
  vtkVector3d year_rotationVec;

  // Frequency of the year rotation [rot/s].
  double year_frequency;

  // Frequency of the year rotation at t0 increase to year_frequency until t_damping [rot/s].
  double year_frequency_init;

  // The direction vector of the day rotation axis. Doesn't have to be normalized.
  vtkVector3d day_rotationVec;

  // Frequency of the day rotation [rot/s].
  double day_frequency;

  // Frequency of the day rotation at t0 increase to day_frequency until t_damping [rot/s].
  double day_frequency_init;

  // Any point on the initial day rotation axis.
  vtkVector3d initial_centerOfDayRotation;

  double year_acceleration; // (derived)
  double day_acceleration;  // (derived)
  double year_w;            // (derived)
  double year_w_init;       // (derived)
  double day_w;             // (derived)
  double day_w_init;        // (derived)

  template <typename MapType>
  PlanetaryMotion(const MapType& params)
    : Motion(params)
    , year_acceleration(0.0)
    , day_acceleration(0.0)
  {
    std::string motion_type;
    set(motion_type, "motion_type", params);
    assert(motion_type == "PLANETARY");

    set(this->orbit_cntr, "orbit_cntr", params);
    set(this->orbit_radius, "orbit_radius", params);
    set(this->year_rotationVec, "year_rotationVec", params);
    set(this->year_frequency, "year_frequency", params);
    set(this->year_frequency_init, "year_frequency_init", params, this->year_frequency);
    set(this->day_rotationVec, "day_rotationVec", params);
    set(this->day_frequency, "day_frequency", params);
    set(this->day_frequency_init, "day_frequency_init", params, this->day_frequency);
    set(this->initial_centerOfDayRotation, "initial_centerOfDayRotation", params);

    this->year_rotationVec.Normalize();
    this->day_rotationVec.Normalize();

    this->year_w = 2 * vtkMath::Pi() * this->year_frequency;
    this->year_w_init = 2 * vtkMath::Pi() * this->year_frequency_init;

    this->day_w = 2 * vtkMath::Pi() * this->day_frequency;
    this->day_w_init = 2 * vtkMath::Pi() * this->day_frequency_init;

    if (this->t_damping > 0)
    {
      this->year_acceleration = (this->year_w - this->year_w_init) / this->t_damping;
      this->day_acceleration = (this->day_w - this->day_w_init) / this->t_damping;
    }
  }

  bool Move(vtkPoints* pts, double time) const override
  {
    if (time < this->tstart_prescribe)
    {
      // nothing to do, this motion hasn't been activated yet.
      return false;
    }

    // compute rotation angular displacement
    double day_theta =
      this->compute_displacement(time, this->day_w_init, this->day_acceleration, this->day_w);

    // compute revolution angular displacement
    double year_theta =
      this->compute_displacement(time, this->year_w_init, this->year_acceleration, this->year_w);

    if (day_theta != 0.0 || year_theta != 0.0)
    {

      vtkNew<vtkTransform> transform;
      transform->Identity();

      // year_theta is in radians
      // convert to degrees.
      year_theta = vtkMath::DegreesFromRadians(year_theta);

      transform->Translate(this->orbit_cntr.GetData());
      transform->RotateWXYZ(year_theta, this->year_rotationVec.GetData());
      transform->Translate(-this->orbit_cntr[0], -this->orbit_cntr[1], -this->orbit_cntr[2]);

      // day_theta is in radians.
      // convert to degrees
      day_theta = vtkMath::DegreesFromRadians(day_theta);

      transform->Translate(this->initial_centerOfDayRotation.GetData());
      transform->RotateWXYZ(day_theta, this->day_rotationVec.GetData());
      transform->Translate(-this->initial_centerOfDayRotation[0],
        -this->initial_centerOfDayRotation[1], -this->initial_centerOfDayRotation[2]);

      ApplyTransform worker(transform);
      // transform points.
      using PointTypes = vtkTypeList::Create<float, double>;
      vtkArrayDispatch::DispatchByValueType<PointTypes>::Execute(pts->GetData(), worker);
      pts->GetData()->Modified();
    }
    return true;
  }
};

//------------------------------------------------------------------------------
// Move given a position file.
struct PositionFileMotion : public Motion
{
  // name of the file that contains the coordinates and angular
  // velocity vectors as a function of time.
  std::string positionFile;

  // If this is set to false - old rot.vel. format of the input file is required.
  // If set to true (default), the format becomes t,CoMx,CoMy,CoMz,cosX,cosY,cosZ,Orientation[rad]
  bool isOrientation;

  // Center of mass for time. This is generally the center of bounds for the STL
  // file itself.
  vtkVector3d initial_centerOfMass;

  struct tuple_type
  {
    vtkVector3d center_of_mass;

    // for isOrientation=true
    vtkVector3d direction_cosines;
    double rotation;

    // for isOrientation=false;
    vtkVector3d angular_velocities;

    tuple_type()
      : center_of_mass(0.0)
      , direction_cosines(0.0)
      , rotation(0.0)
      , angular_velocities(0.0)
    {
    }
  };

  mutable std::map<double, tuple_type> positions; // (derived).

  template <typename MapType>
  PositionFileMotion(const MapType& params)
    : Motion(params)
    , isOrientation(false)
    , initial_centerOfMass{ VTK_DOUBLE_MAX }
  {
    std::string motion_type;
    set(motion_type, "motion_type", params);
    assert(motion_type == "POSITION_FILE");

    set(this->positionFile, "positionFile", params);
    set(this->initial_centerOfMass, "initial_centerOfMass", params, this->initial_centerOfMass);

    std::string s_isOrientation;
    set(s_isOrientation, "isOrientation", params, std::string("false"));
    s_isOrientation = vtksys::SystemTools::LowerCase(s_isOrientation);
    this->isOrientation = s_isOrientation == "true" || s_isOrientation == "1";
  }

  // read_position_file is defined later since it needs the Actions namespace.
  bool read_position_file(const std::string& rootDir) const;

  bool Move(vtkPoints* pts, double time) const override
  {
    if ((time < this->tstart_prescribe) || (this->positions.size() < 2))
    {
      // nothing to do, this motion hasn't been activated yet.
      // if there's less than 2 position entries, the interpolation logic fails
      // and hence we don't handle it.
      return false;
    }

    time -= this->tstart_prescribe;

    // let's clamp to end time in the position time to avoid complications.
    time = std::min(this->positions.rbegin()->first, time);

    auto iter = this->positions.lower_bound(time);
    if (iter == this->positions.begin() && iter->first != time)
    {
      // first time is greater than `time`, nothing to do.
      return false;
    }

    // iter can never be end since we've clamp time to the last time in the
    // position file.
    assert(iter != this->positions.end());

    vtkNew<vtkTransform> transform;
    transform->PostMultiply();
    // center to the initial_centerOfMass.
    if (this->initial_centerOfMass != vtkVector3d{ VTK_DOUBLE_MAX })
    {
      transform->Translate((initial_centerOfMass * -1.0).GetData());
    }

    vtkVector3d cumulativeS(0.0); //, cumulativeTheta(0.0);
    if (!this->isOrientation)
    {
      for (auto citer = this->positions.begin(); citer != iter; ++citer)
      {
        assert(time >= citer->first);

        auto next = std::next(citer);
        assert(next != this->positions.end());

        const double interval = (next->first - citer->first);
        const double dt = std::min(time - citer->first, interval);

        const double t = dt / interval; // normalized dt
        const vtkVector3d s = t * (next->second.center_of_mass - citer->second.center_of_mass);

        // theta = (w0 + w1)*dt / 2
        const vtkVector3d theta =
          (citer->second.angular_velocities + next->second.angular_velocities) * dt * 0.5;
        transform->RotateWXYZ(
          vtkMath::DegreesFromRadians(theta.Norm()), theta[0], theta[1], theta[2]);

        cumulativeS = cumulativeS + s;
        // cumulativeTheta = cumulativeTheta + theta;
      }
    }
    else
    {
      if (iter->first < time)
      {
        auto next = std::next(iter);
        assert(next != this->positions.end());

        const double interval = (next->first - iter->first);
        const double dt = std::min(time - iter->first, interval);
        const double t = dt / interval; // normalized dt

        const double rotation = (1.0 - t) * iter->second.rotation + t * next->second.rotation;
        const vtkVector3d cosines =
          (1.0 - t) * iter->second.direction_cosines + t * next->second.direction_cosines;
        transform->RotateWXYZ(vtkMath::DegreesFromRadians(rotation), cosines.GetData());

        const vtkVector3d disp =
          (1.0 - t) * iter->second.center_of_mass + t * next->second.center_of_mass;
        transform->Translate(disp.GetData());
      }
      else // iter->first == time
      {
        transform->RotateWXYZ(vtkMath::DegreesFromRadians(iter->second.rotation),
          iter->second.direction_cosines.GetData());
        transform->Translate(iter->second.center_of_mass.GetData());
      }
    }
    // restore
    if (this->initial_centerOfMass != vtkVector3d{ VTK_DOUBLE_MAX })
    {
      transform->Translate(initial_centerOfMass.GetData());
    }
    transform->Translate(cumulativeS.GetData());

    ApplyTransform worker(transform);
    // transform points.
    using PointTypes = vtkTypeList::Create<float, double>;
    vtkArrayDispatch::DispatchByValueType<PointTypes>::Execute(pts->GetData(), worker);
    pts->GetData()->Modified();
    return true;
  }
};

//-----------------------------------------------------------------------------
// Move given a universal transform file.
struct UniversalTransformMotion : public Motion
{
  // name of the file that contains the transformation data
  // as a function of time.
  std::string utm;

  struct tuple_type
  {
    vtkVector3d translation_vector;
    vtkVector3d rotation_center;
    vtkVector4d quaternion;
    vtkVector3d linear_scale;

    tuple_type()
      : translation_vector(0.0)
      , rotation_center(0.0)
      , quaternion(0.0)
      , linear_scale(0.0)
    {
    }
  };

  mutable std::map<double, tuple_type> transforms; // (derived).

  template <typename MapType>
  UniversalTransformMotion(const MapType& params)
    : Motion(params)
  {
    std::string motion_type;
    set(motion_type, "motion_type", params);
    assert(motion_type == "UNIVERSAL_TRANSFORM");

    set(this->utm, "utm", params);
  }

  // read_universaltransform_file is defined later since it needs the Actions namespace.
  bool read_universaltransform_file(const std::string& rootDir) const;

  bool Move(vtkPoints* pts, double time) const override
  {
    if (this->transforms.empty())
    {
      // at least one entry is required
      return false;
    }

    // let's clamp to time range in the universal transform file
    time = std::min(this->transforms.rbegin()->first, time);
    time = std::max(this->transforms.begin()->first, time);

    auto next = this->transforms.lower_bound(time);
    auto prev = next;

    vtkNew<vtkTransform> transform;
    transform->PostMultiply();

    double t;
    if (next->first > time)
    {
      prev = std::prev(next);
      const double interval = (next->first - prev->first);
      const double dt = std::min(time - prev->first, interval);
      t = dt / interval; // normalized dt
    }
    else // this also handles single entry files
    {
      t = 0.0;
    }

    const vtkVector3d rotation_center =
      prev->second.rotation_center * (1.0 - t) + next->second.rotation_center * t;
    transform->Translate((rotation_center * -1.0).GetData());

    const vtkVector3d linear_scale =
      prev->second.linear_scale * (1.0 - t) + next->second.linear_scale * t;
    transform->Scale(linear_scale.GetData());

    double quatdotprod = prev->second.quaternion.Dot(next->second.quaternion);

    if (quatdotprod < 0.0)
    {
      next->second.quaternion = -next->second.quaternion;
      quatdotprod = -quatdotprod;
    }

    vtkVector4d quatnow;
    if (quatdotprod > 0.9995) // linear interpolation (LERP)
    {
      quatnow = prev->second.quaternion * (1.0 - t) + next->second.quaternion * t;
    }
    else // spherical linear interpolation (SLERP)
    {
      const double thdiff = std::acos(quatdotprod);
      const double sndiff = std::sin(thdiff);
      const double cfi = sin((1.0 - t) * thdiff) / sndiff;
      const double cfn = sin(t * thdiff) / sndiff;
      quatnow = prev->second.quaternion * cfi + next->second.quaternion * cfn;
    }

    const double quatmag = quatnow.Norm();
    const double oquatmag = 1.0 / quatmag;
    if (quatmag > 0.1) // Should never lead to division by zero for a quaternion
    {
      quatnow = quatnow * oquatmag;
    }

    vtkVector3d axis;
    double angle;
    if (quatnow[3] == 1.0)
    {
      // Arbitrary axis
      axis[0] = 1.0;
      axis[1] = 0.0;
      axis[2] = 0.0;
      angle = 0.0;
    }
    else if (quatnow[3] == 0.0)
    {
      // Arbitrary axis
      axis[0] = 1.0;
      axis[1] = 0.0;
      axis[2] = 0.0;
      angle = 180.0;
    }
    else
    {
      const double coeff = 1.0 / std::sqrt(1.0 - quatnow[3] * quatnow[3]);
      angle = vtkMath::DegreesFromRadians(2.0 * std::acos(quatnow[3]));
      axis[0] = quatnow[0] * coeff;
      axis[1] = quatnow[1] * coeff;
      axis[2] = quatnow[2] * coeff;
      axis.Normalize(); // Should never lead to division by zero for a quaternion
    }

    transform->RotateWXYZ(angle, axis.GetData());

    const vtkVector3d translation_vector =
      prev->second.translation_vector * (1.0 - t) + next->second.translation_vector * t;
    transform->Translate(translation_vector.GetData());

    ApplyTransform worker(transform);
    // transform points.
    using PointTypes = vtkTypeList::Create<float, double>;
    vtkArrayDispatch::DispatchByValueType<PointTypes>::Execute(pts->GetData(), worker);
    pts->GetData()->Modified();
    return true;
  }
};

//-----------------------------------------------------------------------------
template <typename MapType>
std::shared_ptr<const Motion> CreateMotion(const MapType& params)
{
  std::string motion_type;
  try
  {
    set(motion_type, "motion_type", params);
  }
  catch (const MissingParameterError&)
  {
    vtkGenericWarningMacro("Missing 'motion_type'. Cannot determine motion type. Skipping.");
    return nullptr;
  }

  try
  {
    if (motion_type == "IMPOSE_VEL")
    {
      return std::make_shared<ImposeVelMotion>(params);
    }
    else if (motion_type == "ROTATE_AXIS")
    {
      return std::make_shared<RotateAxisMotion>(params);
    }
    else if (motion_type == "ROTATE")
    {
      return std::make_shared<RotateMotion>(params);
    }
    else if (motion_type == "PLANETARY")
    {
      return std::make_shared<PlanetaryMotion>(params);
    }
    else if (motion_type == "POSITION_FILE")
    {
      return std::make_shared<PositionFileMotion>(params);
    }
    else if (motion_type == "UNIVERSAL_TRANSFORM")
    {
      return std::make_shared<UniversalTransformMotion>(params);
    }
    vtkGenericWarningMacro("Unsupported motion_type '" << motion_type << "'. Skipping.");
  }
  catch (const MissingParameterError& e)
  {
    vtkGenericWarningMacro("Missing required parameter '" << e.what() << "' "
                                                          << "for motion_type='" << motion_type
                                                          << "'");
  }

  return nullptr;
}
VTK_ABI_NAMESPACE_END
}

//=============================================================================
namespace Actions
{
using namespace tao::pegtl;

//------------------------------------------------------------------------------
// actions when parsing LegacyPositionFile::Grammar or
// OrientationsPositionFile::Grammar
namespace PositionFile
{
VTK_ABI_NAMESPACE_BEGIN
template <typename Rule>
struct action : nothing<Rule>
{
};

template <>
struct action<MotionFX::Common::Number>
{
  // if a Number is encountered, push it into the set of active_numbers.
  template <typename Input, typename OtherState>
  static void apply(const Input& in, std::vector<double>& active_numbers, OtherState&)
  {
    active_numbers.push_back(std::atof(in.string().c_str()));
  }
};

template <>
struct action<MotionFX::LegacyPositionFile::Row>
{
  // for each row parsed, add the item to the state.
  template <typename AngularVelocitiesType>
  static void apply0(std::vector<double>& active_numbers, AngularVelocitiesType& state)
  {
    assert(active_numbers.size() == 7);

    using tuple_type = typename AngularVelocitiesType::mapped_type;
    tuple_type tuple;
    tuple.center_of_mass = vtkVector3d(active_numbers[1], active_numbers[2], active_numbers[3]);

    auto freq = vtkVector3d(active_numbers[4], active_numbers[5], active_numbers[6]);
    // convert rot/s to angular velocity
    tuple.angular_velocities = freq * 2 * vtkMath::Pi();

    state[active_numbers[0]] = tuple;
    active_numbers.clear();
  }
};

template <>
struct action<MotionFX::OrientationsPositionFile::Row>
{
  template <typename OrientationsType>
  static void apply0(std::vector<double>& active_numbers, OrientationsType& state)
  {
    assert(active_numbers.size() == 8);
    using tuple_type = typename OrientationsType::mapped_type;
    tuple_type tuple;
    tuple.center_of_mass = vtkVector3d(active_numbers[1], active_numbers[2], active_numbers[3]);
    tuple.direction_cosines = vtkVector3d(active_numbers[4], active_numbers[5], active_numbers[6]);
    tuple.rotation = active_numbers[7];
    state[active_numbers[0]] = tuple;
    active_numbers.clear();
  }
};
VTK_ABI_NAMESPACE_END
} // namespace PositionFile

//-----------------------------------------------------------------------------
// actions when parsing UniversalTransformRow::Grammar
namespace UniversalTransformFile
{
VTK_ABI_NAMESPACE_BEGIN
template <typename Rule>
struct action : nothing<Rule>
{
};

template <>
struct action<MotionFX::Common::Number>
{
  // if a Number is encountered, push it into the set of active_numbers.
  template <typename Input, typename OtherState>
  static void apply(const Input& in, std::vector<double>& active_numbers, OtherState&)
  {
    active_numbers.push_back(std::atof(in.string().c_str()));
  }
};

template <>
struct action<MotionFX::UniversalTransformRow::Row>
{
  template <typename UniversalTransformType>
  static void apply0(std::vector<double>& active_numbers, UniversalTransformType& state)
  {
    assert(active_numbers.size() == 14);
    using tuple_type = typename UniversalTransformType::mapped_type;
    tuple_type tuple;
    tuple.translation_vector = vtkVector3d(active_numbers[1], active_numbers[2], active_numbers[3]);
    tuple.rotation_center = vtkVector3d(active_numbers[4], active_numbers[5], active_numbers[6]);
    tuple.quaternion =
      vtkVector4d(active_numbers[7], active_numbers[8], active_numbers[9], active_numbers[10]);
    tuple.linear_scale = vtkVector3d(active_numbers[11], active_numbers[12], active_numbers[13]);
    state[active_numbers[0]] = tuple;
    active_numbers.clear();
  }
};
VTK_ABI_NAMESPACE_END
} // namespace UniversalTransformSpace

//-----------------------------------------------------------------------------
// actions when parsing CFG::Grammar
namespace CFG
{
VTK_ABI_NAMESPACE_BEGIN
//------------------------------------------------------------------------------
// When parsing CFG, we need to accumulate values and keep track of them.
// Value and ActiveState help us do that.
struct Value
{
  std::vector<double> DoubleValue;
  std::string StringValue;
  void clear()
  {
    this->StringValue.clear();
    this->DoubleValue.clear();
  }
};

struct ActiveState
{
  std::string ActiveParameterName;
  Value ActiveValue;
  std::map<std::string, Value> ActiveParameters;
  impl::MapOfVectorOfMotions& Motions;

  ActiveState(impl::MapOfVectorOfMotions& motions)
    : Motions(motions)
  {
  }
  ~ActiveState() = default;

private:
  ActiveState(const ActiveState&) = delete;
  void operator=(const ActiveState&) = delete;
};
//------------------------------------------------------------------------------

template <typename Rule>
struct action : nothing<Rule>
{
};

template <>
struct action<MotionFX::CFG::Value>
{

  template <typename Input>
  static void apply(const Input& in, ActiveState& state)
  {
    auto content = in.string();
    // the value can have trailing spaces; remove them.
    while (!content.empty() && std::isspace(content.back()))
    {
      content.pop_back();
    }
    vtksys::RegularExpression tupleRe("^\"([^\"]+)\"$");
    vtksys::RegularExpression numberRe(
      "^[ \t]*[-+]?(([0-9]+.?)|([0-9]*.))[0-9]*([eE][-+]?[0-9]+)?[ \t]*$");
    if (tupleRe.find(content))
    {
      state.ActiveValue.DoubleValue.clear();
      const auto tuple = tupleRe.match(1);
      auto values = vtksys::SystemTools::SplitString(tuple, ' ');
      for (const auto& val : values)
      {
        if (numberRe.find(val))
        {
          state.ActiveValue.DoubleValue.push_back(std::atof(numberRe.match(0).c_str()));
        }
        else
        {
          vtkGenericWarningMacro("Expecting number, got '" << val << "'");
        }
      }
      state.ActiveValue.StringValue = tupleRe.match(1);
    }
    else if (numberRe.find(content))
    {
      state.ActiveValue.DoubleValue.push_back(std::atof(numberRe.match(0).c_str()));
    }
    else
    {
      state.ActiveValue.StringValue = content;
    }
  }
};

template <>
struct action<MotionFX::CFG::ParameterName>
{
  template <typename Input>
  static void apply(const Input& in, ActiveState& state)
  {
    state.ActiveParameterName = in.string();
  }
};

template <>
struct action<MotionFX::CFG::Statement>
{
  static void apply0(ActiveState& state)
  {
    auto& params = state.ActiveParameters;
    if (params.find(state.ActiveParameterName) != params.end())
    {
      // warn: duplicate parameter, overriding.
    }
    params[state.ActiveParameterName] = state.ActiveValue;
    state.ActiveParameterName.clear();
    state.ActiveValue.clear();
  }
};

template <>
struct action<MotionFX::CFG::Motion>
{
  static void apply0(ActiveState& state)
  {
    if (auto motion = impl::CreateMotion(state.ActiveParameters))
    {
      // fixme: lets add logic to catch overlapping motions.
      state.Motions[motion->stl].push_back(motion);
    }
    state.ActiveValue.clear();
  }
};

template <>
struct action<MotionFX::CFG::Grammar>
{
  static void apply0(ActiveState& state)
  {
    // let's sort all motions according to tstart_prescribe.
    for (auto& apair : state.Motions)
    {
      std::sort(apair.second.begin(), apair.second.end(),
        [](const std::shared_ptr<const impl::Motion>& m0,
          const std::shared_ptr<const impl::Motion>& m1) {
          return m0->tstart_prescribe < m1->tstart_prescribe;
        });
    }
  }
};

VTK_ABI_NAMESPACE_END
} // namespace CFG

} // namespace Actions

namespace impl
{
VTK_ABI_NAMESPACE_BEGIN
bool PositionFileMotion::read_position_file(const std::string& rootDir) const
{
  // read positionFile.
  try
  {
    tao::pegtl::read_input<> in(rootDir + "/" + this->positionFile);
    if (this->isOrientation)
    {
      std::vector<double> numbers;
      tao::pegtl::parse<MotionFX::OrientationsPositionFile::Grammar,
        Actions::PositionFile::action /*, tao::pegtl::tracer*/>(in, numbers, this->positions);
    }
    else
    {
      std::vector<double> numbers;
      tao::pegtl::parse<MotionFX::LegacyPositionFile::Grammar,
        Actions::PositionFile::action /*, tao::pegtl::tracer*/>(in, numbers, this->positions);
    }
    return true;
  }
  catch (const tao::pegtl::input_error& e)
  {
    vtkGenericWarningMacro("PositionFileMotion::read_position_file failed: " << e.what());
  }
  return false;
}

bool UniversalTransformMotion::read_universaltransform_file(const std::string& rootDir) const
{
  // read universalTransformFile.
  try
  {
    tao::pegtl::read_input<> in(rootDir + "/" + this->utm);
    std::vector<double> numbers;
    tao::pegtl::parse<MotionFX::UniversalTransformRow::Grammar,
      Actions::UniversalTransformFile::action /*, tao::pegtl::tracer*/>(
      in, numbers, this->transforms);
    return true;
  }
  catch (const tao::pegtl::input_error& e)
  {
    vtkGenericWarningMacro(
      "UniversalTransformMotion::read_universaltransform_file failed: " << e.what());
  }
  return false;
}
VTK_ABI_NAMESPACE_END
} // impl

VTK_ABI_NAMESPACE_BEGIN
class vtkMotionFXCFGReader::vtkInternals
{
public:
  vtkInternals()
    : TimeRange(0, -1)
  {
  }
  ~vtkInternals() = default;

  const vtkVector2d& GetTimeRange() const { return this->TimeRange; }

  bool Parse(const std::string& filename)
  {
    tao::pegtl::read_input<> in(filename);
    Actions::CFG::ActiveState state(this->Motions);
    tao::pegtl::parse<MotionFX::CFG::Grammar, Actions::CFG::action>(in, state);
    if (this->Motions.empty())
    {
      vtkGenericWarningMacro(
        "No valid 'motions' were parsed from the CFG file. "
        "This indicates a potential mismatch in the grammar rules and the file contents. "
        "A highly verbose log for advanced debugging can be generated by defining the environment "
        "variable `MOTIONFX_DEBUG_GRAMMAR` to debug grammar related issues.");
      if (getenv("MOTIONFX_DEBUG_GRAMMAR") != nullptr)
      {
        tao::pegtl::read_input<> in2(filename);
        tao::pegtl::parse<MotionFX::CFG::Grammar, tao::pegtl::nothing, tao::pegtl::tracer>(in2);
      }
      return false;
    }

    const auto dir = vtksys::SystemTools::GetFilenamePath(filename);

    // lets read the STL files for each of the bodies and remove any bodies that
    // do not have readable STL files.
    for (auto iter = this->Motions.begin(); iter != this->Motions.end();)
    {
      const std::string fname = dir + "/" + iter->first;
      if (vtksys::SystemTools::TestFileAccess(fname, vtksys::TEST_FILE_OK | vtksys::TEST_FILE_READ))
      {
        vtkNew<vtkSTLReader> reader;
        reader->SetFileName(fname.c_str());
        reader->Update();

        vtkPolyData* pd = reader->GetOutput();
        if (pd->GetNumberOfPoints() > 0)
        {
          this->Geometries.emplace_back(iter->first, pd);
          ++iter;
          continue;
        }
      }
      vtkGenericWarningMacro(
        "Failed to open '" << iter->first << "'. Skipping motions associated with it.");
      iter = this->Motions.erase(iter);
    }

    if (this->Motions.empty())
    {
      vtkGenericWarningMacro("All parsed `motion`s were skipped!");
      return false;
    }

    // now let's process and extra initializations needed by the active motions.
    for (const auto& pair : this->Motions)
    {
      for (const auto& motion : pair.second)
      {
        if (auto mpf = std::dynamic_pointer_cast<const impl::PositionFileMotion>(motion))
        {
          mpf->read_position_file(dir);
        }
        else if (auto mut = std::dynamic_pointer_cast<const impl::UniversalTransformMotion>(motion))
        {
          mut->read_universaltransform_file(dir);
        }
      }
    }

    this->TimeRange[0] = VTK_DOUBLE_MAX;
    this->TimeRange[1] = VTK_DOUBLE_MIN;
    for (auto apair : this->Motions)
    {
      this->TimeRange[0] = std::min(apair.second.front()->tstart_prescribe, this->TimeRange[0]);
      this->TimeRange[1] = std::max(apair.second.back()->tend_prescribe, this->TimeRange[1]);
    }
    return this->TimeRange[0] <= this->TimeRange[1];
  }

  vtkSmartPointer<vtkPolyData> Move(unsigned int bodyIdx, double time) const
  {
    assert(bodyIdx < this->GetNumberOfBodies());

    auto pd = vtkSmartPointer<vtkPolyData>::New();
    pd->ShallowCopy(this->Geometries[bodyIdx].second);

    // deep copy points, since we'll need to modify them.
    vtkNew<vtkPoints> points;
    points->DeepCopy(pd->GetPoints());

    // how let's move!
    const auto iter = this->Motions.find(this->Geometries[bodyIdx].first);
    assert(iter != this->Motions.end());
    for (auto& motion_ptr : iter->second)
    {
      // since motions are sorted by tstart_prescribe and we're assured no
      // overlap, we can simply iterate in order.
      motion_ptr->Move(points, time);
    }
    pd->SetPoints(points);
    pd->Modified();
    return pd;
  }

  std::string GetBodyName(unsigned int bodyIdx) const
  {
    assert(bodyIdx < this->GetNumberOfBodies());
    return vtksys::SystemTools::GetFilenameWithoutExtension(this->Geometries[bodyIdx].first);
  }

  // do not call this before Parse().
  unsigned int GetNumberOfBodies() const
  {
    assert(this->Motions.size() == this->Geometries.size());
    return static_cast<unsigned int>(this->Motions.size());
  }

private:
  vtkInternals(const vtkInternals&) = delete;
  void operator=(const vtkInternals&) = delete;

  impl::MapOfVectorOfMotions Motions;
  vtkVector2d TimeRange;
  std::vector<std::pair<std::string, vtkSmartPointer<vtkPolyData>>> Geometries;
};

vtkStandardNewMacro(vtkMotionFXCFGReader);
//------------------------------------------------------------------------------
vtkMotionFXCFGReader::vtkMotionFXCFGReader()
  : TimeResolution(100)
  , Internals(nullptr)
{
  this->SetNumberOfInputPorts(0);
  this->SetNumberOfOutputPorts(1);
}

//------------------------------------------------------------------------------
vtkMotionFXCFGReader::~vtkMotionFXCFGReader()
{
  delete this->Internals;
  this->Internals = nullptr;
}

//------------------------------------------------------------------------------
void vtkMotionFXCFGReader::SetFileName(const char* fname)
{
  const std::string arg(fname ? fname : "");
  if (this->FileName != arg)
  {
    this->FileName = arg;
    this->FileNameMTime.Modified();
    this->Modified();
  }
}

//------------------------------------------------------------------------------
int vtkMotionFXCFGReader::RequestInformation(
  vtkInformation*, vtkInformationVector**, vtkInformationVector* outputVector)
{
  if (!this->ReadMetaData())
  {
    return 0;
  }

  vtkInformation* outInfo = outputVector->GetInformationObject(0);

  auto trange = this->Internals->GetTimeRange();
  if (trange[1] > trange[0])
  {
    const double delta = (trange[1] - trange[0]) / this->TimeResolution;
    std::vector<double> timesteps(this->TimeResolution);
    for (int cc = 0; cc < this->TimeResolution - 1; ++cc)
    {
      timesteps[cc] = trange[0] + cc * delta;
    }
    timesteps.back() = trange[1];

    outInfo->Set(
      vtkStreamingDemandDrivenPipeline::TIME_STEPS(), timesteps.data(), this->TimeResolution);
    outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_RANGE(), trange.GetData(), 2);
  }
  else
  {
    outInfo->Remove(vtkStreamingDemandDrivenPipeline::TIME_STEPS());
    outInfo->Remove(vtkStreamingDemandDrivenPipeline::TIME_RANGE());
  }
  return 1;
}

//------------------------------------------------------------------------------
int vtkMotionFXCFGReader::RequestData(
  vtkInformation*, vtkInformationVector**, vtkInformationVector* outputVector)
{
  if (!this->ReadMetaData())
  {
    return 0;
  }

  vtkMultiBlockDataSet* output = vtkMultiBlockDataSet::GetData(outputVector, 0);

  const auto& internals = (*this->Internals);
  output->SetNumberOfBlocks(internals.GetNumberOfBodies());

  vtkInformation* outInfo = outputVector->GetInformationObject(0);

  double time = internals.GetTimeRange()[0];
  if (outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()))
  {
    time = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP());
  }

  // clamp the time request.
  time = std::max(time, internals.GetTimeRange()[0]);
  time = std::min(time, internals.GetTimeRange()[1]);

  for (unsigned int cc = 0, max = internals.GetNumberOfBodies(); cc < max; ++cc)
  {
    output->SetBlock(cc, internals.Move(cc, time));
    output->GetMetaData(cc)->Set(vtkMultiBlockDataSet::NAME(), internals.GetBodyName(cc).c_str());
  }
  return 1;
}

//------------------------------------------------------------------------------
bool vtkMotionFXCFGReader::ReadMetaData()
{
  if (this->FileNameMTime < this->MetaDataMTime)
  {
    return (this->Internals != nullptr);
  }

  delete this->Internals;
  this->Internals = nullptr;

  if (vtksys::SystemTools::TestFileAccess(
        this->FileName, vtksys::TEST_FILE_OK | vtksys::TEST_FILE_READ))
  {
    auto* interals = new vtkInternals();
    if (interals->Parse(this->FileName))
    {
      this->Internals = interals;
      this->MetaDataMTime.Modified();
      return true;
    }
    delete interals;
  }
  else
  {
    vtkErrorMacro("Cannot read file '" << this->FileName << "'.");
  }
  return (this->Internals != nullptr);
}

//------------------------------------------------------------------------------
void vtkMotionFXCFGReader::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << "FileName: " << this->FileName << endl;
  os << indent << "TimeResolution: " << this->TimeResolution << endl;
}
VTK_ABI_NAMESPACE_END