This repository was archived by the owner on Dec 19, 2024. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathNewOmniDriverEmu.cpp
More file actions
547 lines (443 loc) · 18.7 KB
/
Copy pathNewOmniDriverEmu.cpp
File metadata and controls
547 lines (443 loc) · 18.7 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
/******************************************************************************
* SOFA, Simulation Open-Framework Architecture *
* (c) 2006 INRIA, USTL, UJF, CNRS, MGH *
* *
* This program is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include "NewOmniDriverEmu.h"
#include <sofa/core/ObjectFactory.h>
#include <sofa/core/objectmodel/HapticDeviceEvent.h>
#include <sofa/type/Quat.h>
//
////force feedback
#include <SofaHaptics/ForceFeedback.h>
#include <SofaHaptics/NullForceFeedback.h>
//
#include <sofa/simulation/AnimateBeginEvent.h>
#include <sofa/simulation/AnimateEndEvent.h>
#include <sofa/simulation/PauseEvent.h>
//
#include <sofa/simulation/Node.h>
#include <cstring>
#include <SofaOpenglVisual/OglModel.h>
#include <sofa/core/objectmodel/KeypressedEvent.h>
#include <sofa/core/objectmodel/KeyreleasedEvent.h>
#include <sofa/core/objectmodel/MouseEvent.h>
//sensable namespace
#include <pthread.h>
#include <thread>
double prevTime;
namespace sofa
{
namespace component
{
namespace controller
{
using namespace sofa::defaulttype;
using namespace core::behavior;
using namespace sofa::defaulttype;
NewOmniDriverEmu::NewOmniDriverEmu()
: forceScale(initData(&forceScale, 1.0, "forceScale","Default scaling factor applied to the force feedback"))
, scale(initData(&scale, 1.0, "scale","Default scale applied to the Phantom Coordinates. "))
, positionBase(initData(&positionBase, Vec3d(0,0,0), "positionBase","Position of the interface base in the scene world coordinates"))
, orientationBase(initData(&orientationBase, Quat(0,0,0,1), "orientationBase","Orientation of the interface base in the scene world coordinates"))
, positionTool(initData(&positionTool, Vec3d(0,0,0), "positionTool","Position of the tool in the omni end effector frame"))
, orientationTool(initData(&orientationTool, Quat(0,0,0,1), "orientationTool","Orientation of the tool in the omni end effector frame"))
, permanent(initData(&permanent, false, "permanent" , "Apply the force feedback permanently"))
, omniVisu(initData(&omniVisu, false, "omniVisu", "Visualize the position of the interface in the virtual scene"))
, simuFreq(initData(&simuFreq, 1000, "simuFreq", "frequency of the \"simulated Omni\""))
, simulateTranslation(initData(&simulateTranslation, false, "simulateTranslation", "do very naive \"translation simulation\" of omni, with constant orientation <0 0 0 1>"))
, trajPts(initData(&trajPts, "trajPoints","Trajectory positions"))
, trajTim(initData(&trajTim, "trajTiming","Trajectory timing"))
, visu_base(NULL)
, visu_end(NULL)
{
this->f_listening.setValue(true);
data.forceFeedback = new NullForceFeedback();
noDevice = false;
moveOmniBase = false;
executeAsynchro = false;
omniSimThreadCreated = false;
}
NewOmniDriverEmu::~NewOmniDriverEmu()
{
if (visu_base)
{
delete visu_base;
}
if (visu_end)
{
delete visu_end;
}
}
void NewOmniDriverEmu::cleanup()
{
sout << "NewOmniDriverEmu::cleanup()" << sendl;
}
void NewOmniDriverEmu::init()
{
std::cout << "[NewOmniEmu] init" << endl;
}
void *hapticSimuExecute( void *ptr )
{
NewOmniDriverEmu *omniDrv = (NewOmniDriverEmu*)ptr;
double timeScale = 1.0 / (double)CTime::getTicksPerSec();
double startTime, endTime, totalTime, realTimePrev = -1.0, realTimeAct;
double requiredTime = 1.0/double(omniDrv->simuFreq.getValue()) * 1.0/timeScale; // [us]
double timeCorrection = 0.1 * requiredTime;
int timeToSleep;
// construct the "trajectory"
NewOmniDriverEmu::VecCoord pts = omniDrv->trajPts.getValue();
unsigned int numPts = pts.size();
type::vector<double> tmg = omniDrv->trajTim.getValue();
unsigned int numSegs = tmg.size();
double stepTime = 1.0/omniDrv->simuFreq.getValue();
if (numSegs != (2*numPts - 1))
{
std::cerr << "Bad trajectory specification " << std::endl;
return(0);
}
NewOmniDriverEmu::VecCoord stepDiff;
type::vector<int> stepNum;
unsigned int seg = 0;
for (unsigned int np = 0; np < numPts; np++)
{
//for the point
unsigned int n = tmg[seg]*omniDrv->simuFreq.getValue();
stepNum.push_back(n);
cout << "N pts = " << n << endl;
NewOmniDriverEmu::Coord crd;
cout << " adding " << crd << endl;
stepDiff.push_back(crd);
//for the line
if (np < numPts-1)
{
seg++;
n = tmg[seg]*omniDrv->simuFreq.getValue();
cout << "N lin = " << n << endl;
stepNum.push_back(n);
Vec3d dx = (pts[np+1].getCenter() - pts[np].getCenter())/double(n);
type::Quat<double> dor; ///TODO difference for rotations!!!
NewOmniDriverEmu::Coord crd(dx, dor);
cout << "adding " << crd << endl;
stepDiff.push_back(crd);
}
seg++;
}
std::cout << " stepNum = " << stepNum << std::endl;
std::cout << " stepDiff = " << stepDiff << std::endl;
//trajectory done
std::cout << "TimeScale = " << timeScale << std::endl;
SolidTypes<double>::SpatialVector temp1, temp2;
long long unsigned asynchroStep=0;
double averageFreq = 0.0, minimalFreq=1e10;
unsigned int actSeg = 0;
unsigned int actStep = 0;
sofa::type::Quat<double> actualRot;
sofa::type::Vec3d actualPos = pts[0].getCenter();
cout << "numSegs = " << numSegs << endl;
cout << "numSegs = " << numSegs << endl;
while (true)
{
if (omniDrv->executeAsynchro)
{
startTime = double(omniDrv->thTimer->getTime());
//compute the actual position
if (actSeg < numSegs)
{
if (actStep < stepNum[actSeg])
{
actualPos += stepDiff[actSeg].getCenter();
//cout << "Adding [" << actStep << "] " << stepDiff[actSeg] << endl;
actStep++;
}
else
{
actStep=0;
actSeg++;
//cout << "Changing " << endl;
}
}
//else
// cout << "Finished" << endl;
omniDrv->data.servoDeviceData.pos = actualPos;
omniDrv->data.servoDeviceData.quat = actualRot;
SolidTypes<double>::Transform baseOmni_H_endOmni(actualPos * omniDrv->data.scale, actualRot);
SolidTypes<double>::Transform world_H_virtualTool = omniDrv->data.world_H_baseOmni * baseOmni_H_endOmni * omniDrv->data.endOmni_H_virtualTool;
omniDrv->data.forceFeedback->computeWrench(world_H_virtualTool,temp1,temp2);
realTimeAct = double(omniDrv->thTimer->getTime());
if (asynchroStep > 0)
{
double realFreq = 1.0/( (realTimeAct - realTimePrev)*timeScale );
averageFreq += realFreq;
//std::cout << "actual frequency = " << realFreq << std::endl;
if (realFreq < minimalFreq)
minimalFreq = realFreq;
if ( ((asynchroStep+1) % 1000) == 0)
{
std::cout << "Average frequency of the loop = " << averageFreq/double(asynchroStep) << " Hz " << std::endl;
std::cout << "Minimal frequency of the loop = " << minimalFreq << " Hz " << std::endl;
}
}
realTimePrev = realTimeAct;
asynchroStep++;
endTime = double(omniDrv->thTimer->getTime()); //[s]
totalTime = (endTime - startTime); // [us]
timeToSleep = int( (requiredTime - totalTime) - timeCorrection); // [us]
if (timeToSleep > 0)
{
std::this_thread::sleep_for(std::chrono::microseconds(timeToSleep));
}
else
{
std::cout << "Cannot achieve desired frequency, computation too slow: " << totalTime << std::endl;
}
}
else
{
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
}
void NewOmniDriverEmu::bwdInit()
{
sout<<"NewOmniDriverEmu::bwdInit() is called"<<sendl;
simulation::Node *context = dynamic_cast<simulation::Node *>(this->getContext()); // access to current node
ForceFeedback *ff = context->getTreeObject<ForceFeedback>();
data.forceFeedback = ff;
setDataValue();
if (!omniSimThreadCreated)
{
sout << "Not initializing phantom, starting emulating thread..." << sendl;
pthread_t hapSimuThread;
if (thTimer == NULL)
thTimer = new(CTime);
if ( pthread_create( &hapSimuThread, NULL, hapticSimuExecute, (void*)this) == 0 )
{
sout << "Thread created for Omni simulation" << sendl;
omniSimThreadCreated=true;
}
}
else
sout << "Emulating thread already running" << sendl;
}
void NewOmniDriverEmu::setDataValue()
{
data.scale = scale.getValue();
data.forceScale = forceScale.getValue();
Quat q = orientationBase.getValue();
q.normalize();
orientationBase.setValue(q);
data.world_H_baseOmni.set( positionBase.getValue(), q );
q=orientationTool.getValue();
q.normalize();
data.endOmni_H_virtualTool.set(positionTool.getValue(), q);
data.permanent_feedback = permanent.getValue();
}
void NewOmniDriverEmu::reset()
{
std::cout<<"NewOmniDriver::reset() is called" <<std::endl;
this->reinit();
}
void NewOmniDriverEmu::reinitVisual()
{
cout << "NewOmniDriver::reinitVisual() is called " << endl;
if(visu_base!=NULL)
{
cout << "visu_base = " << visu_base << endl;
delete(visu_base);
visu_base = new sofa::component::visualmodel::OglModel();
visu_base->fileMesh.setValue("mesh/omni_test2.obj");
visu_base->m_scale.setValue(type::Vector3(scale.getValue(),scale.getValue(),scale.getValue()));
visu_end->setColor(1.0f,1.0f,1.0f,1.0f);
visu_base->init();
visu_base->initVisual();
visu_base->updateVisual();
visu_base->applyRotation(orientationBase.getValue());
visu_base->applyTranslation( positionBase.getValue()[0],positionBase.getValue()[1], positionBase.getValue()[2]);
}
if (visu_end != NULL)
{
//serr<<"create visual model for NewOmniDriver end"<<sendl;
cout << "visu_end = " << visu_end << endl;
delete(visu_end);
visu_end = new sofa::component::visualmodel::OglModel();
visu_end->fileMesh.setValue("mesh/stylus.obj");
visu_end->m_scale.setValue(type::Vector3(scale.getValue(),scale.getValue(),scale.getValue()));
visu_end->setColor(1.0f,0.3f,0.0f,1.0f);
visu_end->init();
visu_end->initVisual();
visu_end->updateVisual();
}
}
void NewOmniDriverEmu::reinit()
{
std::cout<<"NewOmniDriver::reinit() is called" <<std::endl;
this->cleanup();
this->bwdInit();
this->reinitVisual();
std::cout<<"NewOmniDriver::reinit() done" <<std::endl;
//////////////// visu_base: place the visual model of the NewOmniDriver
//sofa::component::visualmodel::RigidMappedModel::VecCoord* x_rigid = visu_base->getRigidX();
// x_rigid->resize(1);
//(*x_rigid)[0].getOrientation() = q;
//(*x_rigid)[0].getCenter() = positionBase.getValue();
//double s =
//this->scale=Vector3(this->)
}
void NewOmniDriverEmu::draw()
{
//cout << "NewOmniDriver::draw is called" << endl;
if(omniVisu.getValue())
{
if (visu_base == NULL)
{
cout << "Creating visu_base" << endl;
// create visual object
//serr<<"create visual model for NewOmniDriver base"<<sendl;
visu_base = new sofa::component::visualmodel::OglModel();
visu_base->fileMesh.setValue("mesh/omni_test2.obj");
visu_base->m_scale.setValue(type::Vector3(scale.getValue(),scale.getValue(),scale.getValue()));
visu_base->init();
visu_base->initVisual();
visu_base->updateVisual();
visu_base->applyRotation(orientationBase.getValue());
visu_base->applyTranslation( positionBase.getValue()[0],positionBase.getValue()[1], positionBase.getValue()[2]);
//getContext()->addObject(visu_base);
}
if (visu_end == NULL)
{
//serr<<"create visual model for NewOmniDriver end"<<sendl;
visu_end = new sofa::component::visualmodel::OglModel();
visu_end->fileMesh.setValue("mesh/stylus.obj");
visu_end->m_scale.setValue(type::Vector3(scale.getValue(),scale.getValue(),scale.getValue()));
visu_end->setColor(1.0f,0.3f,0.0f,1.0f);
visu_end->init();
visu_end->initVisual();
visu_end->updateVisual();
}
// compute position of the endOmni in worldframe
SolidTypes<double>::Transform baseOmni_H_endOmni(data.deviceData.pos*data.scale, data.deviceData.quat);
SolidTypes<double>::Transform world_H_endOmni = data.world_H_baseOmni * baseOmni_H_endOmni ;
visu_end->xforms.resize(1);
(visu_end->xforms)[0].getOrientation() = world_H_endOmni.getOrientation();
(visu_end->xforms)[0].getCenter() = world_H_endOmni.getOrigin();
// draw the 2 visual models
visu_base->drawVisual();
visu_end->drawVisual();
}
}
void NewOmniDriverEmu::copyDeviceDataCallback(OmniData *pUserData)
{
OmniData *data = pUserData; // static_cast<OmniData*>(pUserData);
memcpy(&data->deviceData, &data->servoDeviceData, sizeof(DeviceData));
data->servoDeviceData.nupdates = 0;
data->servoDeviceData.ready = true;
}
void NewOmniDriverEmu::stopCallback(OmniData *pUserData)
{
OmniData *data = pUserData; // static_cast<OmniData*>(pUserData);
data->servoDeviceData.stop = true;
}
void NewOmniDriverEmu::onKeyPressedEvent(core::objectmodel::KeypressedEvent *kpe)
{
}
void NewOmniDriverEmu::onKeyReleasedEvent(core::objectmodel::KeyreleasedEvent *kre)
{
//omniVisu.setValue(false);
}
void NewOmniDriverEmu::handleEvent(core::objectmodel::Event *event)
{
//std::cout<<"NewEvent detected !!"<<std::endl;
if (dynamic_cast<sofa::simulation::AnimateBeginEvent *>(event))
{
//getData(); // copy data->servoDeviceData to gDeviceData
//if (!simulateTranslation.getValue()) {
copyDeviceDataCallback(&data);
if (data.deviceData.ready)
{
cout << "Data ready, event" << endl;
data.deviceData.quat.normalize();
//sout << "driver is working ! " << data->servoDeviceData.transform[12+0] << endl;
/// COMPUTATION OF THE vituralTool 6D POSITION IN THE World COORDINATES
SolidTypes<double>::Transform baseOmni_H_endOmni(data.deviceData.pos*data.scale, data.deviceData.quat);
SolidTypes<double>::Transform world_H_virtualTool = data.world_H_baseOmni * baseOmni_H_endOmni * data.endOmni_H_virtualTool;
// store actual position of interface for the forcefeedback (as it will be used as soon as new LCP will be computed)
data.forceFeedback->setReferencePosition(world_H_virtualTool);
/// TODO : SHOULD INCLUDE VELOCITY !!
sofa::core::objectmodel::HapticDeviceEvent omniEvent(data.deviceData.id, world_H_virtualTool.getOrigin(), world_H_virtualTool.getOrientation() , data.deviceData.m_buttonState);
this->getContext()->propagateEvent(sofa::core::ExecParams::defaultInstance(), &omniEvent);
if (moveOmniBase)
{
std::cout<<" new positionBase = "<<positionBase_buf<<std::endl;
visu_base->applyTranslation(positionBase_buf[0] - positionBase.getValue()[0],
positionBase_buf[1] - positionBase.getValue()[1],
positionBase_buf[2] - positionBase.getValue()[2]);
positionBase.setValue(positionBase_buf);
setDataValue();
//this->reinitVisual();
}
executeAsynchro=true;
}
else
std::cout<<"data not ready"<<std::endl;
//} else {
}
if (dynamic_cast<core::objectmodel::KeypressedEvent *>(event))
{
core::objectmodel::KeypressedEvent *kpe = dynamic_cast<core::objectmodel::KeypressedEvent *>(event);
if (kpe->getKey()=='Z' ||kpe->getKey()=='z' )
{
moveOmniBase = !moveOmniBase;
std::cout<<"key z detected "<<std::endl;
omniVisu.setValue(moveOmniBase);
if(moveOmniBase)
{
this->cleanup();
positionBase_buf = positionBase.getValue();
}
else
{
this->reinit();
}
}
if(kpe->getKey()=='K' || kpe->getKey()=='k')
{
positionBase_buf.x()=0.0;
positionBase_buf.y()=0.5;
positionBase_buf.z()=2.6;
}
if(kpe->getKey()=='L' || kpe->getKey()=='l')
{
positionBase_buf.x()=-0.15;
positionBase_buf.y()=1.5;
positionBase_buf.z()=2.6;
}
if(kpe->getKey()=='M' || kpe->getKey()=='m')
{
positionBase_buf.x()=0.0;
positionBase_buf.y()=2.5;
positionBase_buf.z()=2.6;
}
}
}
int NewOmniDriverEmuClass = core::RegisterObject("Solver to test compliance computation for new articulated system objects")
.add< NewOmniDriverEmu >();
} // namespace controller
} // namespace component
} // namespace sofa