FreeCAD

Форк
0
/
InspectionFeature.cpp 
991 строка · 31.0 Кб
1
/***************************************************************************
2
 *   Copyright (c) 2011 Werner Mayer <wmayer[at]users.sourceforge.net>     *
3
 *                                                                         *
4
 *   This file is part of the FreeCAD CAx development system.              *
5
 *                                                                         *
6
 *   This library is free software; you can redistribute it and/or         *
7
 *   modify it under the terms of the GNU Library General Public           *
8
 *   License as published by the Free Software Foundation; either          *
9
 *   version 2 of the License, or (at your option) any later version.      *
10
 *                                                                         *
11
 *   This library  is distributed in the hope that it will be useful,      *
12
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
13
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
14
 *   GNU Library General Public License for more details.                  *
15
 *                                                                         *
16
 *   You should have received a copy of the GNU Library General Public     *
17
 *   License along with this library; see the file COPYING.LIB. If not,    *
18
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
19
 *   Suite 330, Boston, MA  02111-1307, USA                                *
20
 *                                                                         *
21
 ***************************************************************************/
22

23
#include "PreCompiled.h"
24

25
#ifndef _PreComp_
26
#include <boost/core/ignore_unused.hpp>
27
#include <numeric>
28

29
#include <BRepBuilderAPI_MakeVertex.hxx>
30
#include <BRepClass3d_SolidClassifier.hxx>
31
#include <BRepExtrema_DistShapeShape.hxx>
32
#include <BRepGProp_Face.hxx>
33
#include <TopExp.hxx>
34
#include <TopoDS.hxx>
35
#include <gp_Pnt.hxx>
36

37
#include <QEventLoop>
38
#include <QFuture>
39
#include <QFutureWatcher>
40
#include <QtConcurrentMap>
41
#endif
42

43
#include <Base/Console.h>
44
#include <Base/FutureWatcherProgress.h>
45
#include <Base/Sequencer.h>
46
#include <Base/Stream.h>
47

48
#include <Mod/Mesh/App/Core/Algorithm.h>
49
#include <Mod/Mesh/App/Core/Grid.h>
50
#include <Mod/Mesh/App/Core/Iterator.h>
51
#include <Mod/Mesh/App/Core/MeshKernel.h>
52
#include <Mod/Mesh/App/MeshFeature.h>
53
#include <Mod/Part/App/PartFeature.h>
54
#include <Mod/Points/App/PointsFeature.h>
55
#include <Mod/Points/App/PointsGrid.h>
56

57
#include "InspectionFeature.h"
58

59

60
using namespace Inspection;
61
namespace sp = std::placeholders;
62

63
InspectActualMesh::InspectActualMesh(const Mesh::MeshObject& rMesh)
64
    : _mesh(rMesh.getKernel())
65
{
66
    Base::Matrix4D tmp;
67
    _clTrf = rMesh.getTransform();
68
    _bApply = _clTrf != tmp;
69
}
70

71
InspectActualMesh::~InspectActualMesh() = default;
72

73
unsigned long InspectActualMesh::countPoints() const
74
{
75
    return _mesh.CountPoints();
76
}
77

78
Base::Vector3f InspectActualMesh::getPoint(unsigned long index) const
79
{
80
    Base::Vector3f point = _mesh.GetPoint(index);
81
    if (_bApply) {
82
        _clTrf.multVec(point, point);
83
    }
84
    return point;
85
}
86

87
// ----------------------------------------------------------------
88

89
InspectActualPoints::InspectActualPoints(const Points::PointKernel& rPoints)
90
    : _rKernel(rPoints)
91
{}
92

93
unsigned long InspectActualPoints::countPoints() const
94
{
95
    return _rKernel.size();
96
}
97

98
Base::Vector3f InspectActualPoints::getPoint(unsigned long index) const
99
{
100
    Base::Vector3d pnt = _rKernel.getPoint(index);
101
    return Base::Vector3f(float(pnt.x), float(pnt.y), float(pnt.z));
102
}
103

104
// ----------------------------------------------------------------
105

106
InspectActualShape::InspectActualShape(const Part::TopoShape& shape)
107
    : _rShape(shape)
108
{
109
    Standard_Real deflection = _rShape.getAccuracy();
110
    fetchPoints(deflection);
111
}
112

113
void InspectActualShape::fetchPoints(double deflection)
114
{
115
    // get points from faces or sub-sampled edges
116
    TopTools_IndexedMapOfShape mapOfShapes;
117
    TopExp::MapShapes(_rShape.getShape(), TopAbs_FACE, mapOfShapes);
118
    if (!mapOfShapes.IsEmpty()) {
119
        std::vector<Data::ComplexGeoData::Facet> faces;
120
        _rShape.getFaces(points, faces, deflection);
121
    }
122
    else {
123
        TopExp::MapShapes(_rShape.getShape(), TopAbs_EDGE, mapOfShapes);
124
        if (!mapOfShapes.IsEmpty()) {
125
            std::vector<Data::ComplexGeoData::Line> lines;
126
            _rShape.getLines(points, lines, deflection);
127
        }
128
        else {
129
            std::vector<Base::Vector3d> normals;
130
            _rShape.getPoints(points, normals, deflection);
131
        }
132
    }
133
}
134

135
unsigned long InspectActualShape::countPoints() const
136
{
137
    return points.size();
138
}
139

140
Base::Vector3f InspectActualShape::getPoint(unsigned long index) const
141
{
142
    return Base::toVector<float>(points[index]);
143
}
144

145
// ----------------------------------------------------------------
146

147
namespace Inspection
148
{
149
class MeshInspectGrid: public MeshCore::MeshGrid
150
{
151
public:
152
    MeshInspectGrid(const MeshCore::MeshKernel& mesh, float fGridLen, const Base::Matrix4D& mat)
153
        : MeshCore::MeshGrid(mesh)
154
        , _transform(mat)
155
    {
156
        Base::BoundBox3f clBBMesh = _pclMesh->GetBoundBox().Transformed(mat);
157
        Rebuild(std::max<unsigned long>((unsigned long)(clBBMesh.LengthX() / fGridLen), 1),
158
                std::max<unsigned long>((unsigned long)(clBBMesh.LengthY() / fGridLen), 1),
159
                std::max<unsigned long>((unsigned long)(clBBMesh.LengthZ() / fGridLen), 1));
160
    }
161

162
    void Validate(const MeshCore::MeshKernel& kernel) override
163
    {
164
        // do nothing
165
        boost::ignore_unused(kernel);
166
    }
167

168
    void Validate()
169
    {
170
        // do nothing
171
    }
172

173
    bool Verify() const override
174
    {
175
        // do nothing
176
        return true;
177
    }
178

179
protected:
180
    void CalculateGridLength(int /*iCtGridPerAxis*/) override
181
    {
182
        // do nothing
183
    }
184

185
    unsigned long HasElements() const override
186
    {
187
        return _pclMesh->CountFacets();
188
    }
189

190
    void Pos(const Base::Vector3f& rclPoint,
191
             unsigned long& rulX,
192
             unsigned long& rulY,
193
             unsigned long& rulZ) const
194
    {
195
        rulX = (unsigned long)((rclPoint.x - _fMinX) / _fGridLenX);
196
        rulY = (unsigned long)((rclPoint.y - _fMinY) / _fGridLenY);
197
        rulZ = (unsigned long)((rclPoint.z - _fMinZ) / _fGridLenZ);
198

199
        assert((rulX < _ulCtGridsX) && (rulY < _ulCtGridsY) && (rulZ < _ulCtGridsZ));
200
    }
201

202
    void AddFacet(const MeshCore::MeshGeomFacet& rclFacet, unsigned long ulFacetIndex)
203
    {
204
        unsigned long ulX1;
205
        unsigned long ulY1;
206
        unsigned long ulZ1;
207
        unsigned long ulX2;
208
        unsigned long ulY2;
209
        unsigned long ulZ2;
210

211
        Base::BoundBox3f clBB;
212
        clBB.Add(rclFacet._aclPoints[0]);
213
        clBB.Add(rclFacet._aclPoints[1]);
214
        clBB.Add(rclFacet._aclPoints[2]);
215

216
        Pos(Base::Vector3f(clBB.MinX, clBB.MinY, clBB.MinZ), ulX1, ulY1, ulZ1);
217
        Pos(Base::Vector3f(clBB.MaxX, clBB.MaxY, clBB.MaxZ), ulX2, ulY2, ulZ2);
218

219

220
        if ((ulX1 < ulX2) || (ulY1 < ulY2) || (ulZ1 < ulZ2)) {
221
            for (unsigned long ulX = ulX1; ulX <= ulX2; ulX++) {
222
                for (unsigned long ulY = ulY1; ulY <= ulY2; ulY++) {
223
                    for (unsigned long ulZ = ulZ1; ulZ <= ulZ2; ulZ++) {
224
                        if (rclFacet.IntersectBoundingBox(GetBoundBox(ulX, ulY, ulZ))) {
225
                            _aulGrid[ulX][ulY][ulZ].insert(ulFacetIndex);
226
                        }
227
                    }
228
                }
229
            }
230
        }
231
        else {
232
            _aulGrid[ulX1][ulY1][ulZ1].insert(ulFacetIndex);
233
        }
234
    }
235

236
    void InitGrid() override
237
    {
238
        unsigned long i, j;
239

240
        Base::BoundBox3f clBBMesh = _pclMesh->GetBoundBox().Transformed(_transform);
241

242
        float fLengthX = clBBMesh.LengthX();
243
        float fLengthY = clBBMesh.LengthY();
244
        float fLengthZ = clBBMesh.LengthZ();
245

246
        _fGridLenX = (1.0f + fLengthX) / float(_ulCtGridsX);
247
        _fMinX = clBBMesh.MinX - 0.5f;
248

249
        _fGridLenY = (1.0f + fLengthY) / float(_ulCtGridsY);
250
        _fMinY = clBBMesh.MinY - 0.5f;
251

252
        _fGridLenZ = (1.0f + fLengthZ) / float(_ulCtGridsZ);
253
        _fMinZ = clBBMesh.MinZ - 0.5f;
254

255
        _aulGrid.clear();
256
        _aulGrid.resize(_ulCtGridsX);
257
        for (i = 0; i < _ulCtGridsX; i++) {
258
            _aulGrid[i].resize(_ulCtGridsY);
259
            for (j = 0; j < _ulCtGridsY; j++) {
260
                _aulGrid[i][j].resize(_ulCtGridsZ);
261
            }
262
        }
263
    }
264

265
    void RebuildGrid() override
266
    {
267
        _ulCtElements = _pclMesh->CountFacets();
268
        InitGrid();
269

270
        unsigned long i = 0;
271
        MeshCore::MeshFacetIterator clFIter(*_pclMesh);
272
        clFIter.Transform(_transform);
273
        for (clFIter.Init(); clFIter.More(); clFIter.Next()) {
274
            AddFacet(*clFIter, i++);
275
        }
276
    }
277

278
private:
279
    Base::Matrix4D _transform;
280
};
281
}  // namespace Inspection
282

283
InspectNominalMesh::InspectNominalMesh(const Mesh::MeshObject& rMesh, float offset)
284
    : _mesh(rMesh.getKernel())
285
{
286
    Base::Matrix4D tmp;
287
    _clTrf = rMesh.getTransform();
288
    _bApply = _clTrf != tmp;
289

290
    // Max. limit of grid elements
291
    float fMaxGridElements = 8000000.0f;
292
    Base::BoundBox3f box = _mesh.GetBoundBox().Transformed(rMesh.getTransform());
293

294
    // estimate the minimum allowed grid length
295
    float fMinGridLen =
296
        (float)pow((box.LengthX() * box.LengthY() * box.LengthZ() / fMaxGridElements), 0.3333f);
297
    float fGridLen = 5.0f * MeshCore::MeshAlgorithm(_mesh).GetAverageEdgeLength();
298

299
    // We want to avoid to get too small grid elements otherwise building up the grid structure
300
    // would take too much time and memory. Having quite a dense grid speeds up more the following
301
    // algorithms extremely. Due to the issue above it's always a compromise between speed and
302
    // memory usage.
303
    fGridLen = std::max<float>(fMinGridLen, fGridLen);
304

305
    // build up grid structure to speed up algorithms
306
    _pGrid = new MeshInspectGrid(_mesh, fGridLen, rMesh.getTransform());
307
    _box = box;
308
    _box.Enlarge(offset);
309
}
310

311
InspectNominalMesh::~InspectNominalMesh()
312
{
313
    delete this->_pGrid;
314
}
315

316
float InspectNominalMesh::getDistance(const Base::Vector3f& point) const
317
{
318
    if (!_box.IsInBox(point)) {
319
        return FLT_MAX;  // must be inside bbox
320
    }
321

322
    std::vector<unsigned long> indices;
323
    //_pGrid->GetElements(point, indices);
324
    if (indices.empty()) {
325
        std::set<unsigned long> inds;
326
        _pGrid->MeshGrid::SearchNearestFromPoint(point, inds);
327
        indices.insert(indices.begin(), inds.begin(), inds.end());
328
    }
329

330
    float fMinDist = FLT_MAX;
331
    bool positive = true;
332
    for (unsigned long it : indices) {
333
        MeshCore::MeshGeomFacet geomFace = _mesh.GetFacet(it);
334
        if (_bApply) {
335
            geomFace.Transform(_clTrf);
336
        }
337

338
        float fDist = geomFace.DistanceToPoint(point);
339
        if (fabs(fDist) < fabs(fMinDist)) {
340
            fMinDist = fDist;
341
            positive = point.DistanceToPlane(geomFace._aclPoints[0], geomFace.GetNormal()) > 0;
342
        }
343
    }
344

345
    if (!positive) {
346
        fMinDist = -fMinDist;
347
    }
348
    return fMinDist;
349
}
350

351
// ----------------------------------------------------------------
352

353
InspectNominalFastMesh::InspectNominalFastMesh(const Mesh::MeshObject& rMesh, float offset)
354
    : _mesh(rMesh.getKernel())
355
{
356
    const MeshCore::MeshKernel& kernel = rMesh.getKernel();
357

358
    Base::Matrix4D tmp;
359
    _clTrf = rMesh.getTransform();
360
    _bApply = _clTrf != tmp;
361

362
    // Max. limit of grid elements
363
    float fMaxGridElements = 8000000.0f;
364
    Base::BoundBox3f box = kernel.GetBoundBox().Transformed(rMesh.getTransform());
365

366
    // estimate the minimum allowed grid length
367
    float fMinGridLen =
368
        (float)pow((box.LengthX() * box.LengthY() * box.LengthZ() / fMaxGridElements), 0.3333f);
369
    float fGridLen = 5.0f * MeshCore::MeshAlgorithm(kernel).GetAverageEdgeLength();
370

371
    // We want to avoid to get too small grid elements otherwise building up the grid structure
372
    // would take too much time and memory. Having quite a dense grid speeds up more the following
373
    // algorithms extremely. Due to the issue above it's always a compromise between speed and
374
    // memory usage.
375
    fGridLen = std::max<float>(fMinGridLen, fGridLen);
376

377
    // build up grid structure to speed up algorithms
378
    _pGrid = new MeshInspectGrid(kernel, fGridLen, rMesh.getTransform());
379
    _box = box;
380
    _box.Enlarge(offset);
381
    max_level = (unsigned long)(offset / fGridLen);
382
}
383

384
InspectNominalFastMesh::~InspectNominalFastMesh()
385
{
386
    delete this->_pGrid;
387
}
388

389
/**
390
 * This algorithm is not that exact as that from InspectNominalMesh but is by
391
 * factors faster and sufficient for many cases.
392
 */
393
float InspectNominalFastMesh::getDistance(const Base::Vector3f& point) const
394
{
395
    if (!_box.IsInBox(point)) {
396
        return FLT_MAX;  // must be inside bbox
397
    }
398

399
    std::set<unsigned long> indices;
400
#if 0  // a point in a neighbour grid can be nearer
401
    std::vector<unsigned long> elements;
402
    _pGrid->GetElements(point, elements);
403
    indices.insert(elements.begin(), elements.end());
404
#else
405
    unsigned long ulX, ulY, ulZ;
406
    _pGrid->Position(point, ulX, ulY, ulZ);
407
    unsigned long ulLevel = 0;
408
    while (indices.empty() && ulLevel <= max_level) {
409
        _pGrid->GetHull(ulX, ulY, ulZ, ulLevel++, indices);
410
    }
411
    if (indices.empty() || ulLevel == 1) {
412
        _pGrid->GetHull(ulX, ulY, ulZ, ulLevel, indices);
413
    }
414
#endif
415

416
    float fMinDist = FLT_MAX;
417
    bool positive = true;
418
    for (unsigned long it : indices) {
419
        MeshCore::MeshGeomFacet geomFace = _mesh.GetFacet(it);
420
        if (_bApply) {
421
            geomFace.Transform(_clTrf);
422
        }
423

424
        float fDist = geomFace.DistanceToPoint(point);
425
        if (fabs(fDist) < fabs(fMinDist)) {
426
            fMinDist = fDist;
427
            positive = point.DistanceToPlane(geomFace._aclPoints[0], geomFace.GetNormal()) > 0;
428
        }
429
    }
430

431
    if (!positive) {
432
        fMinDist = -fMinDist;
433
    }
434
    return fMinDist;
435
}
436

437
// ----------------------------------------------------------------
438

439
InspectNominalPoints::InspectNominalPoints(const Points::PointKernel& Kernel, float /*offset*/)
440
    : _rKernel(Kernel)
441
{
442
    int uGridPerAxis = 50;  // totally 125.000 grid elements
443
    this->_pGrid = new Points::PointsGrid(Kernel, uGridPerAxis);
444
}
445

446
InspectNominalPoints::~InspectNominalPoints()
447
{
448
    delete this->_pGrid;
449
}
450

451
float InspectNominalPoints::getDistance(const Base::Vector3f& point) const
452
{
453
    // TODO: Make faster
454
    std::set<unsigned long> indices;
455
    unsigned long x, y, z;
456
    Base::Vector3d pointd(point.x, point.y, point.z);
457
    _pGrid->Position(pointd, x, y, z);
458
    _pGrid->GetElements(x, y, z, indices);
459

460
    double fMinDist = DBL_MAX;
461
    for (unsigned long it : indices) {
462
        Base::Vector3d pt = _rKernel.getPoint(it);
463
        double fDist = Base::Distance(pointd, pt);
464
        if (fDist < fMinDist) {
465
            fMinDist = fDist;
466
        }
467
    }
468

469
    return (float)fMinDist;
470
}
471

472
// ----------------------------------------------------------------
473

474
InspectNominalShape::InspectNominalShape(const TopoDS_Shape& shape, float /*radius*/)
475
    : _rShape(shape)
476
{
477
    distss = new BRepExtrema_DistShapeShape();
478
    distss->LoadS1(_rShape);
479

480
    // When having a solid then use its shell because otherwise the distance
481
    // for inner points will always be zero
482
    if (!_rShape.IsNull() && _rShape.ShapeType() == TopAbs_SOLID) {
483
        TopExp_Explorer xp;
484
        xp.Init(_rShape, TopAbs_SHELL);
485
        if (xp.More()) {
486
            distss->LoadS1(xp.Current());
487
            isSolid = true;
488
        }
489
    }
490
    // distss->SetDeflection(radius);
491
}
492

493
InspectNominalShape::~InspectNominalShape()
494
{
495
    delete distss;
496
}
497

498
float InspectNominalShape::getDistance(const Base::Vector3f& point) const
499
{
500
    gp_Pnt pnt3d(point.x, point.y, point.z);
501
    BRepBuilderAPI_MakeVertex mkVert(pnt3d);
502
    distss->LoadS2(mkVert.Vertex());
503

504
    float fMinDist = FLT_MAX;
505
    if (distss->Perform() && distss->NbSolution() > 0) {
506
        fMinDist = (float)distss->Value();
507
        // the shape is a solid, check if the vertex is inside
508
        if (isSolid) {
509
            if (isInsideSolid(pnt3d)) {
510
                fMinDist = -fMinDist;
511
            }
512
        }
513
        else if (fMinDist > 0) {
514
            // check if the distance was computed from a face
515
            if (isBelowFace(pnt3d)) {
516
                fMinDist = -fMinDist;
517
            }
518
        }
519
    }
520
    return fMinDist;
521
}
522

523
bool InspectNominalShape::isInsideSolid(const gp_Pnt& pnt3d) const
524
{
525
    const Standard_Real tol = 0.001;
526
    BRepClass3d_SolidClassifier classifier(_rShape);
527
    classifier.Perform(pnt3d, tol);
528
    return (classifier.State() == TopAbs_IN);
529
}
530

531
bool InspectNominalShape::isBelowFace(const gp_Pnt& pnt3d) const
532
{
533
    // check if the distance was computed from a face
534
    for (Standard_Integer index = 1; index <= distss->NbSolution(); index++) {
535
        if (distss->SupportTypeShape1(index) == BRepExtrema_IsInFace) {
536
            TopoDS_Shape face = distss->SupportOnShape1(index);
537
            Standard_Real u, v;
538
            distss->ParOnFaceS1(index, u, v);
539
            // gp_Pnt pnt = distss->PointOnShape1(index);
540
            BRepGProp_Face props(TopoDS::Face(face));
541
            gp_Vec normal;
542
            gp_Pnt center;
543
            props.Normal(u, v, center, normal);
544
            gp_Vec dir(center, pnt3d);
545
            Standard_Real scalar = normal.Dot(dir);
546
            if (scalar < 0) {
547
                return true;
548
            }
549
            break;
550
        }
551
    }
552

553
    return false;
554
}
555

556
// ----------------------------------------------------------------
557

558
TYPESYSTEM_SOURCE(Inspection::PropertyDistanceList, App::PropertyLists)
559

560
PropertyDistanceList::PropertyDistanceList() = default;
561

562
PropertyDistanceList::~PropertyDistanceList() = default;
563

564
void PropertyDistanceList::setSize(int newSize)
565
{
566
    _lValueList.resize(newSize);
567
}
568

569
int PropertyDistanceList::getSize() const
570
{
571
    return static_cast<int>(_lValueList.size());
572
}
573

574
void PropertyDistanceList::setValue(float lValue)
575
{
576
    aboutToSetValue();
577
    _lValueList.resize(1);
578
    _lValueList[0] = lValue;
579
    hasSetValue();
580
}
581

582
void PropertyDistanceList::setValues(const std::vector<float>& values)
583
{
584
    aboutToSetValue();
585
    _lValueList = values;
586
    hasSetValue();
587
}
588

589
PyObject* PropertyDistanceList::getPyObject()
590
{
591
    PyObject* list = PyList_New(getSize());
592
    for (int i = 0; i < getSize(); i++) {
593
        PyList_SetItem(list, i, PyFloat_FromDouble(_lValueList[i]));
594
    }
595
    return list;
596
}
597

598
void PropertyDistanceList::setPyObject(PyObject* value)
599
{
600
    if (PyList_Check(value)) {
601
        Py_ssize_t nSize = PyList_Size(value);
602
        std::vector<float> values;
603
        values.resize(nSize);
604

605
        for (Py_ssize_t i = 0; i < nSize; ++i) {
606
            PyObject* item = PyList_GetItem(value, i);
607
            if (!PyFloat_Check(item)) {
608
                std::string error = std::string("type in list must be float, not ");
609
                error += item->ob_type->tp_name;
610
                throw Py::TypeError(error);
611
            }
612

613
            values[i] = (float)PyFloat_AsDouble(item);
614
        }
615

616
        setValues(values);
617
    }
618
    else if (PyFloat_Check(value)) {
619
        setValue((float)PyFloat_AsDouble(value));
620
    }
621
    else {
622
        std::string error = std::string("type must be float or list of float, not ");
623
        error += value->ob_type->tp_name;
624
        throw Py::TypeError(error);
625
    }
626
}
627

628
void PropertyDistanceList::Save(Base::Writer& writer) const
629
{
630
    if (writer.isForceXML()) {
631
        writer.Stream() << writer.ind() << "<FloatList count=\"" << getSize() << "\">" << std::endl;
632
        writer.incInd();
633
        for (int i = 0; i < getSize(); i++) {
634
            writer.Stream() << writer.ind() << "<F v=\"" << _lValueList[i] << "\"/>" << std::endl;
635
        }
636
        writer.decInd();
637
        writer.Stream() << writer.ind() << "</FloatList>" << std::endl;
638
    }
639
    else {
640
        writer.Stream() << writer.ind() << "<FloatList file=\"" << writer.addFile(getName(), this)
641
                        << "\"/>" << std::endl;
642
    }
643
}
644

645
void PropertyDistanceList::Restore(Base::XMLReader& reader)
646
{
647
    reader.readElement("FloatList");
648
    std::string file(reader.getAttribute("file"));
649

650
    if (!file.empty()) {
651
        // initiate a file read
652
        reader.addFile(file.c_str(), this);
653
    }
654
}
655

656
void PropertyDistanceList::SaveDocFile(Base::Writer& writer) const
657
{
658
    Base::OutputStream str(writer.Stream());
659
    uint32_t uCt = (uint32_t)getSize();
660
    str << uCt;
661
    for (float it : _lValueList) {
662
        str << it;
663
    }
664
}
665

666
void PropertyDistanceList::RestoreDocFile(Base::Reader& reader)
667
{
668
    Base::InputStream str(reader);
669
    uint32_t uCt = 0;
670
    str >> uCt;
671
    std::vector<float> values(uCt);
672
    for (float& it : values) {
673
        str >> it;
674
    }
675
    setValues(values);
676
}
677

678
App::Property* PropertyDistanceList::Copy() const
679
{
680
    PropertyDistanceList* p = new PropertyDistanceList();
681
    p->_lValueList = _lValueList;
682
    return p;
683
}
684

685
void PropertyDistanceList::Paste(const App::Property& from)
686
{
687
    aboutToSetValue();
688
    _lValueList = dynamic_cast<const PropertyDistanceList&>(from)._lValueList;
689
    hasSetValue();
690
}
691

692
unsigned int PropertyDistanceList::getMemSize() const
693
{
694
    return static_cast<unsigned int>(_lValueList.size() * sizeof(float));
695
}
696

697
// ----------------------------------------------------------------
698

699
namespace Inspection
700
{
701
// helper class to use Qt's concurrent framework
702
struct DistanceInspection
703
{
704

705
    DistanceInspection(float radius,
706
                       InspectActualGeometry* a,
707
                       std::vector<InspectNominalGeometry*> n)
708
        : radius(radius)
709
        , actual(a)
710
        , nominal(n)
711
    {}
712
    float mapped(unsigned long index) const
713
    {
714
        Base::Vector3f pnt = actual->getPoint(index);
715

716
        float fMinDist = FLT_MAX;
717
        for (auto it : nominal) {
718
            float fDist = it->getDistance(pnt);
719
            if (fabs(fDist) < fabs(fMinDist)) {
720
                fMinDist = fDist;
721
            }
722
        }
723

724
        if (fMinDist > this->radius) {
725
            fMinDist = FLT_MAX;
726
        }
727
        else if (-fMinDist > this->radius) {
728
            fMinDist = -FLT_MAX;
729
        }
730

731
        return fMinDist;
732
    }
733

734
    float radius;
735
    InspectActualGeometry* actual;
736
    std::vector<InspectNominalGeometry*> nominal;
737
};
738

739
// Helper internal class for QtConcurrent map operation. Holds sums-of-squares and counts for RMS
740
// calculation
741
class DistanceInspectionRMS
742
{
743
public:
744
    DistanceInspectionRMS() = default;
745
    DistanceInspectionRMS& operator+=(const DistanceInspectionRMS& rhs)
746
    {
747
        this->m_numv += rhs.m_numv;
748
        this->m_sumsq += rhs.m_sumsq;
749
        return *this;
750
    }
751
    double getRMS()
752
    {
753
        if (this->m_numv == 0) {
754
            return 0.0;
755
        }
756
        return sqrt(this->m_sumsq / (double)this->m_numv);
757
    }
758
    int m_numv {0};
759
    double m_sumsq {0.0};
760
};
761
}  // namespace Inspection
762

763
PROPERTY_SOURCE(Inspection::Feature, App::DocumentObject)
764

765
Feature::Feature()
766
{
767
    ADD_PROPERTY(SearchRadius, (0.05));
768
    ADD_PROPERTY(Thickness, (0.0));
769
    ADD_PROPERTY(Actual, (nullptr));
770
    ADD_PROPERTY(Nominals, (nullptr));
771
    ADD_PROPERTY(Distances, (0.0));
772
}
773

774
Feature::~Feature() = default;
775

776
short Feature::mustExecute() const
777
{
778
    if (SearchRadius.isTouched()) {
779
        return 1;
780
    }
781
    if (Thickness.isTouched()) {
782
        return 1;
783
    }
784
    if (Actual.isTouched()) {
785
        return 1;
786
    }
787
    if (Nominals.isTouched()) {
788
        return 1;
789
    }
790
    return 0;
791
}
792

793
App::DocumentObjectExecReturn* Feature::execute()
794
{
795
    bool useMultithreading = true;
796

797
    App::DocumentObject* pcActual = Actual.getValue();
798
    if (!pcActual) {
799
        throw Base::ValueError("No actual geometry to inspect specified");
800
    }
801

802
    InspectActualGeometry* actual = nullptr;
803
    if (pcActual->isDerivedFrom<Mesh::Feature>()) {
804
        Mesh::Feature* mesh = static_cast<Mesh::Feature*>(pcActual);
805
        actual = new InspectActualMesh(mesh->Mesh.getValue());
806
    }
807
    else if (pcActual->isDerivedFrom<Points::Feature>()) {
808
        Points::Feature* pts = static_cast<Points::Feature*>(pcActual);
809
        actual = new InspectActualPoints(pts->Points.getValue());
810
    }
811
    else if (pcActual->isDerivedFrom<Part::Feature>()) {
812
        useMultithreading = false;
813
        Part::Feature* part = static_cast<Part::Feature*>(pcActual);
814
        actual = new InspectActualShape(part->Shape.getShape());
815
    }
816
    else {
817
        throw Base::TypeError("Unknown geometric type");
818
    }
819

820
    // clang-format off
821
    // get a list of nominals
822
    std::vector<InspectNominalGeometry*> inspectNominal;
823
    const std::vector<App::DocumentObject*>& nominals = Nominals.getValues();
824
    for (auto it : nominals) {
825
        InspectNominalGeometry* nominal = nullptr;
826
        if (it->isDerivedFrom<Mesh::Feature>()) {
827
            Mesh::Feature* mesh = static_cast<Mesh::Feature*>(it);
828
            nominal = new InspectNominalMesh(mesh->Mesh.getValue(), this->SearchRadius.getValue());
829
        }
830
        else if (it->isDerivedFrom<Points::Feature>()) {
831
            Points::Feature* pts = static_cast<Points::Feature*>(it);
832
            nominal = new InspectNominalPoints(pts->Points.getValue(), this->SearchRadius.getValue());
833
        }
834
        else if (it->isDerivedFrom<Part::Feature>()) {
835
            useMultithreading = false;
836
            Part::Feature* part = static_cast<Part::Feature*>(it);
837
            nominal = new InspectNominalShape(part->Shape.getValue(), this->SearchRadius.getValue());
838
        }
839

840
        if (nominal) {
841
            inspectNominal.push_back(nominal);
842
        }
843
    }
844
    // clang-format on
845

846
#if 0
847
#if 1  // test with some huge data sets
848
    std::vector<unsigned long> index(actual->countPoints());
849
    std::generate(index.begin(), index.end(), Base::iotaGen<unsigned long>(0));
850
    DistanceInspection check(this->SearchRadius.getValue(), actual, inspectNominal);
851
    QFuture<float> future = QtConcurrent::mapped
852
        (index, std::bind(&DistanceInspection::mapped, &check, sp::_1));
853
    //future.waitForFinished(); // blocks the GUI
854
    Base::FutureWatcherProgress progress("Inspecting...", actual->countPoints());
855
    QFutureWatcher<float> watcher;
856
    QObject::connect(&watcher, &QFutureWatcher<float>::progressValueChanged,
857
                     &progress, &Base::FutureWatcherProgress::progressValueChanged);
858

859
    // keep it responsive during computation
860
    QEventLoop loop;
861
    QObject::connect(&watcher, &QFutureWatcher::finished, &loop, &QEventLoop::quit);
862
    watcher.setFuture(future);
863
    loop.exec();
864

865
    std::vector<float> vals;
866
    vals.insert(vals.end(), future.begin(), future.end());
867
#else
868
    DistanceInspection insp(this->SearchRadius.getValue(), actual, inspectNominal);
869
    unsigned long count = actual->countPoints();
870
    std::stringstream str;
871
    str << "Inspecting " << this->Label.getValue() << "...";
872
    Base::SequencerLauncher seq(str.str().c_str(), count);
873

874
    std::vector<float> vals(count);
875
    for (unsigned long index = 0; index < count; index++) {
876
        float fMinDist = insp.mapped(index);
877
        vals[index] = fMinDist;
878
        seq.next();
879
    }
880
#endif
881

882
    Distances.setValues(vals);
883

884
    float fRMS = 0;
885
    int countRMS = 0;
886
    for (std::vector<float>::iterator it = vals.begin(); it != vals.end(); ++it) {
887
        if (fabs(*it) < FLT_MAX) {
888
            fRMS += (*it) * (*it);
889
            countRMS++;
890
        }
891
    }
892

893
    if (countRMS > 0) {
894
        fRMS = fRMS / countRMS;
895
        fRMS = sqrt(fRMS);
896
    }
897

898
    Base::Console().Message("RMS value for '%s' with search radius [%.4f,%.4f] is: %.4f\n",
899
        this->Label.getValue(), -this->SearchRadius.getValue(), this->SearchRadius.getValue(), fRMS);
900
#else
901
    unsigned long count = actual->countPoints();
902
    std::vector<float> vals(count);
903
    std::function<DistanceInspectionRMS(int)> fMap = [&](unsigned int index) {
904
        DistanceInspectionRMS res;
905
        Base::Vector3f pnt = actual->getPoint(index);
906

907
        float fMinDist = FLT_MAX;
908
        for (auto it : inspectNominal) {
909
            float fDist = it->getDistance(pnt);
910
            if (fabs(fDist) < fabs(fMinDist)) {
911
                fMinDist = fDist;
912
            }
913
        }
914

915
        if (fMinDist > this->SearchRadius.getValue()) {
916
            fMinDist = FLT_MAX;
917
        }
918
        else if (-fMinDist > this->SearchRadius.getValue()) {
919
            fMinDist = -FLT_MAX;
920
        }
921
        else {
922
            res.m_sumsq += fMinDist * fMinDist;
923
            res.m_numv++;
924
        }
925

926
        vals[index] = fMinDist;
927
        return res;
928
    };
929

930
    DistanceInspectionRMS res;
931

932
    if (useMultithreading) {
933
        // Build vector of increasing indices
934
        std::vector<unsigned long> index(count);
935
        std::iota(index.begin(), index.end(), 0);
936
        // Perform map-reduce operation : compute distances and update sum of squares for RMS
937
        // computation
938
        QFuture<DistanceInspectionRMS> future =
939
            QtConcurrent::mappedReduced(index, fMap, &DistanceInspectionRMS::operator+=);
940
        // Setup progress bar
941
        Base::FutureWatcherProgress progress("Inspecting...", actual->countPoints());
942
        QFutureWatcher<DistanceInspectionRMS> watcher;
943
        QObject::connect(&watcher,
944
                         &QFutureWatcher<DistanceInspectionRMS>::progressValueChanged,
945
                         &progress,
946
                         &Base::FutureWatcherProgress::progressValueChanged);
947
        // Keep UI responsive during computation
948
        QEventLoop loop;
949
        QObject::connect(&watcher,
950
                         &QFutureWatcher<DistanceInspectionRMS>::finished,
951
                         &loop,
952
                         &QEventLoop::quit);
953
        watcher.setFuture(future);
954
        loop.exec();
955
        res = future.result();
956
    }
957
    else {
958
        // Single-threaded operation
959
        std::stringstream str;
960
        str << "Inspecting " << this->Label.getValue() << "...";
961
        Base::SequencerLauncher seq(str.str().c_str(), count);
962

963
        for (unsigned int i = 0; i < count; i++) {
964
            res += fMap(i);
965
        }
966
    }
967

968
    Base::Console().Message("RMS value for '%s' with search radius [%.4f,%.4f] is: %.4f\n",
969
                            this->Label.getValue(),
970
                            -this->SearchRadius.getValue(),
971
                            this->SearchRadius.getValue(),
972
                            res.getRMS());
973
    Distances.setValues(vals);
974
#endif
975

976
    delete actual;
977
    for (auto it : inspectNominal) {
978
        delete it;
979
    }
980

981
    return nullptr;
982
}
983

984
// ----------------------------------------------------------------
985

986
PROPERTY_SOURCE(Inspection::Group, App::DocumentObjectGroup)
987

988

989
Group::Group() = default;
990

991
Group::~Group() = default;
992

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.