-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathInsertionAlgorithm.h
More file actions
364 lines (319 loc) · 18.4 KB
/
InsertionAlgorithm.h
File metadata and controls
364 lines (319 loc) · 18.4 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
#pragma once
#include <CollisionAlgorithm/BaseAlgorithm.h>
#include <CollisionAlgorithm/BaseGeometry.h>
#include <CollisionAlgorithm/BaseOperation.h>
#include <CollisionAlgorithm/operations/ContainsPoint.h>
#include <CollisionAlgorithm/operations/CreateCenterProximity.h>
#include <CollisionAlgorithm/operations/FindClosestProximity.h>
#include <CollisionAlgorithm/operations/NeedleOperations.h>
#include <CollisionAlgorithm/operations/Project.h>
#include <CollisionAlgorithm/proximity/EdgeProximity.h>
#include <sofa/component/constraint/lagrangian/solver/ConstraintSolverImpl.h>
#include <sofa/component/statecontainer/MechanicalObject.h>
namespace sofa::collisionalgorithm
{
class SOFA_COLLISIONALGORITHM_API InsertionAlgorithm : public BaseAlgorithm
{
public:
SOFA_CLASS(InsertionAlgorithm, BaseAlgorithm);
typedef core::behavior::MechanicalState<defaulttype::Vec3Types> MechStateTipType;
typedef core::objectmodel::SingleLink<InsertionAlgorithm, BaseGeometry,
BaseLink::FLAG_STOREPATH | BaseLink::FLAG_STRONGLINK>
GeomLink;
typedef DetectionOutput<BaseProximity, BaseProximity> AlgorithmOutput;
typedef component::constraint::lagrangian::solver::ConstraintSolverImpl ConstraintSolver;
GeomLink l_tipGeom, l_surfGeom, l_shaftGeom, l_volGeom;
Data<AlgorithmOutput> d_collisionOutput, d_insertionOutput;
Data<bool> d_projective, d_enablePuncture, d_enableInsertion, d_enableShaftCollision;
Data<SReal> d_punctureForceThreshold, d_tipDistThreshold;
ConstraintSolver::SPtr m_constraintSolver;
std::vector<BaseProximity::SPtr> m_couplingPts;
Data<bool> d_drawCollision, d_drawPoints;
Data<SReal> d_drawPointsScale;
InsertionAlgorithm()
: l_tipGeom(initLink("tipGeom", "Link to the geometry structure of the needle tip.")),
l_surfGeom(
initLink("surfGeom", "Link to the geometry of the surface punctured by the needle.")),
l_shaftGeom(initLink("shaftGeom", "Link to the geometry structure of the needle shaft.")),
l_volGeom(initLink("volGeom",
"Link to the geometry of volume wherein the needle is inserted.")),
d_collisionOutput(initData(&d_collisionOutput, "collisionOutput",
"Detected proximities during puncture.")),
d_insertionOutput(initData(&d_insertionOutput, "insertionOutput",
"Detected proximities during insertion.")),
d_projective(initData(
&d_projective, false, "projective",
"Projection of closest detected proximity back onto the needle tip element.")),
d_enablePuncture(
initData(&d_enablePuncture, true, "enablePuncture", "Enable puncture algorithm.")),
d_enableInsertion(
initData(&d_enableInsertion, true, "enableInsertion", "Enable insertion algorithm.")),
d_enableShaftCollision(initData(&d_enableShaftCollision, true, "enableShaftCollision",
"Enable shaft-surface collision.")),
d_punctureForceThreshold(initData(&d_punctureForceThreshold, -1_sreal,
"punctureForceThreshold",
"Threshold for the force applied to the needle tip. "
"Once exceeded, puncture is initiated.")),
d_tipDistThreshold(initData(&d_tipDistThreshold, -1_sreal, "tipDistThreshold",
"Threshold for the distance advanced by the needle tip since "
"the last proximity detection. Once exceeded, a new "
"proximity pair is added for the needle-volume coupling.")),
m_constraintSolver(nullptr),
m_couplingPts(),
d_drawCollision(initData(&d_drawCollision, false, "drawcollision", "Draw collision.")),
d_drawPoints(initData(&d_drawPoints, false, "drawPoints", "Draw detection outputs.")),
d_drawPointsScale(initData(&d_drawPointsScale, 0.0005, "drawPointsScale",
"Scale the drawing of detection output points."))
{
}
void init() override
{
BaseAlgorithm::init();
if (d_enablePuncture.getValue())
{
this->getContext()->get<ConstraintSolver>(m_constraintSolver);
msg_warning_when(!m_constraintSolver)
<< "No constraint solver found in context. Insertion algorithm is disabled.";
if (d_punctureForceThreshold.getValue() < 0)
{
msg_warning() << d_punctureForceThreshold.getName() +
" parameter not defined or set to negative value." msgendl
<< "Puncture will not function properly; provide a positive value";
d_punctureForceThreshold.setValue(std::numeric_limits<double>::max());
}
}
if (d_enableInsertion.getValue())
{
if (d_tipDistThreshold.getValue() < 0)
{
msg_warning() << d_tipDistThreshold.getName() +
" parameter not defined or set to negative value." msgendl
<< "Needle-volume coupling is disabled; provide a positive value";
d_tipDistThreshold.setValue(std::numeric_limits<double>::max());
}
}
}
void draw(const core::visual::VisualParams* vparams)
{
if (!vparams->displayFlags().getShowCollisionModels() && !d_drawCollision.getValue())
return;
vparams->drawTool()->disableLighting();
const AlgorithmOutput& collisionOutput = d_collisionOutput.getValue();
for (const auto& it : collisionOutput)
{
vparams->drawTool()->drawLine(it.first->getPosition(), it.second->getPosition(),
type::RGBAColor(0, 1, 0, 1));
}
const AlgorithmOutput& insertionOutput = d_insertionOutput.getValue();
for (const auto& it : insertionOutput)
{
vparams->drawTool()->drawSphere(it.first->getPosition(), d_drawPointsScale.getValue(),
type::RGBAColor(1, 0, 1, 0.9));
vparams->drawTool()->drawSphere(it.second->getPosition(), d_drawPointsScale.getValue(),
type::RGBAColor(0, 0, 1, 0.9));
vparams->drawTool()->drawLine(it.first->getPosition(), it.second->getPosition(),
type::RGBAColor(1, 1, 0, 1));
}
}
void doDetection()
{
auto& collisionOutput = *d_collisionOutput.beginEdit();
auto& insertionOutput = *d_insertionOutput.beginEdit();
insertionOutput.clear();
collisionOutput.clear();
if (m_couplingPts.empty() && l_surfGeom)
{
// Operations on surface geometry
sofa::helper::AdvancedTimer::stepBegin("Puncture detection - "+this->getName());
auto findClosestProxOnSurf =
Operations::FindClosestProximity::Operation::get(l_surfGeom);
auto projectOnSurf = Operations::Project::Operation::get(l_surfGeom);
// Puncture sequence
if (d_enablePuncture.getValue() && l_tipGeom)
{
auto createTipProximity =
Operations::CreateCenterProximity::Operation::get(l_tipGeom->getTypeInfo());
auto projectOnTip = Operations::Project::Operation::get(l_tipGeom);
const SReal punctureForceThreshold = d_punctureForceThreshold.getValue();
for (auto itTip = l_tipGeom->begin(); itTip != l_tipGeom->end(); itTip++)
{
BaseProximity::SPtr tipProx = createTipProximity(itTip->element());
if (!tipProx) continue;
const BaseProximity::SPtr surfProx = findClosestProxOnSurf(
tipProx, l_surfGeom.get(), projectOnSurf, getFilterFunc());
if (surfProx)
{
surfProx->normalize();
// Check whether puncture is happening - if so, create coupling point ...
if (m_constraintSolver)
{
const MechStateTipType::SPtr mstate =
l_tipGeom->getContext()->get<MechStateTipType>();
const auto& lambda =
m_constraintSolver->getLambda()[mstate.get()].read()->getValue();
SReal norm{0_sreal};
for (const auto& l : lambda)
{
norm += l.norm();
}
if (norm > punctureForceThreshold)
{
m_couplingPts.push_back(surfProx);
continue;
}
}
// ... if not, create a proximity pair for the tip-surface collision
collisionOutput.add(tipProx, surfProx);
}
}
}
sofa::helper::AdvancedTimer::stepEnd("Puncture detection - "+this->getName());
// Shaft collision sequence - Disable if coupling points have been added
sofa::helper::AdvancedTimer::stepBegin("Shaft collision - "+this->getName());
if (d_enableShaftCollision.getValue() && m_couplingPts.empty() && l_shaftGeom)
{
auto createShaftProximity =
Operations::CreateCenterProximity::Operation::get(l_shaftGeom->getTypeInfo());
auto projectOnShaft = Operations::Project::Operation::get(l_shaftGeom);
for (auto itShaft = l_shaftGeom->begin(); itShaft != l_shaftGeom->end(); itShaft++)
{
BaseProximity::SPtr shaftProx = createShaftProximity(itShaft->element());
if (!shaftProx) continue;
const BaseProximity::SPtr surfProx = findClosestProxOnSurf(
shaftProx, l_surfGeom.get(), projectOnSurf, getFilterFunc());
if (surfProx)
{
surfProx->normalize();
if (d_projective.getValue())
{
//shaftProx =
// projectOnShaft(surfProx->getPosition(), itShaft->element()).prox;
//if (!shaftProx) continue;
//shaftProx->normalize();
// Experimental - This enables projection anywhere on the edge
auto findClosestProxOnShaft =
Operations::FindClosestProximity::Operation::get(l_shaftGeom);
shaftProx = findClosestProxOnShaft(surfProx, l_shaftGeom,
projectOnShaft, getFilterFunc());
if (!shaftProx) continue;
shaftProx->normalize();
}
collisionOutput.add(shaftProx, surfProx);
}
}
}
sofa::helper::AdvancedTimer::stepEnd("Shaft collision - "+this->getName());
}
else
{
// Insertion sequence
sofa::helper::AdvancedTimer::stepBegin("Needle insertion - " + this->getName());
if (!d_enableInsertion.getValue() || !l_tipGeom || !l_volGeom || !l_shaftGeom) return;
ElementIterator::SPtr itTip = l_tipGeom->begin();
auto createTipProximity =
Operations::CreateCenterProximity::Operation::get(itTip->getTypeInfo());
const BaseProximity::SPtr tipProx = createTipProximity(itTip->element());
if (!tipProx) return;
// Remove coupling points that are ahead of the tip in the insertion direction
ElementIterator::SPtr itShaft = l_shaftGeom->begin(l_shaftGeom->getSize() - 2);
auto prunePointsAheadOfTip =
Operations::Needle::PrunePointsAheadOfTip::get(itShaft->getTypeInfo());
prunePointsAheadOfTip(m_couplingPts, itShaft->element());
if (m_couplingPts.empty()) return;
type::Vec3 lastCP = m_couplingPts.back()->getPosition();
const SReal tipDistThreshold = this->d_tipDistThreshold.getValue();
// Vector from tip to last coupling point; used for distance and directional checks
const type::Vec3 tipToLastCP = lastCP - tipProx->getPosition();
// Only add a new coupling point if the needle tip has advanced far enough
if (tipToLastCP.norm() > tipDistThreshold)
{
// Prepare the operations before entering the loop
auto createShaftProximity =
Operations::CreateCenterProximity::Operation::get(l_shaftGeom->getTypeInfo());
auto projectOnShaft = Operations::Project::Operation::get(l_shaftGeom);
auto findClosestProxOnVol =
Operations::FindClosestProximity::Operation::get(l_volGeom);
auto projectOnVol = Operations::Project::Operation::get(l_volGeom);
auto containsPointInVol =
Operations::ContainsPointInProximity::Operation::get(l_volGeom);
// Iterate over shaft segments to find which one contains the next candidate CP
for (auto itShaft = l_shaftGeom->begin(); itShaft != l_shaftGeom->end(); itShaft++)
{
BaseProximity::SPtr shaftProx = createShaftProximity(itShaft->element());
if (!shaftProx) continue;
const EdgeProximity::SPtr edgeProx =
dynamic_pointer_cast<EdgeProximity>(shaftProx);
if (!edgeProx) continue;
const type::Vec3 p0 = edgeProx->element()->getP0()->getPosition();
const type::Vec3 p1 = edgeProx->element()->getP1()->getPosition();
const type::Vec3 shaftEdgeDir = (p1 - p0).normalized();
const type::Vec3 lastCPToP1 = p1 - lastCP;
// Skip if last CP lies after edge end point
if (dot(shaftEdgeDir, lastCPToP1) < 0_sreal) continue;
const int numCPs = floor(lastCPToP1.norm() / tipDistThreshold);
for (int idCP = 0; idCP < numCPs; idCP++)
{
// Candidate coupling point along shaft segment
const type::Vec3 candidateCP = lastCP + tipDistThreshold * shaftEdgeDir;
// Project candidate CP onto the edge element and compute scalar coordinate
// along segment
const SReal edgeSegmentLength = (p1 - p0).norm();
const type::Vec3 p0ToCandidateCP = candidateCP - p0;
const SReal projPtOnEdge = dot(p0ToCandidateCP, shaftEdgeDir);
// Skip if candidate CP is outside current edge segment
if (projPtOnEdge < 0_sreal || projPtOnEdge > edgeSegmentLength) break;
// Project candidate CP onto shaft geometry ...
shaftProx = projectOnShaft(candidateCP, itShaft->element()).prox;
if (!shaftProx) continue;
// ... then find nearest volume proximity
const BaseProximity::SPtr volProx = findClosestProxOnVol(
shaftProx, l_volGeom.get(), projectOnVol, getFilterFunc());
if (!volProx) continue;
// Proximity can be detected before the tip enters the tetra (e.g. near a
// boundary face) Only accept proximities if the tip is inside the tetra
// during insertion
if (containsPointInVol(shaftProx->getPosition(), volProx))
{
volProx->normalize();
m_couplingPts.push_back(volProx);
lastCP = volProx->getPosition();
}
}
}
}
else // Don't bother with removing the point that was just added
{
// Remove coupling points that are ahead of the tip in the insertion direction
ElementIterator::SPtr itShaft = l_shaftGeom->begin(l_shaftGeom->getSize() - 2);
auto prunePointsAheadOfTip =
Operations::Needle::PrunePointsAheadOfTip::get(itShaft->getTypeInfo());
prunePointsAheadOfTip(m_couplingPts, itShaft->element());
}
sofa::helper::AdvancedTimer::stepEnd("Needle insertion - " + this->getName());
}
sofa::helper::AdvancedTimer::stepBegin("Reproject coupling points - "+this->getName());
if (d_enableInsertion.getValue() && !m_couplingPts.empty() && l_shaftGeom)
{
// Reprojection on shaft geometry sequence
auto findClosestProxOnShaft =
Operations::FindClosestProximity::Operation::get(l_shaftGeom);
auto projectOnShaft = Operations::Project::Operation::get(l_shaftGeom);
for (int i = 0; i < m_couplingPts.size(); i++)
{
const BaseProximity::SPtr shaftProx = findClosestProxOnShaft(
m_couplingPts[i], l_shaftGeom.get(), projectOnShaft, getFilterFunc());
if (!shaftProx) continue;
shaftProx->normalize();
insertionOutput.add(shaftProx, m_couplingPts[i]);
}
// This is a final-frontier check: If there are coupling points stored, but the
// findClosestProxOnShaf operation yields no proximities on the shaft, it could be
// because the needle has exited abruptly. Thus, we clear the coupling points.
if (insertionOutput.size() == 0) m_couplingPts.clear();
}
sofa::helper::AdvancedTimer::stepEnd("Reproject coupling points - "+this->getName());
d_collisionOutput.endEdit();
d_insertionOutput.endEdit();
}
};
} // namespace sofa::collisionalgorithm