-
Notifications
You must be signed in to change notification settings - Fork 14
/
Rcs.cpp
3612 lines (3128 loc) · 117 KB
/
Rcs.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
/*******************************************************************************
Copyright (c) 2017, Honda Research Institute Europe GmbH
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
/*! \page RcsExamples Rcs.cpp example program
*
* The Rcs.cpp example program implements a number of different modes that
* show how to use the functionality of the libraries. The following command
* line arguments are common to all example modes. Each argument has a default
* value, that can be seen if running the program with the -h option. When
* calling Rcs -m \<mode\> -h, additionally the command line arguments of
* the specific mode will be printed to the console.
* - -dl:
* Sets the debug level of the overall library. As a convention, a
* debug level of 0 is silent. Debug levels between 1 and 4 will display
* warnings, the higher debug levels being more verbose. Debug levels above
* 4 will tell you a lot of things that you might or might not be interested
* in. The example programs should not produce debug output on debug levels
* equal to or less than 4.
* - -m:
* Mode to select the example. The default mode is 0, which displays some
* information on usage.
* - -dir: Configuration file search directory.
* - -f: Configuration file
* - -simpleGraphics:
* Starts the graphics viewer with minimal settings (no anti-aliasing and
* shadows etc.). This is beneficial if the application is started on a
* remote computer, or the computer has a slow graphics card.
* - -nomutex:
* Disables mutex locking for the graphics viewer. This may result in some
* graphics artefacts, but does not compromise the calculation speed for
* computers with slow graphics cards.
* - -valgrind:
* Runs the algorithm for a fixed number of steps without launching Guis and
* graphics viewer. This allows to run memory checks without considering the
* non-relevant parts.
*
*/
#include <Rcs_macros.h>
#include <Rcs_cmdLine.h>
#include <Rcs_math.h>
#include <Rcs_geometry.h>
#include <Rcs_gradientTests.h>
#include <Rcs_resourcePath.h>
#include <Rcs_BVHParser.h>
#include <Rcs_timer.h>
#include <Rcs_sensor.h>
#include <Rcs_typedef.h>
#include <Rcs_graphParser.h>
#include <Rcs_kinematics.h>
#include <Rcs_dynamics.h>
#include <Rcs_joint.h>
#include <Rcs_body.h>
#include <Rcs_shape.h>
#include <Rcs_utils.h>
#include <Rcs_filters.h>
#include <IkSolverConstraintRMR.h>
#include <SolverRAC.h>
#include <TaskFactory.h>
#include <TaskRegionFactory.h>
#include <PhysicsFactory.h>
#include <PhysicsNode.h>
#include <GraphNode.h>
#include <FTSensorNode.h>
#include <CapsuleNode.h>
#include <HUD.h>
#include <VertexArrayNode.h>
#include <PPSSensorNode.h>
#include <KeyCatcher.h>
#include <JointWidget.h>
#include <RcsViewer.h>
#include <Rcs_graphicsUtils.h>
#include <Rcs_guiFactory.h>
#include <BodyPointDragger.h>
#include <ControllerWidgetBase.h>
#include <MatNdWidget.h>
#include <TargetSetter.h>
#include <PPSGui.h>
#include <SegFaultHandler.h>
#include <iostream>
RCS_INSTALL_ERRORHANDLERS
bool runLoop = true;
/*******************************************************************************
* Ctrl-C destructor. Tries to quit gracefully with the first Ctrl-C
* press, then just exits.
******************************************************************************/
void quit(int /*sig*/)
{
static int kHit = 0;
runLoop = false;
fprintf(stderr, "Trying to exit gracefully - %dst attempt\n", kHit + 1);
kHit++;
if (kHit == 2)
{
fprintf(stderr, "Exiting without cleanup\n");
exit(0);
}
}
/*******************************************************************************
* A few pre-defined models
******************************************************************************/
static bool getModel(char* directory, char* xmlFileName)
{
Rcs::CmdLineParser argP;
if (!argP.hasArgument("-model",
"Example models: Husky, DexBot, WAM, Humanoid"))
{
return false;
}
char model[64] = "";
argP.getArgument("-model", model);
if (STREQ(model, "Husky"))
{
strcpy(directory, "config/xml/Husky");
strcpy(xmlFileName, "husky-all.xml");
}
else if (STREQ(model, "DexBot"))
{
strcpy(directory, "config/xml/DexBot");
strcpy(xmlFileName, "gScenario.xml");
}
else if (STREQ(model, "WAM"))
{
strcpy(directory, "config/xml/WAM");
strcpy(xmlFileName, "gScenario.xml");
}
else if (STREQ(model, "Humanoid"))
{
strcpy(directory, "config/xml/GenericHumanoid");
strcpy(xmlFileName, "gScenario.xml");
}
else
{
RMSG("Unknown model: %s", model);
strcpy(directory, "");
strcpy(xmlFileName, "");
return false;
}
return true;
}
/*******************************************************************************
*
******************************************************************************/
int main(int argc, char** argv)
{
int result = 0, mode = 0;
char xmlFileName[128] = "", directory[128] = "";
// Ctrl-C callback handler
signal(SIGINT, quit);
// This initialize the xml library and check potential mismatches between
// the version it was compiled for and the actual shared library used.
LIBXML_TEST_VERSION;
// Parse command line arguments
Rcs::CmdLineParser argP(argc, argv);
argP.getArgument("-dl", &RcsLogLevel, "Debug level (default is 0)");
argP.getArgument("-m", &mode, "Test mode (default is 0)");
argP.getArgument("-f", xmlFileName, "Configuration file name");
argP.getArgument("-dir", directory, "Configuration file directory");
bool valgrind = argP.hasArgument("-valgrind",
"Start without Guis and graphics");
bool simpleGraphics = argP.hasArgument("-simpleGraphics", "OpenGL without fan"
"cy stuff (shadows, anti-aliasing)");
// Initialize GUI and OSG mutex
pthread_mutex_t graphLock;
pthread_mutex_init(&graphLock, NULL);
// Option without mutex for viewer
pthread_mutex_t* mtx = &graphLock;
if (argP.hasArgument("-nomutex", "Graphics without mutex"))
{
mtx = NULL;
}
// Option to set locale - mainly for parsing tests
if (argP.hasArgument("-locale", "Set locale"))
{
char localeStr[256] = "de_DE.utf8";
argP.getArgument("-locale", localeStr);
char* res = setlocale(LC_ALL, localeStr);
if (res==NULL)
{
RLOG(1, "Failed to set locale \"%s\"", localeStr);
}
else
{
struct lconv* loc = localeconv();
RLOG(1, "Locale successfully set to %s", res);
RLOG(1, "Decimal character is %c", *(loc->decimal_point));
}
}
const char* hgr = getenv("SIT");
if (hgr != NULL)
{
std::string meshDir = std::string(hgr) +
std::string("/Data/RobotMeshes/1.0/data");
Rcs_addResourcePath(meshDir.c_str());
}
Rcs_addResourcePath("config");
RPAUSE_DL(5);
switch (mode)
{
// ==============================================================
// Just print out some global information
// ==============================================================
case 0:
{
argP.print();
printf("\nHere's some useful testing modes:\n\n");
printf("\t-m");
printf("\t0 Prints this message (default)\n");
printf("\t\t1 Prints the graph to stdout, writes a dot file and "
"shows\n\t\t it with dotty\n");
printf("\t\t2 Viewer + StateGui + FK\n");
printf("\t\t3 Gradient test for graphs\n");
printf("\t\t4 Viewer + StateGui + FK + Physics\n");
printf("\t\t5 Inverse kinematics + Viewer + Controller Gui\n");
printf("\t\t6 Controller unit tests\n");
printf("\t\t7 Null space convergence test\n");
printf("\t\t8 Resolved acceleration controller test\n");
printf("\t\t9 Depth first traversal test\n");
printf("\t\t10 Task from string creation\n");
printf("\t\t11 Jacobian re-projection test\n");
REXEC(1)
{
RMSGS("SIT is \"%s\"", getenv("SIT"));
RMSGS("MAKEFILE_PLATFORM is \"%s\"", getenv("MAKEFILE_PLATFORM"));
RMSGS("HOSTNAME is \"%s\"", getenv("HOSTNAME"));
Rcs_printResourcePath();
}
REXEC(2)
{
Rcs_printComputerStats(stdout);
}
REXEC(3)
{
Rcs::TaskFactory::instance()->printRegisteredTasks();
Rcs::TaskRegionFactory::instance()->printRegisteredTaskRegions();
Rcs::PhysicsFactory::print();
RcsShape_fprintDistanceFunctions(stdout);
}
break;
}
// ==============================================================
// Graph parsing and dot file output
// ==============================================================
case 1:
{
char dotFile[256] = "RcsGraph.dot";
strcpy(xmlFileName, "gScenario.xml");
strcpy(directory, "config/xml/DexBot");
getModel(directory, xmlFileName);
argP.getArgument("-f", xmlFileName, "Configuration file name (default "
"is \"%s\")", xmlFileName);
argP.getArgument("-dir", directory, "Configuration file directory "
"(default is \"%s\")", directory);
argP.getArgument("-dotFile", dotFile, "Dot file name");
if (argP.hasArgument("-h"))
{
RMSG("Mode %d: Rcs -m %d -dir <graph-directory> -f "
"<graph-file>\n\n\t- Creates a graph from an xml file\n\t- "
"prints it's contents to the console\n\t- creates a dot-file "
"RcsGraph.dot and\n\t- launches it with the dotty tool\n\n\t"
"The default "
"xml file is \"%s\", the default directory is \"%s\"\n",
mode, mode, xmlFileName, directory);
break;
}
Rcs_addResourcePath(directory);
RcsGraph* graph = RcsGraph_create(xmlFileName);
REXEC(1)
{
RMSG("Here's the forward tree:");
RcsGraph_fprint(stderr, graph);
}
RMSG("Writing graph to dot file \"RcsGraph.dot\"");
RcsGraph_writeDotFile(graph, "RcsGraph.dot");
RMSG("Writing graph to xml file \"graph.xml\"");
FILE* out = fopen("graph.xml", "w+");
RcsGraph_fprintXML(out, graph);
fclose(out);
double mGraph = RcsGraph_mass(graph);
RLOGS(0, "\nMass is %f [kg] = %f [N]", mGraph, 9.81*mGraph);
RcsGraph_destroy(graph);
REXEC(0)
{
if (valgrind==false)
{
std::string dottyCommand = "dotty " + std::string(dotFile) + "&";
int err = system(dottyCommand.c_str());
if (err == -1)
{
RMSG("Couldn't start dot file viewer!");
}
}
}
break;
}
// ==============================================================
// Forward kinematics
// ==============================================================
case 2:
{
Rcs::KeyCatcherBase::registerKey("a", "Change body attachement");
Rcs::KeyCatcherBase::registerKey("C", "Toggle COM display");
Rcs::KeyCatcherBase::registerKey("d", "Print dot file");
Rcs::KeyCatcherBase::registerKey("f", "Write graph to file");
Rcs::KeyCatcherBase::registerKey("j", "Create JointWidget");
Rcs::KeyCatcherBase::registerKey("l", "Reload graph file");
Rcs::KeyCatcherBase::registerKey("m", "Set q to model state");
Rcs::KeyCatcherBase::registerKey("p", "Print information to console");
Rcs::KeyCatcherBase::registerKey("q", "Quit");
Rcs::KeyCatcherBase::registerKey("W", "Merge bodies");
Rcs::KeyCatcherBase::registerKey("x", "Rewind bvh file");
Rcs::KeyCatcherBase::registerKey("e", "Remove body under mouse");
Rcs::KeyCatcherBase::registerKey("J", "Remove joints of body by name");
Rcs::KeyCatcherBase::registerKey("E", "Remove all joints of graph");
Rcs::KeyCatcherBase::registerKey("T", "Load trajectory file");
Rcs::KeyCatcherBase::registerKey("X", "Make monolithic");
Rcs::KeyCatcherBase::registerKey("S", "Scale graph");
Rcs::KeyCatcherBase::registerKey("b", "Boxify graph");
Rcs::KeyCatcherBase::registerKey("H", "Toggle HUD");
double dtSim = 0.0, dtStep = 0.04;
int fwdKinType = 0;
char hudText[512] = "", comRef[64] = "";
char dotFile[256] = "RcsGraph.dot";
char bgColor[64] = "LIGHT_GRAYISH_GREEN";
std::string fKinBdyName;
strcpy(xmlFileName, "gScenario.xml");
strcpy(directory, "config/xml/DexBot");
getModel(directory, xmlFileName);
argP.getArgument("-dt", &dtStep, "Animation time step (default is %f)",
dtStep);
argP.getArgument("-dotFile", dotFile, "Dot file name");
argP.getArgument("-f", xmlFileName, "Configuration file name (default"
" is \"%s\")", xmlFileName);
argP.getArgument("-dir", directory, "Configuration file directory "
"(default is \"%s\")", directory);
argP.getArgument("-comRef", comRef, "Reference body for COM (default is "
"root)");
argP.getArgument("-bgColor", bgColor, "Background color (default is "
"\"%s\")", bgColor);
argP.getArgument("-fKin", &fwdKinType, "Forward kinematics: 0: all dof,"
"1: sub tree, 2: body only (default is %d)", fwdKinType);
argP.getArgument("-fKinBdy", &fKinBdyName, "Forward kinematics start "
"body (default is none)");
bool testCopy = argP.hasArgument("-copy", "Test graph copying");
bool resizeable = argP.hasArgument("-resizeable", "Adjust visualization "
"of shapes dynamically");
bool editMode = argP.hasArgument("-edit", "Start in xml edit mode "
"(no Qt Gui)");
bool playBVH = argP.hasArgument("-bvh", "Play bvh file");
bool noHud = argP.hasArgument("-noHud", "Don't show HUD");
Rcs_addResourcePath(directory);
if (argP.hasArgument("-h"))
{
RMSG("Mode %d: Rcs -m %d -dir <graph-directory> -f "
"<graph-file>\n\n\t- Creates a graph from an xml file\n\t"
"- Creates a viewer (if option -valgrind is not set)\n\t"
"- Creates a JointWidget (if option -valgrind is not set)\n\t"
"- Runs the forward kinematics in a loop\n\n\t"
"The joints angles can be modified by the sliders\n",
mode, mode);
printf("\n\tForward kinematics:\n");
printf("\t-dir\t<directory=%s> Configuration file directory\n",
directory);
printf("\t-f\t<configFile=%s> Configuration file\n",
xmlFileName);
printf("\t-edit\t Don't launch JointWidget. Otherwise, reloading"
" doesn't work with the widget being active.\n");
printf("\n");
printf("\n");
printf("\tExamples: Rcs -m 2\n");
printf("\t-dir config/xml/LWR -f lbr_iiwa_14_r820.urdf\n");
printf("\t-dir config/xml/DarwinOP -f robotis_op.urdf\n");
printf("\t-dir config/xml/Husky -f dual_arm_husky_original.urdf\n");
printf("\t-dir config/xml/Valkyrie -f valkyrie_sim.urdf\n");
printf("\n");
break;
}
RcsGraph* graph = RcsGraph_create(xmlFileName);
if (graph == NULL)
{
RMSG("Failed to create graph from file \"%s\" - exiting",
xmlFileName);
break;
}
char bvhFile[256];
strcpy(bvhFile, graph->xmlFile);
argP.getArgument("-bvhFile", bvhFile, "BVH file "
"(default is \"%s\")", bvhFile);
MatNd* bvhTraj = NULL;
unsigned int bvhIdx = 0;
if (playBVH && String_hasEnding(bvhFile, ".bvh", false))
{
bvhTraj = RcsGraph_createTrajectoryFromBVHFile(graph, bvhFile,
&dtStep, 0.01,
M_PI/180.0);
if (bvhTraj && (bvhTraj->n!=graph->dof))
{
RLOG(1, "Mismatch in bvh array dimensions: found %d columns, but "
"graph has %d dof", bvhTraj->n, graph->dof);
MatNd_destroy(bvhTraj);
bvhTraj = NULL;
}
}
if (testCopy==true)
{
RcsGraph* graph2 = graph;
double t_copy = Timer_getSystemTime();
graph = RcsGraph_clone(graph2);
t_copy = Timer_getSystemTime() - t_copy;
RcsGraph_destroy(graph2);
RMSG("Copying graph took %.3f msec", t_copy*1.0e3);
}
const RcsBody* comBase = RcsGraph_getBodyByName(graph, comRef);
RCSGRAPH_TRAVERSE_JOINTS(graph)
{
JNT->constrained = true;
}
int guiHandle = -1;
unsigned int loopCount = 0;
double mass = 0.0, Id[3][3], r_com[3];
Mat3d_setIdentity(Id);
Vec3d_setZero(r_com);
Rcs::KeyCatcher* kc = NULL;
Rcs::GraphNode* gn = NULL;
Rcs::CapsuleNode* comNd = NULL;
Rcs::HUD* hud = NULL;
Rcs::Viewer* viewer = NULL;
if (!valgrind)
{
viewer = new Rcs::Viewer(!simpleGraphics, !simpleGraphics);
viewer->setBackgroundColor(bgColor);
gn = new Rcs::GraphNode(graph, resizeable);
gn->toggleReferenceFrames();
viewer->add(gn);
comNd = new Rcs::CapsuleNode(r_com, Id, 0.05, 0.0);
comNd->makeDynamic(r_com);
comNd->setMaterial("RED");
comNd->toggleWireframe();
comNd->hide();
viewer->add(comNd);
char xmlFile2[64] = "";
argP.getArgument("-f2", xmlFile2, "Optional second graph file (default"
"is empty)");
if (strlen(xmlFile2) > 0)
{
RcsGraph* graph2 = RcsGraph_create(xmlFile2);
RCHECK(graph2);
viewer->add(new Rcs::GraphNode(graph2, resizeable));
}
if (!noHud)
{
hud = new Rcs::HUD();
viewer->add(hud);
}
kc = new Rcs::KeyCatcher();
viewer->add(kc);
RCSGRAPH_TRAVERSE_SENSORS(graph)
{
if (SENSOR->type==RCSSENSOR_PPS)
{
bool debug = RcsLogLevel > 0 ? true : false;
viewer->add(new Rcs::PPSSensorNode(SENSOR, debug));
}
}
viewer->runInThread(mtx);
if ((editMode==false) && (bvhTraj==NULL))
{
guiHandle = Rcs::JointWidget::create(graph, mtx);
}
}
REXEC(5)
{
RPAUSE_MSG("Hit enter to start kinematics computation loop");
}
while (runLoop)
{
pthread_mutex_lock(&graphLock);
if (valgrind)
{
RLOG(1, "Starting step");
}
if (graph != NULL)
{
if (bvhTraj!=NULL)
{
MatNd row = MatNd_getRowViewTranspose(bvhTraj, bvhIdx);
MatNd_copy(graph->q, &row);
bvhIdx++;
if (bvhIdx >= bvhTraj->m)
{
bvhIdx = 0;
}
}
dtSim = Timer_getSystemTime();
switch (fwdKinType)
{
case 0:
RcsGraph_setState(graph, NULL, NULL);
break;
case 1:
{
RcsBody* fkBdy = RcsGraph_getBodyByName(graph, fKinBdyName.c_str());
RcsGraph_computeBodyKinematics(graph, fkBdy, NULL, NULL, true);
}
break;
case 2:
{
RcsBody* fkBdy = RcsGraph_getBodyByName(graph, fKinBdyName.c_str());
RcsGraph_computeBodyKinematics(graph, fkBdy, NULL, NULL, false);
}
break;
default:
RFATAL("No forward kinematics mode %d", fwdKinType);
}
dtSim = Timer_getSystemTime() - dtSim;
if (comBase != NULL)
{
mass = RcsGraph_COG_Body(comBase, r_com);
}
else
{
mass = RcsGraph_COG(graph, r_com);
}
}
if (valgrind)
{
RLOG(1, "Finished step");
if (valgrind==true && loopCount>10)
{
runLoop = false;
}
}
pthread_mutex_unlock(&graphLock);
if (kc != NULL)
{
if (kc->getAndResetKey('q'))
{
runLoop = false;
}
else if (kc->getAndResetKey('H'))
{
if (hud)
{
hud->toggle();
}
}
else if (kc->getAndResetKey('S'))
{
RMSG("Changing scale factor");
printf("Enter scaling factor: ");
double scaleFactor;
std::cin >> scaleFactor;
bool collisionVisible = gn->collisionModelVisible();
bool graphicsVisible = gn->graphicsModelVisible();
bool physicsVisible = gn->physicsModelVisible();
bool framesVisible = gn->referenceFramesVisible();
bool ghostVisible = gn->getGhostMode();
bool wireframeVisible = gn->getWireframe();
viewer->removeNode(gn);
gn = NULL;
pthread_mutex_lock(&graphLock);
RcsGraph_scale(graph, scaleFactor);
gn = new Rcs::GraphNode(graph);
gn->toggleReferenceFrames();
gn->displayGraphicsModel(graphicsVisible);
gn->displayPhysicsModel(physicsVisible);
gn->displayCollisionModel(collisionVisible);
gn->displayReferenceFrames(framesVisible);
gn->setGhostMode(ghostVisible);
gn->showWireframe(wireframeVisible);
pthread_mutex_unlock(&graphLock);
viewer->add(gn);
}
else if (kc->getAndResetKey('m'))
{
std::string mdlState;
RMSG("Changing model state");
printf("Enter name of model state: ");
std::cin >> mdlState;
pthread_mutex_lock(&graphLock);
bool ok = RcsGraph_setModelStateFromXML(graph, mdlState.c_str(), 0);
pthread_mutex_unlock(&graphLock);
RMSG("%s changing model state to %s",
ok ? "SUCCEEDED" : "FAILED", mdlState.c_str());
}
else if (kc->getAndResetKey('j'))
{
RMSGS("Creating JointWidget");
guiHandle = Rcs::JointWidget::create(graph, &graphLock);
}
else if (kc->getAndResetKey('e'))
{
Rcs::BodyNode* bNd =
viewer->getBodyNodeUnderMouse<Rcs::BodyNode*>();
if (bNd==NULL)
{
RMSG("No BodyNode found under mouse");
continue;
}
RMSG("Removing body \"%s\" under mouse", bNd->body()->name);
pthread_mutex_lock(&graphLock);
bool ok = RcsGraph_removeBody(graph, bNd->body()->name, NULL, 0);
if (ok)
{
ok = gn->removeBodyNode(bNd);
}
pthread_mutex_unlock(&graphLock);
RMSG("%s removing body", ok ? "SUCCEESS" : "FAILURE");
}
else if (kc->getAndResetKey('J'))
{
std::string bodyName;
RMSG("Removing all joints of a body");
printf("Enter body name: ");
std::cin >> bodyName;
RcsBody* bdy = RcsGraph_getBodyByName(graph, bodyName.c_str());
bool success = RcsBody_removeJoints(bdy, graph);
RMSG("Removing all joints of a body %s %s", bodyName.c_str(),
success ? "SUCCEEDED" : "FAILED");
}
else if (kc->getAndResetKey('E'))
{
RMSG("Removing all joints of graph");
pthread_mutex_lock(&graphLock);
RCSGRAPH_TRAVERSE_BODIES(graph)
{
bool success = RcsBody_removeJoints(BODY, graph);
RLOG(1, "Removing all joints of a body %s %s", BODY->name,
success ? "SUCCEEDED" : "FAILED");
}
pthread_mutex_unlock(&graphLock);
}
else if (kc->getAndResetKey('C'))
{
RMSGS("Toggling COM");
comNd->toggle();
}
else if (kc->getAndResetKey('f'))
{
RMSG("Writing graph to xml file");
FILE* out = fopen("graph.txt", "w+");
RcsGraph_fprint(out, graph);
fclose(out);
out = fopen("graph.xml", "w+");
RcsGraph_fprintXML(out, graph);
fclose(out);
}
else if (kc->getAndResetKey('d'))
{
RMSGS("Writing dot file");
RcsGraph_writeDotFile(graph, dotFile);
char osCmd[256];
sprintf(osCmd, "dotty %s&", dotFile);
int err = system(osCmd);
if (err == -1)
{
RMSG("Couldn't start dot file viewer!");
}
}
else if (kc->getAndResetKey('a'))
{
std::string parentName, childName;
RMSG("Changing body childName");
printf("Enter body to attach (parent): ");
std::cin >> parentName;
printf("Enter attachement (child) body: ");
std::cin >> childName;
RcsBody* child = RcsGraph_getBodyByName(graph, parentName.c_str());
RcsBody* parent = RcsGraph_getBodyByName(graph, childName.c_str());
RLOG(0, "Attaching \"%s\" (%s) to \"%s\" (%s)",
child ? child->name : "NULL", childName.c_str(),
parent ? parent->name : "NULL", parentName.c_str());
HTr A_KV;
HTr_setIdentity(&A_KV);
HTr_invTransform(&A_KV, parent ? parent->A_BI : HTr_identity(),
child ? child->A_BI : HTr_identity());
if (child && child->rigid_body_joints == true)
{
RcsJoint* jPtr = child->jnt;
while (jPtr->next != NULL)
{
MatNd_set(graph->q, jPtr->jointIndex, 0, 0.0);
jPtr = jPtr->next;
}
}
bool success = RcsBody_attachToBody(graph, child, parent, &A_KV);
RMSG("%s changing body attachement",
success ? "SUCCESS" : "FAILURE");
RcsGraph_fprintJointRecursion(stdout, graph, parentName.c_str());
}
else if (kc->getAndResetKey('p'))
{
if (graph != NULL)
{
RMSG("Here's the forward tree:");
RcsGraph_fprint(stderr, graph);
RLOGS(0, "m=%f r_com=%f %f %f",
mass, r_com[0], r_com[1], r_com[2]);
RcsGraph_fprintModelState(stdout, graph, graph->q);
}
}
else if (kc->getAndResetKey('b'))
{
RMSG("Boxifying graph ...");
viewer->removeNode(gn);
pthread_mutex_lock(&graphLock);
gn = NULL;
RCSGRAPH_TRAVERSE_BODIES(graph)
{
bool success = RcsBody_boxify(BODY, RCSSHAPE_COMPUTE_GRAPHICS+
RCSSHAPE_COMPUTE_PHYSICS);
RLOG(0, "%s boxifying body %s", success ? "SUCCESS" : "FAILURE",
BODY->name);
}
gn = new Rcs::GraphNode(graph);
pthread_mutex_unlock(&graphLock);
viewer->add(gn);
RMSG("... done boxifying graph");
}
else if (kc->getAndResetKey('l'))
{
RMSG("Reloading GraphNode from %s", xmlFileName);
if (guiHandle != -1)
{
bool success = RcsGuiFactory_destroyGUI(guiHandle);
RLOG(0, "%s destroyed Gui", success ? "Successfully" : "Not");
}
bool collisionVisible = gn->collisionModelVisible();
bool graphicsVisible = gn->graphicsModelVisible();
bool physicsVisible = gn->physicsModelVisible();
bool framesVisible = gn->referenceFramesVisible();
bool ghostVisible = gn->getGhostMode();
bool wireframeVisible = gn->getWireframe();
viewer->removeNode(gn);
viewer->removeNode("PPSSensorNode");
pthread_mutex_lock(&graphLock);
gn = NULL;
RcsGraph_destroy(graph);
graph = RcsGraph_create(xmlFileName);
comBase = RcsGraph_getBodyByName(graph, comRef);
if (graph != NULL)
{
gn = new Rcs::GraphNode(graph);
gn->toggleReferenceFrames();
gn->displayGraphicsModel(graphicsVisible);
gn->displayPhysicsModel(physicsVisible);
gn->displayCollisionModel(collisionVisible);
gn->displayReferenceFrames(framesVisible);
gn->setGhostMode(ghostVisible);
gn->showWireframe(wireframeVisible);
pthread_mutex_unlock(&graphLock);
viewer->add(gn);
pthread_mutex_lock(&graphLock);
}
else
{
RLOG(1, "Couldn't create graph - skipping osg "
"node");
}
pthread_mutex_unlock(&graphLock);
RMSG("... done");
}
else if (kc->getAndResetKey('W'))
{
RMSG("Merging bodies. Here are the options:");
int nBodiesMergeable = 0;
RCSGRAPH_TRAVERSE_BODIES(graph)
{
if (BODY->jnt==NULL && BODY!=graph->root)
{
printf(" %s\n", BODY->name);
nBodiesMergeable++;
}
}
if (nBodiesMergeable>0)
{
std::string bdyName;
printf("Enter body to merge: ");
std::cin >> bdyName;
pthread_mutex_lock(&graphLock);
bool success = RcsBody_mergeWithParent(graph, bdyName.c_str());
RMSG("%s merging body %s", success ? "SUCCEEDED" : "FAILED",
bdyName.c_str());
if (success==true)
{
FILE* fd = fopen("merged.xml", "w+");
RCHECK(fd);
RcsGraph_fprintXML(fd, graph);
fclose(fd);
}
pthread_mutex_unlock(&graphLock);
viewer->removeNode(gn);
gn = NULL;
gn = new Rcs::GraphNode(graph);
gn->toggleReferenceFrames();
viewer->add(gn);
}
else
{
RMSG("There are no more bodies to merge");
}
}
else if (kc->getAndResetKey('x'))
{
RMSG("Rewinding BVH file");
bvhIdx = 0;
}
else if (kc->getAndResetKey('T'))
{
RMSG("Loading trajectory file");
std::string tFile;
printf("Enter file name: ");
std::cin >> tFile;
MatNd* newTraj = MatNd_createFromFile(tFile.c_str());
if ((newTraj!=NULL) && (newTraj->n==graph->dof))
{
MatNd_destroy(bvhTraj);
bvhTraj = newTraj;
bvhIdx = 0;
}
else
{
RLOG(1, "Failed to read trajectory file \"%s\"", tFile.c_str());
}
}
else if (kc->getAndResetKey('X'))
{
RMSG("Merging graph to a single rigid body");
pthread_mutex_lock(&graphLock);
RMSG("Removing all joints of graph");
RCSGRAPH_TRAVERSE_BODIES(graph)
{
bool success = RcsBody_removeJoints(BODY, graph);
RMSG("Removing all joints of a body %s %s", BODY->name,
success ? "SUCCEEDED" : "FAILED");
}
RcsBody* first = RcsBody_depthFirstTraversalGetNext(graph->root);
while (first)
{
bool success = RcsBody_mergeWithParent(graph, first->name);
RMSG("%s to merge body %s with root",
success ? "SUCCEEDED" : "FAILED", first->name);
first = RcsBody_depthFirstTraversalGetNext(graph->root);
RMSG("Next body to merge: \"%s\"", first ? first->name : "NULL");
RPAUSE();
}
pthread_mutex_unlock(&graphLock);
viewer->removeNode(gn);
gn = NULL;
gn = new Rcs::GraphNode(graph);
gn->toggleReferenceFrames();
viewer->add(gn);
}
} // KeyCatcher
sprintf(hudText, "Graph \"%s\"\nDof: %d nJ: %d\n"
"Forward kinematics step: %.1f ms\n",
graph->xmlFile, graph->dof, graph->nJ, dtSim*1000.0);
if (bvhTraj!=NULL)
{
char a[256];
sprintf(a, "BVH row %d (from %d)\n", bvhIdx, bvhTraj->m);
strcat(hudText, a);
}
if (hud != NULL)
{
hud->setText(hudText);