-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNatNetLinux.cpp
More file actions
1418 lines (1270 loc) · 52.1 KB
/
NatNetLinux.cpp
File metadata and controls
1418 lines (1270 loc) · 52.1 KB
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
/*********************************************************************
* \page SampleClient.cpp
* \file SampleClient.cpp
* \brief Sample client using NatNet library
* This program connects to a NatNet server, receives a data stream, and writes that data stream
* to an ascii file. The purpose is to illustrate using the NatNetClient class.
* Usage [optional]:
* SampleClient [ServerIP] [LocalIP] [OutputFilename]
* [ServerIP] IP address of the server (e.g. 192.168.0.107) ( defaults to local machine)
* [OutputFilename] Name of points file (pts) to write out. defaults to Client-output.pts
*********************************************************************/
/*
Copyright © 2012 NaturalPoint Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include <inttypes.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#ifdef _WIN32
#include <conio.h>
#else
#include <unistd.h>
#include <termios.h>
#include <stdio.h>
#include <sys/select.h>
#include <sys/ioctl.h>
#endif
// stl
#include <map>
#include <string>
#include <vector>
#include <deque>
#include <thread>
#include <mutex>
#include <memory>
using namespace std;
#include <NatNetTypes.h>
#include <NatNetCAPI.h>
#include <NatNetClient.h>
#ifndef _WIN32
char getch();
int _kbhit();
#endif
// NatNet Callbacks
void NATNET_CALLCONV ServerDiscoveredCallback(const sNatNetDiscoveredServer* pDiscoveredServer, void* pUserContext);
void NATNET_CALLCONV DataHandler(sFrameOfMocapData* data, void* pUserData); // receives data from the server
void NATNET_CALLCONV MessageHandler(Verbosity msgType, const char* msg); // receives NatNet error messages
// Write output to file
void WriteHeader(FILE* fp, sDataDescriptions* pDataDefs);
void WriteFrame(FILE* fp, sFrameOfMocapData* data);
void WriteFooter(FILE* fp);
// Helper functions
void ResetClient();
int ConnectClient();
bool UpdateDataDescriptions(bool printToConsole);
void UpdateDataToDescriptionMaps(sDataDescriptions* pDataDefs);
void PrintDataDescriptions(sDataDescriptions* pDataDefs);
int ProcessKeyboardInput();
int SetGetProperty(char* szSetGetCommand);
void OutputFrameQueueToConsole();
static const ConnectionType kDefaultConnectionType = ConnectionType_Multicast;
//static const ConnectionType kDefaultConnectionType = ConnectionType_Unicast;
static const int kMaxMessageLength = 256;
// Connection variables
NatNetClient* g_pClient = NULL;
sNatNetClientConnectParams g_connectParams;
sServerDescription g_serverDescription;
// Server Discovery (optional)
vector< sNatNetDiscoveredServer > g_discoveredServers;
char g_discoveredMulticastGroupAddr[kNatNetIpv4AddrStrLenMax] = NATNET_DEFAULT_MULTICAST_ADDRESS;
// DataDescriptions to Frame Data Lookup maps
sDataDescriptions* g_pDataDefs = NULL;
map<int, int> g_AssetIDtoAssetDescriptionOrder;
map<int, string> g_AssetIDtoAssetName;
bool gUpdatedDataDescriptions = false;
bool gNeedUpdatedDataDescriptions = true;
string strDefaultLocal = "";
string strDefaultMotive = "";
// Frame Queue
typedef struct MocapFrameWrapper
{
shared_ptr<sFrameOfMocapData> data;
double transitLatencyMillisec;
double clientLatencyMillisec;
} MocapFrameWrapper;
std::timed_mutex gNetworkQueueMutex;
std::deque<MocapFrameWrapper> gNetworkQueue;
const int kMaxQueueSize = 500;
// Misc
FILE* g_outputFile = NULL;
int g_analogSamplesPerMocapFrame = 0;
float gSmoothingValue = 0.1f;
bool gPauseOutput = false;
void printfBits(uint64_t val, int nBits)
{
for (int i = nBits - 1; i >= 0; i--)
{
printf("%d", (int) (val >> i) & 0x01);
}
printf("\n");
}
/**
* \brief Simple NatNet client
*
* \param argc Number of input arguments.
* \param argv Array of input arguments.
* \return NatNetTypes.h error code.
*/
int main( int argc, char* argv[] )
{
// Print NatNet client version info
unsigned char ver[4];
NatNet_GetVersion( ver );
printf( "NatNet Sample Client (NatNet ver. %d.%d.%d.%d)\n", ver[0], ver[1], ver[2], ver[3] );
// Install logging callback
NatNet_SetLogCallback( MessageHandler );
// Create NatNet client
g_pClient = new NatNetClient();
// Set the frame callback handler
g_pClient->SetFrameReceivedCallback( DataHandler, g_pClient ); // this function will receive data from the server
// [Optional] Automatic Motive server discovery
// If no arguments were specified on the command line, attempt to discover servers on the local network.
if ( (argc == 1) && (strDefaultLocal.empty() && strDefaultMotive.empty()) )
{
// An example of synchronous server discovery.
#if 0
const unsigned int kDiscoveryWaitTimeMillisec = 5 * 1000; // Wait 5 seconds for responses.
const int kMaxDescriptions = 10; // Get info for, at most, the first 10 servers to respond.
sNatNetDiscoveredServer servers[kMaxDescriptions];
int actualNumDescriptions = kMaxDescriptions;
NatNet_BroadcastServerDiscovery( servers, &actualNumDescriptions );
if ( actualNumDescriptions < kMaxDescriptions )
{
// If this happens, more servers responded than the array was able to store.
}
#endif
// Do asynchronous server discovery.
printf( "Looking for servers on the local network.\n" );
printf( "Press the number key that corresponds to any discovered server to connect to that server.\n" );
printf( "Press Q at any time to quit.\n\n" );
NatNetDiscoveryHandle discovery;
NatNet_CreateAsyncServerDiscovery( &discovery, ServerDiscoveredCallback );
while ( const int c = getch() )
{
if ( c >= '1' && c <= '9' )
{
const size_t serverIndex = c - '1';
if ( serverIndex < g_discoveredServers.size() )
{
const sNatNetDiscoveredServer& discoveredServer = g_discoveredServers[serverIndex];
if ( discoveredServer.serverDescription.bConnectionInfoValid )
{
// Build the connection parameters.
#ifdef _WIN32
_snprintf_s(
#else
snprintf(
#endif
g_discoveredMulticastGroupAddr, sizeof g_discoveredMulticastGroupAddr,
"%" PRIu8 ".%" PRIu8".%" PRIu8".%" PRIu8"",
discoveredServer.serverDescription.ConnectionMulticastAddress[0],
discoveredServer.serverDescription.ConnectionMulticastAddress[1],
discoveredServer.serverDescription.ConnectionMulticastAddress[2],
discoveredServer.serverDescription.ConnectionMulticastAddress[3]
);
g_connectParams.connectionType = discoveredServer.serverDescription.ConnectionMulticast ? ConnectionType_Multicast : ConnectionType_Unicast;
g_connectParams.serverCommandPort = discoveredServer.serverCommandPort;
g_connectParams.serverDataPort = discoveredServer.serverDescription.ConnectionDataPort;
g_connectParams.serverAddress = discoveredServer.serverAddress;
g_connectParams.localAddress = discoveredServer.localAddress;
g_connectParams.multicastAddress = g_discoveredMulticastGroupAddr;
}
else
{
// We're missing some info because it's a legacy server.
// Guess the defaults and make a best effort attempt to connect.
g_connectParams.connectionType = kDefaultConnectionType;
g_connectParams.serverCommandPort = discoveredServer.serverCommandPort;
g_connectParams.serverDataPort = 0;
g_connectParams.serverAddress = discoveredServer.serverAddress;
g_connectParams.localAddress = discoveredServer.localAddress;
g_connectParams.multicastAddress = NULL;
}
break;
}
}
else if ( c == 'q' )
{
return 0;
}
}
NatNet_FreeAsyncServerDiscovery( discovery );
}
else
{
// Manually specify Motive server IP/connection type
g_connectParams.connectionType = kDefaultConnectionType;
g_connectParams.localAddress = strDefaultLocal.c_str();
g_connectParams.serverAddress = strDefaultMotive.c_str();
g_connectParams.connectionType = kDefaultConnectionType;
g_connectParams.serverCommandPort = 1510;
g_connectParams.serverDataPort = 1511;
g_connectParams.multicastAddress = g_discoveredMulticastGroupAddr;
if ( argc >= 2 )
{
g_connectParams.serverAddress = argv[1];
}
if ( argc >= 3 )
{
g_connectParams.localAddress = argv[2];
}
}
// Connect to Motive
int iResult = ConnectClient();
if (iResult != ErrorCode_OK)
{
printf("Error initializing client. See log for details. Exiting.\n");
return 1;
}
else
{
printf("Client initialized and ready.\n");
}
// Get latest asset list from Motive
gUpdatedDataDescriptions = UpdateDataDescriptions(true);
if (!gUpdatedDataDescriptions)
{
printf("[SampleClient] ERROR : Unable to retrieve Data Descriptions from Motive.\n");
}
else
{
// Create data file for writing received stream into
const char* szFile = "Client-output.pts";
if (argc > 3)
{
szFile = argv[3];
}
g_outputFile = fopen(szFile, "w");
if (!g_outputFile)
{
printf("[SampleClient] Error opening output file %s. Exiting.\n", szFile);
}
else
{
WriteHeader(g_outputFile, g_pDataDefs);
}
}
// Main thread loop
// Data will be delivered in a separate thread to DataHandler() callback functon
printf("\n[SampleClient] Client is connected to server and listening for data...\n");
bool bRunning = true;
while (bRunning)
{
// If Motive Asset list has changed, update our lookup maps
if (gNeedUpdatedDataDescriptions)
{
gUpdatedDataDescriptions = UpdateDataDescriptions(false);
if (gUpdatedDataDescriptions)
{
gNeedUpdatedDataDescriptions = false;
}
}
// Process any keyboard commands
int keyboardInputChar = ProcessKeyboardInput();
if (keyboardInputChar == 'q')
{
bRunning = false;
}
// print all mocap frames in data queue to console
if (!gPauseOutput)
{
OutputFrameQueueToConsole();
}
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
// Exiting - clean up
if (g_pClient)
{
g_pClient->Disconnect();
delete g_pClient;
g_pClient = NULL;
}
if (g_outputFile)
{
WriteFooter(g_outputFile);
fclose(g_outputFile);
g_outputFile = NULL;
}
if (g_pDataDefs)
{
NatNet_FreeDescriptions(g_pDataDefs);
g_pDataDefs = NULL;
}
return ErrorCode_OK;
}
/**
* \brief Process Keyboard Input.
*
* \return Keyboard character.
*/
int ProcessKeyboardInput()
{
int keyboardChar = 0;
int iResult = 0;
void* response = nullptr;
int nBytes = 0;
if (_kbhit())
{
keyboardChar = getch();
switch (keyboardChar)
{
// Exit program
case 'q':
printf("\n\nQuitting...");
break;
// Disconnect and reconnect to Motive
case 'r':
ResetClient();
break;
// Get Motive description
case 'p':
sServerDescription ServerDescription;
memset(&ServerDescription, 0, sizeof(ServerDescription));
g_pClient->GetServerDescription(&ServerDescription);
if (!ServerDescription.HostPresent)
{
printf("[SampleClient] Unable to connect to Motive server.");
}
break;
// Update data descriptions ( Motive active asset list )
case 's':
printf("\n\n[SampleClient] Requesting Data Descriptions...");
gUpdatedDataDescriptions = UpdateDataDescriptions(true);
if (!gUpdatedDataDescriptions)
{
printf("[SampleClient] ERROR : Unable to retrieve Data Descriptions from Motive.\n");
}
else
{
gNeedUpdatedDataDescriptions = false;
}
break;
// Change connection type to multicast
case 'm':
g_connectParams.connectionType = ConnectionType_Multicast;
iResult = ConnectClient();
if (iResult == ErrorCode_OK)
printf("[SampleClient] Client connection type changed to Multicast.\n\n");
else
printf("[SampleClient] Error changing client connection type to Multicast.\n\n");
break;
// Change connection type to unicast
case 'u':
g_connectParams.connectionType = ConnectionType_Unicast;
iResult = ConnectClient();
if (iResult == ErrorCode_OK)
printf("[SampleClient] Client connection type changed to Unicast.\n\n");
else
printf("[SampleClient] Error changing client connection type to Unicast.\n\n");
break;
// Connect to Motive
case 'c':
iResult = ConnectClient();
break;
// Disconnect from Motive
// note: applies to unicast connections only - indicates to Motive to stop sending packets
// to this client's endpoint
case 'd':
iResult = g_pClient->SendMessageAndWait("Disconnect", &response, &nBytes);
if (iResult == ErrorCode_OK)
printf("[SampleClient] Disconnected");
else
printf("[SampleClient] Error Disconnecting");
break;
// test command : get framerate
case 'f' :
iResult = g_pClient->SendMessageAndWait("FrameRate", &response, &nBytes);
if (iResult == ErrorCode_OK)
{
float fRate = *((float*)response);
printf("Mocap Framerate : %3.2f\n", fRate);
}
else
{
printf("Error getting frame rate.\n");
}
break;
// test command : Set / Get a RigidBody property
case 'e':
{
// Note : Smoothing value is actually float [0.0,1.0]. Motive UI formats it to [0-100]
char szCommand[kMaxMessageLength];
sprintf(szCommand, "SetProperty,RigidBody1,Smoothing,%f", gSmoothingValue);
SetGetProperty(szCommand);
gSmoothingValue += .1f;
}
break;
case 'z':
gPauseOutput = !gPauseOutput;
if (gPauseOutput)
{
printf("\n\n--- Console Data Output Paused ---\n\n");
}
else
{
printf("\n\n--- Console Data Output Resumed ---\n\n");
}
break;
default:
break;
}
}
return keyboardChar;
}
/**
* \brief [optional] called by NatNet with a list of automatically discovered Motive instances on the network(s).
*
* \param pDiscoveredServer
* \param pUserContext
* \return
*/
void NATNET_CALLCONV ServerDiscoveredCallback( const sNatNetDiscoveredServer* pDiscoveredServer, void* pUserContext )
{
char serverHotkey = '.';
if ( g_discoveredServers.size() < 9 )
{
serverHotkey = static_cast<char>('1' + g_discoveredServers.size());
}
printf( "[%c] %s %d.%d.%d at %s ",
serverHotkey,
pDiscoveredServer->serverDescription.szHostApp,
pDiscoveredServer->serverDescription.HostAppVersion[0],
pDiscoveredServer->serverDescription.HostAppVersion[1],
pDiscoveredServer->serverDescription.HostAppVersion[2],
pDiscoveredServer->serverAddress);
if ( pDiscoveredServer->serverDescription.bConnectionInfoValid )
{
printf( "(%s)", pDiscoveredServer->serverDescription.ConnectionMulticast ? "multicast" : "unicast" );
}
else
{
printf( "(WARNING: Legacy server, could not auto-detect settings. Auto-connect may not work reliably.)" );
}
printf( " from %s\n", pDiscoveredServer->localAddress );
g_discoveredServers.push_back( *pDiscoveredServer );
}
/**
* \brief Establish a NatNet Client connection.
*
* \return
*/
int ConnectClient()
{
// Disconnect from any previous server (if connected)
g_pClient->Disconnect();
// Connect to NatNet server (e.g. Motive)
int retCode = g_pClient->Connect( g_connectParams );
if (retCode != ErrorCode_OK)
{
// Connection failed - print connection error code
printf("[SampleClinet] Unable to connect to server. Error code: %d. Exiting.\n", retCode);
return ErrorCode_Internal;
}
else
{
// Connection succeeded
void* pResult;
int nBytes = 0;
ErrorCode ret = ErrorCode_OK;
// example : print server info
memset(&g_serverDescription, 0, sizeof(g_serverDescription));
ret = g_pClient->GetServerDescription(&g_serverDescription);
if (ret != ErrorCode_OK || !g_serverDescription.HostPresent)
{
printf("[SampleClient] Unable to connect to server. Host not present. Exiting.\n");
return 1;
}
printf("\n[SampleClient] Server application info:\n");
printf("Application: %s (ver. %d.%d.%d.%d)\n", g_serverDescription.szHostApp, g_serverDescription.HostAppVersion[0],
g_serverDescription.HostAppVersion[1], g_serverDescription.HostAppVersion[2], g_serverDescription.HostAppVersion[3]);
printf("NatNet Version: %d.%d.%d.%d\n", g_serverDescription.NatNetVersion[0], g_serverDescription.NatNetVersion[1],
g_serverDescription.NatNetVersion[2], g_serverDescription.NatNetVersion[3]);
printf("Client IP:%s\n", g_connectParams.localAddress);
printf("Server IP:%s\n", g_connectParams.serverAddress);
printf("Server Name:%s\n", g_serverDescription.szHostComputerName);
// example : get mocap frame rate
ret = g_pClient->SendMessageAndWait("FrameRate", &pResult, &nBytes);
if (ret == ErrorCode_OK)
{
float fRate = *((float*)pResult);
printf("Mocap Framerate : %3.2f\n", fRate);
}
else
{
printf("Error getting frame rate.\n");
}
}
return ErrorCode_OK;
}
/**
* \brief Get the latest active assets list from Motive.
*
* \param printToConsole
* \return
*/
bool UpdateDataDescriptions(bool printToConsole)
{
// release memory allocated by previous in previous GetDataDescriptionList()
if (g_pDataDefs)
{
NatNet_FreeDescriptions(g_pDataDefs);
}
// Retrieve Data Descriptions from Motive
printf("\n\n[SampleClient] Requesting Data Descriptions...\n");
int iResult = g_pClient->GetDataDescriptionList(&g_pDataDefs);
if (iResult != ErrorCode_OK || g_pDataDefs == NULL)
{
return false;
}
else
{
if (printToConsole)
{
PrintDataDescriptions(g_pDataDefs);
}
}
UpdateDataToDescriptionMaps(g_pDataDefs);
return true;
}
/**
* Print data descriptions to std out.
*
* \param pDataDefs
*/
void PrintDataDescriptions(sDataDescriptions* pDataDefs)
{
printf("[SampleClient] Received %d Data Descriptions:\n", pDataDefs->nDataDescriptions);
for (int i = 0; i < pDataDefs->nDataDescriptions; i++)
{
printf("Data Description # %d (type=%d)\n", i, pDataDefs->arrDataDescriptions[i].type);
if (pDataDefs->arrDataDescriptions[i].type == Descriptor_MarkerSet)
{
// MarkerSet
sMarkerSetDescription* pMS = pDataDefs->arrDataDescriptions[i].Data.MarkerSetDescription;
printf("MarkerSet Name : %s\n", pMS->szName);
for (int i = 0; i < pMS->nMarkers; i++)
printf("%s\n", pMS->szMarkerNames[i]);
}
else if (pDataDefs->arrDataDescriptions[i].type == Descriptor_RigidBody)
{
// RigidBody
sRigidBodyDescription* pRB = pDataDefs->arrDataDescriptions[i].Data.RigidBodyDescription;
printf("RigidBody Name : %s\n", pRB->szName);
printf("RigidBody ID : %d\n", pRB->ID);
printf("RigidBody Parent ID : %d\n", pRB->parentID);
printf("Parent Offset : %3.2f,%3.2f,%3.2f\n", pRB->offsetx, pRB->offsety, pRB->offsetz);
if (pRB->MarkerPositions != NULL && pRB->MarkerRequiredLabels != NULL)
{
for (int markerIdx = 0; markerIdx < pRB->nMarkers; ++markerIdx)
{
const MarkerData& markerPosition = pRB->MarkerPositions[markerIdx];
const int markerRequiredLabel = pRB->MarkerRequiredLabels[markerIdx];
printf("\tMarker #%d:\n", markerIdx);
printf("\t\tPosition: %.2f, %.2f, %.2f\n", markerPosition[0], markerPosition[1], markerPosition[2]);
if (markerRequiredLabel != 0)
{
printf("\t\tRequired active label: %d\n", markerRequiredLabel);
}
}
}
}
else if (pDataDefs->arrDataDescriptions[i].type == Descriptor_Skeleton)
{
// Skeleton
sSkeletonDescription* pSK = pDataDefs->arrDataDescriptions[i].Data.SkeletonDescription;
printf("Skeleton Name : %s\n", pSK->szName);
printf("Skeleton ID : %d\n", pSK->skeletonID);
printf("RigidBody (Bone) Count : %d\n", pSK->nRigidBodies);
for (int j = 0; j < pSK->nRigidBodies; j++)
{
sRigidBodyDescription* pRB = &pSK->RigidBodies[j];
printf(" RigidBody Name : %s\n", pRB->szName);
printf(" RigidBody ID : %d\n", pRB->ID);
printf(" RigidBody Parent ID : %d\n", pRB->parentID);
printf(" Parent Offset : %3.2f,%3.2f,%3.2f\n", pRB->offsetx, pRB->offsety, pRB->offsetz);
}
}
else if (pDataDefs->arrDataDescriptions[i].type == Descriptor_Asset)
{
// Trained Markerset
sAssetDescription* pAsset = pDataDefs->arrDataDescriptions[i].Data.AssetDescription;
printf("Trained Markerset Name : %s\n", pAsset->szName);
printf("Asset ID : %d\n", pAsset->AssetID);
// Trained Markerset Rigid Bodies
printf("Trained Markerset RigidBody (Bone) Count : %d\n", pAsset->nRigidBodies);
for (int j = 0; j < pAsset->nRigidBodies; j++)
{
sRigidBodyDescription* pRB = &pAsset->RigidBodies[j];
printf(" RigidBody Name : %s\n", pRB->szName);
printf(" RigidBody ID : %d\n", pRB->ID);
printf(" RigidBody Parent ID : %d\n", pRB->parentID);
printf(" Parent Offset : %3.2f,%3.2f,%3.2f\n", pRB->offsetx, pRB->offsety, pRB->offsetz);
}
// Trained Markerset Markers
printf("Trained Markerset Marker Count : %d\n", pAsset->nMarkers);
for (int j = 0; j < pAsset->nMarkers; j++)
{
sMarkerDescription marker = pAsset->Markers[j];
int modelID, markerID;
NatNet_DecodeID(marker.ID, &modelID, &markerID);
printf(" Marker Name : %s\n", marker.szName);
printf(" Marker ID : %d\n", markerID);
printf(" Marker Params : ");
printfBits(marker.params, sizeof(marker.params) * 8);
}
}
else if (pDataDefs->arrDataDescriptions[i].type == Descriptor_ForcePlate)
{
// Force Plate
sForcePlateDescription* pFP = pDataDefs->arrDataDescriptions[i].Data.ForcePlateDescription;
printf("Force Plate ID : %d\n", pFP->ID);
printf("Force Plate Serial : %s\n", pFP->strSerialNo);
printf("Force Plate Width : %3.2f\n", pFP->fWidth);
printf("Force Plate Length : %3.2f\n", pFP->fLength);
printf("Force Plate Electrical Center Offset (%3.3f, %3.3f, %3.3f)\n", pFP->fOriginX, pFP->fOriginY, pFP->fOriginZ);
for (int iCorner = 0; iCorner < 4; iCorner++)
printf("Force Plate Corner %d : (%3.4f, %3.4f, %3.4f)\n", iCorner, pFP->fCorners[iCorner][0], pFP->fCorners[iCorner][1], pFP->fCorners[iCorner][2]);
printf("Force Plate Type : %d\n", pFP->iPlateType);
printf("Force Plate Data Type : %d\n", pFP->iChannelDataType);
printf("Force Plate Channel Count : %d\n", pFP->nChannels);
for (int iChannel = 0; iChannel < pFP->nChannels; iChannel++)
printf("\tChannel %d : %s\n", iChannel, pFP->szChannelNames[iChannel]);
}
else if (pDataDefs->arrDataDescriptions[i].type == Descriptor_Device)
{
// Peripheral Device
sDeviceDescription* pDevice = pDataDefs->arrDataDescriptions[i].Data.DeviceDescription;
printf("Device Name : %s\n", pDevice->strName);
printf("Device Serial : %s\n", pDevice->strSerialNo);
printf("Device ID : %d\n", pDevice->ID);
printf("Device Channel Count : %d\n", pDevice->nChannels);
for (int iChannel = 0; iChannel < pDevice->nChannels; iChannel++)
printf("\tChannel %d : %s\n", iChannel, pDevice->szChannelNames[iChannel]);
}
else if (pDataDefs->arrDataDescriptions[i].type == Descriptor_Camera)
{
// Camera
sCameraDescription* pCamera = pDataDefs->arrDataDescriptions[i].Data.CameraDescription;
printf("Camera Name : %s\n", pCamera->strName);
printf("Camera Position (%3.2f, %3.2f, %3.2f)\n", pCamera->x, pCamera->y, pCamera->z);
printf("Camera Orientation (%3.2f, %3.2f, %3.2f, %3.2f)\n", pCamera->qx, pCamera->qy, pCamera->qz, pCamera->qw);
}
else
{
// Unknown
printf("Unknown data type.\n");
}
}
}
/**
* Update maps whenever the asset list in Motive has changed (as indicated in the data packet's TrackedModelsChanged bit)
*
* \param pDataDefs
*/
void UpdateDataToDescriptionMaps(sDataDescriptions* pDataDefs)
{
g_AssetIDtoAssetDescriptionOrder.clear();
g_AssetIDtoAssetName.clear();
int assetID = 0;
std::string assetName = "";
int index = 0;
int cameraIndex = 0;
if (pDataDefs == nullptr || pDataDefs->nDataDescriptions <= 0)
return;
for (int i = 0; i < pDataDefs->nDataDescriptions; i++)
{
assetID = -1;
assetName = "";
if (pDataDefs->arrDataDescriptions[i].type == Descriptor_RigidBody)
{
sRigidBodyDescription* pRB = pDataDefs->arrDataDescriptions[i].Data.RigidBodyDescription;
assetID = pRB->ID;
assetName = std::string(pRB->szName);
}
else if (pDataDefs->arrDataDescriptions[i].type == Descriptor_Skeleton)
{
sSkeletonDescription* pSK = pDataDefs->arrDataDescriptions[i].Data.SkeletonDescription;
assetID = pSK->skeletonID;
assetName = std::string(pSK->szName);
// Add individual bones
// skip for now since id could clash with non-skeleton RigidBody ids in our RigidBody lookup table
/*
if (insertResult.second == true)
{
for (int j = 0; j < pSK->nRigidBodies; j++)
{
// Note:
// In the DataCallback packet (sFrameOfMocapData) skeleton bones (rigid bodies) ids are of the form:
// parent skeleton ID : high word (upper 16 bits of int)
// rigid body id : low word (lower 16 bits of int)
//
// In DataDescriptions packet (sDataDescriptions) they are not, so apply the data id format here
// for correct lookup during data callback
std::pair<std::map<int, std::string>::iterator, bool> insertBoneResult;
sRigidBodyDescription rb = pSK->RigidBodies[j];
int id = (rb.parentID << 16) | rb.ID;
std::string skeletonBoneName = string(pSK->szName) + (":") + string(rb.szName) + string(pSK->szName);
insertBoneResult = g_AssetIDtoAssetName.insert(id, skeletonBoneName);
}
}
*/
}
else if (pDataDefs->arrDataDescriptions[i].type == Descriptor_MarkerSet)
{
// Skip markersets for now as they dont have unique id's, but do increase the index
// as they are in the data packet
index++;
continue;
/*
sMarkerSetDescription* pDesc = pDataDefs->arrDataDescriptions[i].Data.MarkerSetDescription;
assetID = index;
assetName = pDesc->szName;
*/
}
else if (pDataDefs->arrDataDescriptions[i].type == Descriptor_ForcePlate)
{
sForcePlateDescription* pDesc = pDataDefs->arrDataDescriptions[i].Data.ForcePlateDescription;
assetID = pDesc->ID;
assetName = pDesc->strSerialNo;
}
else if (pDataDefs->arrDataDescriptions[i].type == Descriptor_Device)
{
sDeviceDescription* pDesc = pDataDefs->arrDataDescriptions[i].Data.DeviceDescription;
assetID = pDesc->ID;
assetName = std::string(pDesc->strName);
}
else if (pDataDefs->arrDataDescriptions[i].type == Descriptor_Camera)
{
// skip cameras as they are not in the data packet
continue;
}
else if (pDataDefs->arrDataDescriptions[i].type == Descriptor_Asset)
{
sAssetDescription* pDesc = pDataDefs->arrDataDescriptions[i].Data.AssetDescription;
assetID = pDesc->AssetID;
assetName = std::string(pDesc->szName);
}
if (assetID == -1)
{
printf("\n[SampleClient] Warning : Unknown data type in description list : %d\n", pDataDefs->arrDataDescriptions[i].type);
}
else
{
// Add to Asset ID to Asset Name map
std::pair<std::map<int, std::string>::iterator, bool> insertResult;
insertResult = g_AssetIDtoAssetName.insert(std::pair<int,std::string>(assetID, assetName));
if (insertResult.second == false)
{
printf("\n[SampleClient] Warning : Duplicate asset ID already in Name map (Existing:%d,%s\tNew:%d,%s\n)",
insertResult.first->first, insertResult.first->second.c_str(), assetID, assetName.c_str());
}
}
// Add to Asset ID to Asset Description Order map
if (assetID != -1)
{
std::pair<std::map<int, int>::iterator, bool> insertResult;
insertResult = g_AssetIDtoAssetDescriptionOrder.insert(std::pair<int, int>(assetID, index++));
if (insertResult.second == false)
{
printf("\n[SampleClient] Warning : Duplicate asset ID already in Order map (ID:%d\tOrder:%d\n)", insertResult.first->first, insertResult.first->second);
}
}
}
}
/**
* Output frame queue to console.
*
*/
void OutputFrameQueueToConsole()
{
// Add data from the network queue into our display queue in order to quickly
// free up access to the network queue.
std::deque<MocapFrameWrapper> displayQueue;
if (gNetworkQueueMutex.try_lock_for(std::chrono::milliseconds(5)))
{
for (MocapFrameWrapper f : gNetworkQueue)
{
displayQueue.push_back(f);
}
// Release all frames in network queue
gNetworkQueue.clear();
gNetworkQueueMutex.unlock();
}
// Now we can take our time displaying our data without
// worrying about interfering with the network processing queue.
for (MocapFrameWrapper f : displayQueue)
{
sFrameOfMocapData* data = f.data.get();
printf("\n===================== New Packet Arrived =============================\n");
printf("FrameID : %d\n", data->iFrame);
printf("Timestamp : %3.2lf\n", data->fTimestamp);
printf("Params : ");
printfBits(data->params, sizeof(data->params)*8);
// timecode - for systems with an eSync and SMPTE timecode generator - decode to values
int hour, minute, second, frame, subframe;
NatNet_DecodeTimecode(data->Timecode, data->TimecodeSubframe, &hour, &minute, &second, &frame, &subframe);
char szTimecode[128] = "";
NatNet_TimecodeStringify(data->Timecode, data->TimecodeSubframe, szTimecode, 128);
printf("Timecode : %s\n", szTimecode);
// Latency Metrics
//
// Software latency here is defined as the span of time between:
// a) The reception of a complete group of 2D frames from the camera system (CameraDataReceivedTimestamp)
// and
// b) The time immediately prior to the NatNet frame being transmitted over the network (TransmitTimestamp)
//
// This figure may appear slightly higher than the "software latency" reported in the Motive user interface,
// because it additionally includes the time spent preparing to stream the data via NatNet.
const uint64_t softwareLatencyHostTicks = data->TransmitTimestamp - data->CameraDataReceivedTimestamp;
const double softwareLatencyMillisec = (softwareLatencyHostTicks * 1000) / static_cast<double>(g_serverDescription.HighResClockFrequency);
printf("Motive Software latency : %.2lf milliseconds\n", softwareLatencyMillisec);
// Only recent versions of the Motive software in combination with Ethernet camera systems support system latency measurement.
// If it's unavailable (for example, with USB camera systems, or during playback), this field will be zero.
const bool bSystemLatencyAvailable = data->CameraMidExposureTimestamp != 0;
if (bSystemLatencyAvailable)
{
// System latency here is defined as the span of time between:
// a) The midpoint of the camera exposure window, and therefore the average age of the photons (CameraMidExposureTimestamp)
// and
// b) The time immediately prior to the NatNet frame being transmitted over the network (TransmitTimestamp)
const uint64_t systemLatencyHostTicks = data->TransmitTimestamp - data->CameraMidExposureTimestamp;
const double systemLatencyMillisec = (systemLatencyHostTicks * 1000) / static_cast<double>(g_serverDescription.HighResClockFrequency);
printf("Motive System latency : %.2lf milliseconds\n", systemLatencyMillisec);
// Transit latency is defined as the span of time between Motive transmitting the frame of data, and its reception by the client (now).
// The SecondsSinceHostTimestamp method relies on NatNetClient's internal clock synchronization with the server using Cristian's algorithm.
printf("NatNet Transit latency : %.2lf milliseconds\n", f.transitLatencyMillisec);
// Total Client latency is defined as the sum of system latency and the transit time taken to relay the data to the NatNet client.
// This is the all-inclusive measurement (photons to client processing).
// You could equivalently do the following (not accounting for time elapsed since we calculated transit latency above):
//const double clientLatencyMillisec = systemLatencyMillisec + transitLatencyMillisec;
printf("Total Client latency : %.2lf milliseconds \n", f.clientLatencyMillisec);
}
else
{
printf("Transit latency : %.2lf milliseconds\n", f.transitLatencyMillisec);
}
// precision timestamps (optionally present, typically PTP) (NatNet 4.1 and later)
if (data->PrecisionTimestampSecs != 0)
{
printf("Precision Timestamp Seconds : %d\n", data->PrecisionTimestampSecs);
printf("Precision Timestamp Fractional Seconds : %d\n", data->PrecisionTimestampFractionalSecs);
}
if (gNeedUpdatedDataDescriptions)
{
printf("\n\n[SampleClient] Waiting for updated asset list\n");
break;
}
bool bTrackedModelsChanged = ((data->params & 0x02) != 0);
if (bTrackedModelsChanged)
{
printf("\n\nMotive asset list changed. Requesting new data descriptions.\n");
gNeedUpdatedDataDescriptions = true;
break;
}
if (g_outputFile)
{
WriteFrame(g_outputFile, data);
}
bool bIsRecording = ((data->params & 0x01) != 0);
if (bIsRecording)
{
printf("\nRECORDING\n");
}
// Rigid Bodies
int i = 0;
printf("------------------------\n");
printf("Rigid Bodies [Count=%d]\n", data->nRigidBodies);
for (i = 0; i < data->nRigidBodies; i++)
{
// params
// 0x01 : bool, rigid body was successfully tracked in this frame
bool bTrackingValid = data->RigidBodies[i].params & 0x01;
int streamingID = data->RigidBodies[i].ID;
printf("%s [ID=%d Error(mm)=%.5f Tracked=%d]\n", g_AssetIDtoAssetName[streamingID].c_str(), streamingID, data->RigidBodies[i].MeanError*1000.0f, bTrackingValid);
printf("\tx\ty\tz\tqx\tqy\tqz\tqw\n");
printf("\t%3.2f\t%3.2f\t%3.2f\t%3.2f\t%3.2f\t%3.2f\t%3.2f\n",
data->RigidBodies[i].x,
data->RigidBodies[i].y,
data->RigidBodies[i].z,
data->RigidBodies[i].qx,
data->RigidBodies[i].qy,
data->RigidBodies[i].qz,
data->RigidBodies[i].qw);
}
// Skeletons
printf("------------------------\n");
printf("Skeletons [Count=%d]\n", data->nSkeletons);
for (i = 0; i < data->nSkeletons; i++)