triSurfaceMesh.C 18.5 KB
Newer Older
1
2
3
4
/*---------------------------------------------------------------------------*\
  =========                 |
  \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
   \\    /   O peration     |
laurence's avatar
laurence committed
5
    \\  /    A nd           | Copyright (C) 2011-2013 OpenFOAM Foundation
6
7
8
9
10
     \\/     M anipulation  |
-------------------------------------------------------------------------------
License
    This file is part of OpenFOAM.

11
12
13
14
    OpenFOAM is free software: you can redistribute it and/or modify it
    under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
15
16
17
18
19
20
21

    OpenFOAM 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 General Public License
    for more details.

    You should have received a copy of the GNU General Public License
22
    along with OpenFOAM.  If not, see <http://www.gnu.org/licenses/>.
23
24
25
26
27
28
29

\*---------------------------------------------------------------------------*/

#include "triSurfaceMesh.H"
#include "Random.H"
#include "addToRunTimeSelectionTable.H"
#include "EdgeMap.H"
mattijs's avatar
mattijs committed
30
31
#include "triSurfaceFields.H"
#include "Time.H"
32
#include "PatchTools.H"
33
34
35
36
37
38
39
40
41
42
43
44
45

// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //

namespace Foam
{

defineTypeNameAndDebug(triSurfaceMesh, 0);
addToRunTimeSelectionTable(searchableSurface, triSurfaceMesh, dict);

}

// * * * * * * * * * * * * * Private Member Functions  * * * * * * * * * * * //

mattijs's avatar
mattijs committed
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
//// Special version of Time::findInstance that does not check headerOk
//// to search for instances of raw files
//Foam::word Foam::triSurfaceMesh::findRawInstance
//(
//    const Time& runTime,
//    const fileName& dir,
//    const word& name
//)
//{
//    // Check current time first
//    if (isFile(runTime.path()/runTime.timeName()/dir/name))
//    {
//        return runTime.timeName();
//    }
//    instantList ts = runTime.times();
//    label instanceI;
//
//    for (instanceI = ts.size()-1; instanceI >= 0; --instanceI)
//    {
//        if (ts[instanceI].value() <= runTime.timeOutputValue())
//        {
//            break;
//        }
//    }
//
//    // continue searching from here
//    for (; instanceI >= 0; --instanceI)
//    {
//        if (isFile(runTime.path()/ts[instanceI].name()/dir/name))
//        {
//            return ts[instanceI].name();
//        }
//    }
//
//
//    // not in any of the time directories, try constant
//
//    // Note. This needs to be a hard-coded constant, rather than the
//    // constant function of the time, because the latter points to
//    // the case constant directory in parallel cases
//
//    if (isFile(runTime.path()/runTime.constant()/dir/name))
//    {
//        return runTime.constant();
//    }
//
//    FatalErrorIn
//    (
//        "searchableSurfaces::findRawInstance"
//        "(const Time&, const fileName&, const word&)"
//    )   << "Cannot find file \"" << name << "\" in directory "
//        << runTime.constant()/dir
//        << exit(FatalError);
//
//    return runTime.constant();
//}


104
105
106
107
108
109
110
//- Check file existence
const Foam::fileName& Foam::triSurfaceMesh::checkFile
(
    const fileName& fName,
    const fileName& objectName
)
{
Mark Olesen's avatar
Mark Olesen committed
111
    if (fName.empty())
112
113
114
115
116
117
118
119
120
121
122
    {
        FatalErrorIn
        (
            "triSurfaceMesh::checkFile(const fileName&, const fileName&)"
        )   << "Cannot find triSurfaceMesh starting from "
            << objectName << exit(FatalError);
    }
    return fName;
}


mattijs's avatar
mattijs committed
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
bool Foam::triSurfaceMesh::addFaceToEdge
(
    const edge& e,
    EdgeMap<label>& facesPerEdge
)
{
    EdgeMap<label>::iterator eFnd = facesPerEdge.find(e);
    if (eFnd != facesPerEdge.end())
    {
        if (eFnd() == 2)
        {
            return false;
        }
        eFnd()++;
    }
    else
    {
        facesPerEdge.insert(e, 1);
    }
    return true;
}


146
147
148
149
150
bool Foam::triSurfaceMesh::isSurfaceClosed() const
{
    // Construct pointFaces. Let's hope surface has compact point
    // numbering ...
    labelListList pointFaces;
laurence's avatar
laurence committed
151
    invertManyToMany(points()().size(), *this, pointFaces);
152
153
154
155
156
157
158
159
160
161
162
163
164

    // Loop over all faces surrounding point. Count edges emanating from point.
    // Every edge should be used by two faces exactly.
    // To prevent doing work twice per edge only look at edges to higher
    // point
    EdgeMap<label> facesPerEdge(100);
    forAll(pointFaces, pointI)
    {
        const labelList& pFaces = pointFaces[pointI];

        facesPerEdge.clear();
        forAll(pFaces, i)
        {
165
            const triSurface::FaceType& f = triSurface::operator[](pFaces[i]);
166
167
            label fp = findIndex(f, pointI);

mattijs's avatar
mattijs committed
168
169
170
171
172
            // Something weird: if I expand the code of addFaceToEdge in both
            // below instances it gives a segmentation violation on some
            // surfaces. Compiler (4.3.2) problem?


173
            // Forward edge
mattijs's avatar
mattijs committed
174
175
176
            label nextPointI = f[f.fcIndex(fp)];

            if (nextPointI > pointI)
177
            {
mattijs's avatar
mattijs committed
178
179
180
181
182
                bool okFace = addFaceToEdge
                (
                    edge(pointI, nextPointI),
                    facesPerEdge
                );
183

mattijs's avatar
mattijs committed
184
                if (!okFace)
185
                {
mattijs's avatar
mattijs committed
186
                    return false;
187
188
189
                }
            }
            // Reverse edge
mattijs's avatar
mattijs committed
190
191
192
            label prevPointI = f[f.rcIndex(fp)];

            if (prevPointI > pointI)
193
            {
mattijs's avatar
mattijs committed
194
195
196
197
198
                bool okFace = addFaceToEdge
                (
                    edge(pointI, prevPointI),
                    facesPerEdge
                );
199

mattijs's avatar
mattijs committed
200
                if (!okFace)
201
                {
mattijs's avatar
mattijs committed
202
                    return false;
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
                }
            }
        }

        // Check for any edges used only once.
        forAllConstIter(EdgeMap<label>, facesPerEdge, iter)
        {
            if (iter() != 2)
            {
                return false;
            }
        }
    }

    return true;
}


// * * * * * * * * * * * * * * * * Constructors  * * * * * * * * * * * * * * //

Foam::triSurfaceMesh::triSurfaceMesh(const IOobject& io, const triSurface& s)
:
    searchableSurface(io),
mattijs's avatar
mattijs committed
226
227
228
229
230
231
232
233
234
235
236
237
238
    objectRegistry
    (
        IOobject
        (
            io.name(),
            io.instance(),
            io.local(),
            io.db(),
            io.readOpt(),
            io.writeOpt(),
            false       // searchableSurface already registered under name
        )
    ),
239
    triSurface(s),
240
    triSurfaceRegionSearch(s),
241
    minQuality_(-1),
242
    surfaceClosed_(-1)
243
244
245
{
    bounds() = boundBox(points());
}
246
247
248
249


Foam::triSurfaceMesh::triSurfaceMesh(const IOobject& io)
:
mattijs's avatar
mattijs committed
250
    // Find instance for triSurfaceMesh
mattijs's avatar
mattijs committed
251
252
253
254
255
256
257
258
259
260
261
262
263
    searchableSurface(io),
    //(
    //    IOobject
    //    (
    //        io.name(),
    //        io.time().findInstance(io.local(), word::null),
    //        io.local(),
    //        io.db(),
    //        io.readOpt(),
    //        io.writeOpt(),
    //        io.registerObject()
    //    )
    //),
mattijs's avatar
mattijs committed
264
265
266
267
268
269
270
271
272
273
274
275
276
277
    // Reused found instance in objectRegistry
    objectRegistry
    (
        IOobject
        (
            io.name(),
            static_cast<const searchableSurface&>(*this).instance(),
            io.local(),
            io.db(),
            io.readOpt(),
            io.writeOpt(),
            false       // searchableSurface already registered under name
        )
    ),
278
279
280
281
282
283
284
285
    triSurface
    (
        checkFile
        (
            searchableSurface::filePath(),
            searchableSurface::objectPath()
        )
    ),
286
    triSurfaceRegionSearch(static_cast<const triSurface&>(*this)),
287
    minQuality_(-1),
288
    surfaceClosed_(-1)
289
290
291
{
    bounds() = boundBox(points());
}
292
293
294
295
296
297
298
299


Foam::triSurfaceMesh::triSurfaceMesh
(
    const IOobject& io,
    const dictionary& dict
)
:
mattijs's avatar
mattijs committed
300
301
302
303
304
305
306
307
308
309
310
311
312
    searchableSurface(io),
    //(
    //    IOobject
    //    (
    //        io.name(),
    //        io.time().findInstance(io.local(), word::null),
    //        io.local(),
    //        io.db(),
    //        io.readOpt(),
    //        io.writeOpt(),
    //        io.registerObject()
    //    )
    //),
mattijs's avatar
mattijs committed
313
314
315
316
317
318
319
320
321
322
323
324
325
326
    // Reused found instance in objectRegistry
    objectRegistry
    (
        IOobject
        (
            io.name(),
            static_cast<const searchableSurface&>(*this).instance(),
            io.local(),
            io.db(),
            io.readOpt(),
            io.writeOpt(),
            false       // searchableSurface already registered under name
        )
    ),
327
328
329
330
331
332
333
334
    triSurface
    (
        checkFile
        (
            searchableSurface::filePath(),
            searchableSurface::objectPath()
        )
    ),
335
    triSurfaceRegionSearch(static_cast<const triSurface&>(*this), dict),
336
    minQuality_(-1),
337
    surfaceClosed_(-1)
338
339
340
341
342
343
344
{
    scalar scaleFactor = 0;

    // allow rescaling of the surface points
    // eg, CAD geometries are often done in millimeters
    if (dict.readIfPresent("scale", scaleFactor) && scaleFactor > 0)
    {
mattijs's avatar
mattijs committed
345
346
        Info<< searchableSurface::name() << " : using scale " << scaleFactor
            << endl;
347
348
        triSurface::scalePoints(scaleFactor);
    }
349
350

    bounds() = boundBox(points());
mattijs's avatar
mattijs committed
351

352
353
354
355
356
357
358
    // Have optional minimum quality for normal calculation
    if (dict.readIfPresent("minQuality", minQuality_) && minQuality_ > 0)
    {
        Info<< searchableSurface::name()
            << " : ignoring triangles with quality < "
            << minQuality_ << " for normals calculation." << endl;
    }
359
}
360
361
362
363
364
365
366
367
368
369
370
371


// * * * * * * * * * * * * * * * * Destructor  * * * * * * * * * * * * * * * //

Foam::triSurfaceMesh::~triSurfaceMesh()
{
    clearOut();
}


void Foam::triSurfaceMesh::clearOut()
{
372
    triSurfaceRegionSearch::clearOut();
373
374
375
376
377
378
379
    edgeTree_.clear();
    triSurface::clearOut();
}


// * * * * * * * * * * * * * * * Member Functions  * * * * * * * * * * * * * //

laurence's avatar
laurence committed
380
Foam::tmp<Foam::pointField> Foam::triSurfaceMesh::coordinates() const
381
{
laurence's avatar
laurence committed
382
383
384
    tmp<pointField> tPts(new pointField(8));
    pointField& pt = tPts();

385
    // Use copy to calculate face centres so they don't get stored
laurence's avatar
laurence committed
386
    pt = PrimitivePatch<triSurface::FaceType, SubList, const pointField&>
387
    (
388
        SubList<triSurface::FaceType>(*this, triSurface::size()),
389
390
        triSurface::points()
    ).faceCentres();
laurence's avatar
laurence committed
391
392
393
394
395
396
397
398

    return tPts;
}


Foam::tmp<Foam::pointField> Foam::triSurfaceMesh::points() const
{
    return triSurface::points();
399
400
401
}


402
403
404
405
406
407
408
409
410
411
bool Foam::triSurfaceMesh::overlaps(const boundBox& bb) const
{
     const indexedOctree<treeDataTriSurface>& octree = tree();

     labelList indices = octree.findBox(treeBoundBox(bb));

     return !indices.empty();
}


412
413
void Foam::triSurfaceMesh::movePoints(const pointField& newPoints)
{
414
    triSurfaceRegionSearch::clearOut();
415
416
417
418
419
420
    edgeTree_.clear();
    triSurface::movePoints(newPoints);
}


const Foam::indexedOctree<Foam::treeDataEdge>&
421
Foam::triSurfaceMesh::edgeTree() const
422
{
423
    if (edgeTree_.empty())
424
425
426
427
428
429
430
431
432
433
434
435
    {
        // Boundary edges
        labelList bEdges
        (
            identity
            (
                nEdges()
               -nInternalEdges()
            )
          + nInternalEdges()
        );

436
437
438
439
440
441
442
443
444
445
446
        treeBoundBox bb(vector::zero, vector::zero);

        if (bEdges.size())
        {
            label nPoints;
            PatchTools::calcBounds
            (
                static_cast<const triSurface&>(*this),
                bb,
                nPoints
            );
447

448
449
            // Random number generator. Bit dodgy since not exactly random ;-)
            Random rndGen(65431);
450

451
452
            // Slightly extended bb. Slightly off-centred just so on symmetric
            // geometry there are less face/edge aligned items.
453

454
455
456
457
            bb = bb.extend(rndGen, 1e-4);
            bb.min() -= point(ROOTVSMALL, ROOTVSMALL, ROOTVSMALL);
            bb.max() += point(ROOTVSMALL, ROOTVSMALL, ROOTVSMALL);
        }
mattijs's avatar
mattijs committed
458

laurence's avatar
laurence committed
459
        scalar oldTol = indexedOctree<treeDataEdge>::perturbTol();
460
        indexedOctree<treeDataEdge>::perturbTol() = tolerance();
461

462
463
464
465
466
467
468
469
470
471
472
        edgeTree_.reset
        (
            new indexedOctree<treeDataEdge>
            (
                treeDataEdge
                (
                    false,          // cachebb
                    edges(),        // edges
                    localPoints(),  // points
                    bEdges          // selected edges
                ),
473
                bb,                 // bb
474
                maxTreeDepth(),      // maxLevel
475
476
                10,                 // leafsize
                3.0                 // duplicity
477
478
            )
        );
479
480

        indexedOctree<treeDataEdge>::perturbTol() = oldTol;
481
482
483
484
485
486
487
    }
    return edgeTree_();
}


const Foam::wordList& Foam::triSurfaceMesh::regions() const
{
488
    if (regions_.empty())
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
    {
        regions_.setSize(patches().size());
        forAll(regions_, regionI)
        {
            regions_[regionI] = patches()[regionI].name();
        }
    }
    return regions_;
}


// Find out if surface is closed.
bool Foam::triSurfaceMesh::hasVolumeType() const
{
    if (surfaceClosed_ == -1)
    {
        if (isSurfaceClosed())
        {
            surfaceClosed_ = 1;
        }
        else
        {
            surfaceClosed_ = 0;
        }
    }

    return surfaceClosed_ == 1;
}


void Foam::triSurfaceMesh::findNearest
(
    const pointField& samples,
    const scalarField& nearestDistSqr,
    List<pointIndexHit>& info
) const
{
526
    triSurfaceSearch::findNearest(samples, nearestDistSqr, info);
527
528
529
}


530
531
532
533
534
535
536
537
void Foam::triSurfaceMesh::findNearest
(
    const pointField& samples,
    const scalarField& nearestDistSqr,
    const labelList& regionIndices,
    List<pointIndexHit>& info
) const
{
538
539
540
541
542
543
544
    triSurfaceRegionSearch::findNearest
    (
        samples,
        nearestDistSqr,
        regionIndices,
        info
    );
545
546
547
}


548
549
550
551
552
553
554
void Foam::triSurfaceMesh::findLine
(
    const pointField& start,
    const pointField& end,
    List<pointIndexHit>& info
) const
{
555
    triSurfaceSearch::findLine(start, end, info);
556
557
558
559
560
561
562
563
564
565
}


void Foam::triSurfaceMesh::findLineAny
(
    const pointField& start,
    const pointField& end,
    List<pointIndexHit>& info
) const
{
566
    triSurfaceSearch::findLineAny(start, end, info);
567
568
569
570
571
572
573
574
575
576
}


void Foam::triSurfaceMesh::findLineAll
(
    const pointField& start,
    const pointField& end,
    List<List<pointIndexHit> >& info
) const
{
577
    triSurfaceSearch::findLineAll(start, end, info);
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
}


void Foam::triSurfaceMesh::getRegion
(
    const List<pointIndexHit>& info,
    labelList& region
) const
{
    region.setSize(info.size());
    forAll(info, i)
    {
        if (info[i].hit())
        {
            region[i] = triSurface::operator[](info[i].index()).region();
        }
        else
        {
            region[i] = -1;
        }
    }
}


void Foam::triSurfaceMesh::getNormal
(
    const List<pointIndexHit>& info,
    vectorField& normal
) const
{
608
609
    const triSurface& s = static_cast<const triSurface&>(*this);

610
611
    normal.setSize(info.size());

612
    if (minQuality_ >= 0)
613
    {
614
615
616
617
618
619
        // Make sure we don't use triangles with low quality since
        // normal is not reliable.

        const labelListList& faceFaces = s.faceFaces();

        forAll(info, i)
620
        {
621
622
623
            if (info[i].hit())
            {
                label faceI = info[i].index();
624
                normal[i] = s[faceI].normal(points());
625
626

                scalar qual = s[faceI].tri(points()).quality();
mattijs's avatar
mattijs committed
627

628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
                if (qual < minQuality_)
                {
                    // Search neighbouring triangles
                    const labelList& fFaces = faceFaces[faceI];

                    forAll(fFaces, j)
                    {
                        label nbrI = fFaces[j];
                        scalar nbrQual = s[nbrI].tri(points()).quality();
                        if (nbrQual > qual)
                        {
                            qual = nbrQual;
                            normal[i] = s[nbrI].normal(points());
                        }
                    }
                }
644
645

                normal[i] /= mag(normal[i]) + VSMALL;
646
647
648
649
650
651
            }
            else
            {
                // Set to what?
                normal[i] = vector::zero;
            }
652
        }
653
654
655
656
    }
    else
    {
        forAll(info, i)
657
        {
658
659
660
661
662
663
664
            if (info[i].hit())
            {
                label faceI = info[i].index();
                //- Cached:
                //normal[i] = faceNormals()[faceI];

                //- Uncached
665
                normal[i] = s[faceI].normal(points());
666
667
668
669
670
671
672
                normal[i] /= mag(normal[i]) + VSMALL;
            }
            else
            {
                // Set to what?
                normal[i] = vector::zero;
            }
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
void Foam::triSurfaceMesh::setField(const labelList& values)
{
    autoPtr<triSurfaceLabelField> fldPtr
    (
        new triSurfaceLabelField
        (
            IOobject
            (
                "values",
                objectRegistry::time().timeName(),  // instance
                "triSurface",                       // local
                *this,
                IOobject::NO_READ,
                IOobject::AUTO_WRITE
            ),
            *this,
            dimless,
            labelField(values)
        )
    );

    // Store field on triMesh
    fldPtr.ptr()->store();
}


mattijs's avatar
mattijs committed
704
705
706
707
708
709
void Foam::triSurfaceMesh::getField
(
    const List<pointIndexHit>& info,
    labelList& values
) const
{
710
    if (foundObject<triSurfaceLabelField>("values"))
mattijs's avatar
mattijs committed
711
    {
712
713
714
715
716
717
718
719
        values.setSize(info.size());

        const triSurfaceLabelField& fld = lookupObject<triSurfaceLabelField>
        (
            "values"
        );

        forAll(info, i)
mattijs's avatar
mattijs committed
720
        {
721
722
723
724
            if (info[i].hit())
            {
                values[i] = fld[info[i].index()];
            }
mattijs's avatar
mattijs committed
725
726
727
728
729
        }
    }
}


730
731
732
733
734
735
736
737
void Foam::triSurfaceMesh::getVolumeType
(
    const pointField& points,
    List<volumeType>& volType
) const
{
    volType.setSize(points.size());

mattijs's avatar
mattijs committed
738
    scalar oldTol = indexedOctree<treeDataTriSurface>::perturbTol();
739
    indexedOctree<treeDataTriSurface>::perturbTol() = tolerance();
mattijs's avatar
mattijs committed
740

741
742
743
744
745
746
    forAll(points, pointI)
    {
        const point& pt = points[pointI];

        // - use cached volume type per each tree node
        // - cheat conversion since same values
747
        volType[pointI] = tree().getVolumeType(pt);
748
    }
mattijs's avatar
mattijs committed
749
750

    indexedOctree<treeDataTriSurface>::perturbTol() = oldTol;
751
752
753
}


mattijs's avatar
mattijs committed
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
//- Write using given format, version and compression
bool Foam::triSurfaceMesh::writeObject
(
    IOstream::streamFormat fmt,
    IOstream::versionNumber ver,
    IOstream::compressionType cmp
) const
{
    fileName fullPath(searchableSurface::objectPath());

    if (!mkDir(fullPath.path()))
    {
        return false;
    }

    triSurface::write(fullPath);

771
    if (!isFile(fullPath))
mattijs's avatar
mattijs committed
772
773
774
775
776
777
778
779
780
    {
        return false;
    }

    //return objectRegistry::writeObject(fmt, ver, cmp);
    return true;
}


781
// ************************************************************************* //