meshRefinementGapRefine.C 51 KB
Newer Older
1
2
3
4
/*---------------------------------------------------------------------------*\
  =========                 |
  \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
   \\    /   O peration     |
OpenFOAM bot's avatar
OpenFOAM bot committed
5
    \\  /    A nd           | www.openfoam.com
OpenFOAM bot's avatar
OpenFOAM bot committed
6
7
     \\/     M anipulation  |
-------------------------------------------------------------------------------
OpenFOAM bot's avatar
OpenFOAM bot committed
8
9
    Copyright (C) 2015 OpenFOAM Foundation
    Copyright (C) 2015-2016 OpenCFD Ltd.
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
-------------------------------------------------------------------------------
License
    This file is part of OpenFOAM.

    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.

    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
    along with OpenFOAM.  If not, see <http://www.gnu.org/licenses/>.

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

#include "meshRefinement.H"
#include "Time.H"
#include "refinementSurfaces.H"
#include "refinementFeatures.H"
#include "shellSurfaces.H"
#include "triSurfaceMesh.H"
#include "treeDataCell.H"
#include "searchableSurfaces.H"
#include "DynamicField.H"
38
39
40
41
#include "transportData.H"
#include "FaceCellWave.H"
#include "volFields.H"
#include "zeroGradientFvPatchFields.H"
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

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

Foam::label Foam::meshRefinement::markSurfaceGapRefinement
(
    const scalar planarCos,

    const label nAllowRefine,
    const labelList& neiLevel,
    const pointField& neiCc,

    labelList& refineCell,
    label& nRefine
) const
{
    const labelList& cellLevel = meshCutter_.cellLevel();
    const pointField& cellCentres = mesh_.cellCentres();

    // Get the gap level for the shells
    const labelList maxLevel(shells_.maxGapLevel());

    label oldNRefine = nRefine;

    if (max(maxLevel) > 0)
    {
        // Use cached surfaceIndex_ to detect if any intersection. If so
        // re-intersect to determine level wanted.

        // Collect candidate faces
        // ~~~~~~~~~~~~~~~~~~~~~~~

        labelList testFaces(getRefineCandidateFaces(refineCell));

        // Collect segments
        // ~~~~~~~~~~~~~~~~

        pointField start(testFaces.size());
        pointField end(testFaces.size());
80
81
82
83
84
85
86
87
88
89
90
91
        {
            labelList minLevel(testFaces.size());
            calcCellCellRays
            (
                neiCc,
                neiLevel,
                testFaces,
                start,
                end,
                minLevel
            );
        }
92
93
94
95


        // Collect cells to test for inside/outside in shell
        labelList cellToCompact(mesh_.nCells(), -1);
96
        labelList bFaceToCompact(mesh_.nBoundaryFaces(), -1);
97
        List<FixedList<label, 3>> shellGapInfo;
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
        List<volumeType> shellGapMode;
        {
            DynamicField<point> compactToCc(mesh_.nCells()/10);
            DynamicList<label> compactToLevel(compactToCc.capacity());
            forAll(testFaces, i)
            {
                label faceI = testFaces[i];
                label own = mesh_.faceOwner()[faceI];
                if (cellToCompact[own] == -1)
                {
                    cellToCompact[own] = compactToCc.size();
                    compactToCc.append(cellCentres[own]);
                    compactToLevel.append(cellLevel[own]);
                }
                if (mesh_.isInternalFace(faceI))
                {
                    label nei = mesh_.faceNeighbour()[faceI];
                    if (cellToCompact[nei] == -1)
                    {
                        cellToCompact[nei] = compactToCc.size();
                        compactToCc.append(cellCentres[nei]);
                        compactToLevel.append(cellLevel[nei]);
                    }
                }
                else
                {
                    label bFaceI = faceI - mesh_.nInternalFaces();
                    if (bFaceToCompact[bFaceI] == -1)
                    {
                        bFaceToCompact[bFaceI] = compactToCc.size();
                        compactToCc.append(neiCc[bFaceI]);
                        compactToLevel.append(neiLevel[bFaceI]);
                    }
                }
            }

            shells_.findHigherGapLevel
            (
                compactToCc,
                compactToLevel,
                shellGapInfo,
                shellGapMode
            );
        }


144
        const List<FixedList<label, 3>>& extendedGapLevel =
145
146
147
148
            surfaces_.extendedGapLevel();
        const List<volumeType>& extendedGapMode =
            surfaces_.extendedGapMode();

149
150
151
152
        labelList ccSurface1;
        List<pointIndexHit> ccHit1;
        labelList ccRegion1;
        vectorField ccNormal1;
153
154

        {
155
156
157
158
            labelList ccSurface2;
            List<pointIndexHit> ccHit2;
            labelList ccRegion2;
            vectorField ccNormal2;
159
160
161
162
163
164
165

            surfaces_.findNearestIntersection
            (
                identity(surfaces_.surfaces().size()),
                start,
                end,

166
167
168
169
                ccSurface1,
                ccHit1,
                ccRegion1,
                ccNormal1,
170

171
172
173
174
                ccSurface2,
                ccHit2,
                ccRegion2,
                ccNormal2
175
176
177
            );
        }

178
179
180
181
182
183
        start.clear();
        end.clear();

        DynamicField<point> rayStart(2*ccSurface1.size());
        DynamicField<point> rayEnd(2*ccSurface1.size());
        DynamicField<scalar> gapSize(2*ccSurface1.size());
184

185
186
187
        DynamicField<point> rayStart2(2*ccSurface1.size());
        DynamicField<point> rayEnd2(2*ccSurface1.size());
        DynamicField<scalar> gapSize2(2*ccSurface1.size());
188

189
190
        DynamicList<label> cellMap(2*ccSurface1.size());
        DynamicList<label> compactMap(2*ccSurface1.size());
191

192
        forAll(ccSurface1, i)
193
        {
194
            label surfI = ccSurface1[i];
195
196
197

            if (surfI != -1)
            {
198
199
                label globalRegionI =
                    surfaces_.globalRegion(surfI, ccRegion1[i]);
200
201

                label faceI = testFaces[i];
202
                const point& surfPt = ccHit1[i].hitPoint();
203
204

                label own = mesh_.faceOwner()[faceI];
205
206
207
208
209
                if
                (
                    cellToCompact[own] != -1
                 && shellGapInfo[cellToCompact[own]][2] > 0
                )
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
                {
                    // Combine info from shell and surface
                    label compactI = cellToCompact[own];
                    FixedList<label, 3> gapInfo;
                    volumeType gapMode;
                    mergeGapInfo
                    (
                        shellGapInfo[compactI],
                        shellGapMode[compactI],
                        extendedGapLevel[globalRegionI],
                        extendedGapMode[globalRegionI],
                        gapInfo,
                        gapMode
                    );

                    const point& cc = cellCentres[own];
226
                    label nRays = generateRays
227
228
229
                    (
                        false,
                        surfPt,
230
                        ccNormal1[i],
231
232
                        gapInfo,
                        gapMode,
233
                        surfPt+((cc-surfPt)&ccNormal1[i])*ccNormal1[i],
234
235
                        cellLevel[own],

236
237
238
                        rayStart,
                        rayEnd,
                        gapSize,
239

240
241
242
243
244
                        rayStart2,
                        rayEnd2,
                        gapSize2
                    );
                    for (label j = 0; j < nRays; j++)
245
                    {
246
247
                        cellMap.append(own);
                        compactMap.append(i);
248
249
250
251
252
                    }
                }
                if (mesh_.isInternalFace(faceI))
                {
                    label nei = mesh_.faceNeighbour()[faceI];
253
254
255
256
257
                    if
                    (
                        cellToCompact[nei] != -1
                     && shellGapInfo[cellToCompact[nei]][2] > 0
                    )
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
                    {
                        // Combine info from shell and surface
                        label compactI = cellToCompact[nei];
                        FixedList<label, 3> gapInfo;
                        volumeType gapMode;
                        mergeGapInfo
                        (
                            shellGapInfo[compactI],
                            shellGapMode[compactI],
                            extendedGapLevel[globalRegionI],
                            extendedGapMode[globalRegionI],
                            gapInfo,
                            gapMode
                        );

                        const point& cc = cellCentres[nei];
274
                        label nRays = generateRays
275
276
277
                        (
                            false,
                            surfPt,
278
                            ccNormal1[i],
279
280
                            gapInfo,
                            gapMode,
281
                            surfPt+((cc-surfPt)&ccNormal1[i])*ccNormal1[i],
282
283
                            cellLevel[nei],

284
285
286
                            rayStart,
                            rayEnd,
                            gapSize,
287

288
289
290
291
292
                            rayStart2,
                            rayEnd2,
                            gapSize2
                        );
                        for (label j = 0; j < nRays; j++)
293
                        {
294
295
                            cellMap.append(nei);
                            compactMap.append(i);
296
297
298
299
300
                        }
                    }
                }
                else
                {
301
302
303
304
                    // Note: on coupled face. What cell are we going to
                    // refine? We've got the neighbouring cell centre
                    // and level but we cannot mark it for refinement on
                    // this side...
305
306
                    label bFaceI = faceI - mesh_.nInternalFaces();

307
308
309
310
311
                    if
                    (
                        bFaceToCompact[bFaceI] != -1
                     && shellGapInfo[bFaceToCompact[bFaceI]][2] > 0
                    )
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
                    {
                        // Combine info from shell and surface
                        label compactI = bFaceToCompact[bFaceI];
                        FixedList<label, 3> gapInfo;
                        volumeType gapMode;
                        mergeGapInfo
                        (
                            shellGapInfo[compactI],
                            shellGapMode[compactI],
                            extendedGapLevel[globalRegionI],
                            extendedGapMode[globalRegionI],
                            gapInfo,
                            gapMode
                        );

                        const point& cc = neiCc[bFaceI];
328
                        label nRays = generateRays
329
330
331
                        (
                            false,
                            surfPt,
332
                            ccNormal1[i],
333
334
                            gapInfo,
                            gapMode,
335
                            surfPt+((cc-surfPt)&ccNormal1[i])*ccNormal1[i],
336
337
                            neiLevel[bFaceI],

338
339
340
                            rayStart,
                            rayEnd,
                            gapSize,
341

342
343
344
345
346
                            rayStart2,
                            rayEnd2,
                            gapSize2
                        );
                        for (label j = 0; j < nRays; j++)
347
                        {
348
349
                            cellMap.append(-1); // See above.
                            compactMap.append(i);
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
        Info<< "Shooting " << returnReduce(rayStart.size(), sumOp<label>())
            << " rays from " << returnReduce(testFaces.size(), sumOp<label>())
            << " intersected faces" << endl;

        rayStart.shrink();
        rayEnd.shrink();
        gapSize.shrink();

        rayStart2.shrink();
        rayEnd2.shrink();
        gapSize2.shrink();

        cellMap.shrink();
        compactMap.shrink();

        testFaces.clear();
        ccSurface1.clear();
        ccHit1.clear();
        ccRegion1.clear();
        ccNormal1 = UIndirectList<vector>(ccNormal1, compactMap)();


        // Do intersections in pairs
        labelList surf1;
        List<pointIndexHit> hit1;
        vectorField normal1;
382
383
        surfaces_.findNearestIntersection
        (
384
385
386
387
388
            rayStart,
            rayEnd,
            surf1,
            hit1,
            normal1
389
390
        );

391
392
393
394
395
396
397
398
399
400
401
        labelList surf2;
        List<pointIndexHit> hit2;
        vectorField normal2;
        surfaces_.findNearestIntersection
        (
            rayStart2,
            rayEnd2,
            surf2,
            hit2,
            normal2
        );
402

403
        forAll(surf1, i)
404
        {
405
            if (surf1[i] != -1 && surf2[i] != -1)
406
407
408
409
            {
                // Found intersection with surface. Check opposite normal.
                label cellI = cellMap[i];

410
411
412
413
414
415
416
417
418
                if
                (
                    cellI != -1
                 && (mag(normal1[i]&normal2[i]) > planarCos)
                 && (
                        magSqr(hit1[i].hitPoint()-hit2[i].hitPoint())
                      < Foam::sqr(gapSize[i])
                    )
                )
419
420
421
422
423
                {
                    if
                    (
                       !markForRefine
                        (
424
                            surf1[i],
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
                            nAllowRefine,
                            refineCell[cellI],
                            nRefine
                        )
                    )
                    {
                        break;
                    }
                }
            }
        }

        if
        (
            returnReduce(nRefine, sumOp<label>())
          > returnReduce(nAllowRefine, sumOp<label>())
        )
        {
            Info<< "Reached refinement limit." << endl;
        }
    }

    return returnReduce(nRefine-oldNRefine, sumOp<label>());
}


//Foam::meshRefinement::findNearestOppositeOp::findNearestOppositeOp
//(
//    const indexedOctree<treeDataTriSurface>& tree,
//    const point& oppositePoint,
//    const vector& oppositeNormal,
//    const scalar minCos
//)
//:
//    tree_(tree),
//    oppositePoint_(oppositePoint),
//    oppositeNormal_(oppositeNormal),
//    minCos_(minCos)
//{}
//
//
//void Foam::meshRefinement::findNearestOppositeOp::operator()
//(
//    const labelUList& indices,
//    const point& sample,
//    scalar& nearestDistSqr,
//    label& minIndex,
//    point& nearestPoint
//) const
//{
//    const treeDataTriSurface& shape = tree_.shapes();
//    const triSurface& patch = shape.patch();
//    const pointField& points = patch.points();
//
//    forAll(indices, i)
//    {
//        const label index = indices[i];
//        const labelledTri& f = patch[index];
//
//        pointHit nearHit = f.nearestPoint(sample, points);
//        scalar distSqr = sqr(nearHit.distance());
//
//        if (distSqr < nearestDistSqr)
//        {
//            // Nearer. Check if
//            // - a bit way from other hit
//            // - in correct search cone
//            vector d(nearHit.rawPoint()-oppositePoint_);
//            scalar normalDist(d&oppositeNormal_);
//
//            if (normalDist > Foam::sqr(SMALL) && normalDist/mag(d) > minCos_)
//            {
//                nearestDistSqr = distSqr;
//                minIndex = index;
//                nearestPoint = nearHit.rawPoint();
//            }
//        }
//    }
//}
//
//
//void Foam::meshRefinement::searchCone
//(
//    const label surfI,
//    labelList& nearMap,                 // cells
//    scalarField& nearGap,               // gap size
//    List<pointIndexHit>& nearInfo,      // nearest point on surface
//    List<pointIndexHit>& oppositeInfo   // detected point on gap (or miss)
//) const
//{
//    const labelList& cellLevel = meshCutter_.cellLevel();
//    const pointField& cellCentres = mesh_.cellCentres();
//    const scalar edge0Len = meshCutter_.level0EdgeLength();
//
//    const labelList& surfaceIndices = surfaces_.surfaces();
520
//    const List<FixedList<label, 3>>& extendedGapLevel =
521
522
523
524
525
526
527
528
529
530
531
//        surfaces_.extendedGapLevel();
//    const List<volumeType>& extendedGapMode = surfaces_.extendedGapMode();
//
//
//    label geomI = surfaceIndices[surfI];
//    const searchableSurface& geom = surfaces_.geometry()[geomI];
//
//    const triSurfaceMesh& s = refCast<const triSurfaceMesh>(geom);
//    const indexedOctree<treeDataTriSurface>& tree = s.tree();
//
//
532
//    const scalar searchCos = Foam::cos(degToRad(30.0));
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
//
//    // Normals for ray shooting and inside/outside detection
//    vectorField nearNormal;
//    geom.getNormal(nearInfo, nearNormal);
//    // Regions
//    labelList nearRegion;
//    geom.getRegion(nearInfo, nearRegion);
//
//
//    // Now loop over all near points and search in the half cone
//    labelList map(nearInfo.size());
//    label compactI = 0;
//
//    oppositeInfo.setSize(nearInfo.size());
//
//    forAll(nearInfo, i)
//    {
//        label globalRegionI =
//            surfaces_.globalRegion(surfI, nearRegion[i]);
//
//        // Get updated gap information now we have the region
//        label nGapCells = extendedGapLevel[globalRegionI][0];
//        label minLevel = extendedGapLevel[globalRegionI][1];
//        label maxLevel = extendedGapLevel[globalRegionI][2];
//        volumeType mode = extendedGapMode[globalRegionI];
//
//        label cellI = nearMap[i];
//        label cLevel = cellLevel[cellI];
//
//        if (cLevel >= minLevel && cLevel < maxLevel)
//        {
564
//            scalar cellSize = edge0Len/pow(2.0, cLevel);
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
//
//            // Update gap size
//            nearGap[i] = nGapCells*cellSize;
//
//            const point& nearPt = nearInfo[i].hitPoint();
//            vector v(cellCentres[cellI]-nearPt);
//            scalar magV = mag(v);
//
//            // Like with ray shooting we want to
//            // - find triangles up to nearGap away on the wanted side of the
//            //   surface
//            // - find triangles up to 0.5*cellSize away on the unwanted side
//            //   of the surface. This is for cells straddling the surface
//            //   where
//            //   the cell centre might be on the wrong side of the surface
//
//            // Tbd: check that cell centre is inbetween the gap hits
//            // (only if the cell is far enough away)
//
//            scalar posNormalSize = 0.0;
//            scalar negNormalSize = 0.0;
//
//            if (mode == volumeType::OUTSIDE)
//            {
//                posNormalSize = nearGap[i];
//                if (magV < 0.5*cellSize)
//                {
//                    negNormalSize = 0.5*cellSize;
//                }
//            }
//            else if (mode == volumeType::INSIDE)
//            {
//                if (magV < 0.5*cellSize)
//                {
//                    posNormalSize = 0.5*cellSize;
//                }
//                negNormalSize = nearGap[i];
//            }
//            else
//            {
//                posNormalSize = nearGap[i];
//                negNormalSize = nearGap[i];
//            }
//
//            // Test with positive normal
//            oppositeInfo[compactI] = tree.findNearest
//            (
//                nearPt,
//                sqr(posNormalSize),
//                findNearestOppositeOp
//                (
//                    tree,
//                    nearPt,
//                    nearNormal[i],
//                    searchCos
//                )
//            );
//
//            if (oppositeInfo[compactI].hit())
//            {
//                map[compactI++] = i;
//            }
//            else
//            {
//                // Test with negative normal
//                oppositeInfo[compactI] = tree.findNearest
//                (
//                    nearPt,
//                    sqr(negNormalSize),
//                    findNearestOppositeOp
//                    (
//                        tree,
//                        nearPt,
//                        -nearNormal[i],
//                        searchCos
//                    )
//                );
//
//                if (oppositeInfo[compactI].hit())
//                {
//                    map[compactI++] = i;
//                }
//            }
//        }
//    }
//
//    Info<< "Selected " << returnReduce(compactI, sumOp<label>())
//        << " hits on the correct side out of "
//        << returnReduce(map.size(), sumOp<label>()) << endl;
//    map.setSize(compactI);
//    oppositeInfo.setSize(compactI);
//
657
//    nearMap = labelUIndList(nearMap, map)();
658
659
660
661
662
//    nearGap = UIndirectList<scalar>(nearGap, map)();
//    nearInfo = UIndirectList<pointIndexHit>(nearInfo, map)();
//    nearNormal = UIndirectList<vector>(nearNormal, map)();
//
//    // Exclude hits which aren't opposite enough. E.g. you might find
Andrew Heather's avatar
Andrew Heather committed
663
//    // a point on a perpendicular wall - but this does not constitute a gap.
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
//    vectorField oppositeNormal;
//    geom.getNormal(oppositeInfo, oppositeNormal);
//
//    compactI = 0;
//    forAll(oppositeInfo, i)
//    {
//        if ((nearNormal[i] & oppositeNormal[i]) < -0.707)
//        {
//            map[compactI++] = i;
//        }
//    }
//
//    Info<< "Selected " << returnReduce(compactI, sumOp<label>())
//        << " hits opposite the nearest out of "
//        << returnReduce(map.size(), sumOp<label>()) << endl;
//    map.setSize(compactI);
//
681
//    nearMap = labelUIndList(nearMap, map)();
682
683
684
685
686
687
//    nearGap = UIndirectList<scalar>(nearGap, map)();
//    nearInfo = UIndirectList<pointIndexHit>(nearInfo, map)();
//    oppositeInfo = UIndirectList<pointIndexHit>(oppositeInfo, map)();
//}


688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
Foam::label Foam::meshRefinement::generateRays
(
    const point& nearPoint,
    const vector& nearNormal,
    const FixedList<label, 3>& gapInfo,
    const volumeType& mode,

    const label cLevel,

    DynamicField<point>& start,
    DynamicField<point>& end
) const
{
    label nOldRays = start.size();

703
    if (cLevel >= gapInfo[1] && cLevel < gapInfo[2] && gapInfo[0] > 0)
704
    {
705
        scalar cellSize = meshCutter_.level0EdgeLength()/pow(2.0, cLevel);
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

        // Calculate gap size
        scalar nearGap = gapInfo[0]*cellSize;

        const vector& n = nearNormal;

        // Situation 'C' above: cell too close. Use surface
        // -normal and -point to shoot rays

        if (mode == volumeType::OUTSIDE)
        {
            start.append(nearPoint+1e-6*n);
            end.append(nearPoint+nearGap*n);
        }
        else if (mode == volumeType::INSIDE)
        {
            start.append(nearPoint-1e-6*n);
            end.append(nearPoint-nearGap*n);
        }
        else if (mode == volumeType::MIXED)
        {
            start.append(nearPoint+1e-6*n);
            end.append(nearPoint+nearGap*n);

            start.append(nearPoint-1e-6*n);
            end.append(nearPoint-nearGap*n);
        }
    }

    return start.size()-nOldRays;
}


Foam::label Foam::meshRefinement::generateRays
740
741
742
743
744
745
746
747
748
749
750
(
    const bool useSurfaceNormal,

    const point& nearPoint,
    const vector& nearNormal,
    const FixedList<label, 3>& gapInfo,
    const volumeType& mode,

    const point& cc,
    const label cLevel,

751
752
753
754
755
756
757
    DynamicField<point>& start,
    DynamicField<point>& end,
    DynamicField<scalar>& gapSize,

    DynamicField<point>& start2,
    DynamicField<point>& end2,
    DynamicField<scalar>& gapSize2
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
) const
{
    // We want to handle the following cases:
    // - surface: small gap (marked with 'surface'). gap might be
    //            on inside or outside of surface.
    // - A: cell well inside the gap.
    // - B: cell well outside the gap.
    // - C: cell straddling the gap. cell centre might be inside
    //      or outside
    //
    //       +---+
    //       | B |
    //       +---+
    //
    //            +------+
    //            |      |
    //            |   C  |
    //    --------|------|----surface
    //            +------+
    //
    //        +---+
    //        | A |
    //        +---+
    //
    //
    //    --------------------surface
    //
    // So:
    // - find nearest point on surface
    // - in situation A,B decide if on wanted side of surface
    // - detect if locally a gap (and the cell inside the gap) by
    //   shooting a ray from the point on the surface in the direction
    //   of
    //   - A,B: the cell centre
    //   - C: the surface normal and/or negative surface normal
    //   and see we hit anything
    //
    // Variations of this scheme:
    // - always shoot in the direction of the surface normal. This needs
    //   then an additional check to make sure the cell centre is
    //   somewhere inside the gap
    // - instead of ray shooting use a 'constrained' nearest search
    //   by e.g. looking inside a search cone (implemented in searchCone).
    //   The problem with this constrained nearest is that it still uses
    //   the absolute nearest point on each triangle and only afterwards
    //   checks if it is inside the search cone.


    // Decide which near points are good:
    // - with updated minLevel and maxLevel and nearGap make sure
    //   the cell is still a candidate
    //   NOTE: inside the gap the nearest point on the surface will
    //         be HALF the gap size - otherwise we would have found
    //         a point on the opposite side
    // - if the mode is both sides
    // - or if the hit is inside the current cell (situation 'C',
    //   magV < 0.5cellSize)
    // - or otherwise if on the correct side

817
    label nOldRays = start.size();
818

819
    if (cLevel >= gapInfo[1] && cLevel < gapInfo[2] && gapInfo[0] > 0)
820
    {
821
        scalar cellSize = meshCutter_.level0EdgeLength()/pow(2.0, cLevel);
822
823
824
825
826
827
828
829
830
831
832
833
834

        // Calculate gap size
        scalar nearGap = gapInfo[0]*cellSize;

        // Distance to nearest
        vector v(cc-nearPoint);
        scalar magV = mag(v);

        if (useSurfaceNormal || magV < 0.5*cellSize)
        {
            const vector& n = nearNormal;

            // Situation 'C' above: cell too close. Use surface
835
            // -normal and -point to shoot rays
836
837
838

            if (mode == volumeType::OUTSIDE)
            {
839
840
841
842
843
844
845
                start.append(nearPoint+1e-6*n);
                end.append(nearPoint+nearGap*n);
                gapSize.append(nearGap);
                // Second vector so we get pairs of intersections
                start2.append(nearPoint+1e-6*n);
                end2.append(nearPoint-1e-6*n);
                gapSize2.append(gapSize.last());
846
847
848
            }
            else if (mode == volumeType::INSIDE)
            {
849
850
851
852
853
854
855
                start.append(nearPoint-1e-6*n);
                end.append(nearPoint-nearGap*n);
                gapSize.append(nearGap);
                // Second vector so we get pairs of intersections
                start2.append(nearPoint-1e-6*n);
                end2.append(nearPoint+1e-6*n);
                gapSize2.append(gapSize.last());
856
857
858
            }
            else if (mode == volumeType::MIXED)
            {
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
                // Do both rays:
                // Outside
                {
                    start.append(nearPoint+1e-6*n);
                    end.append(nearPoint+nearGap*n);
                    gapSize.append(nearGap);
                    // Second vector so we get pairs of intersections
                    start2.append(nearPoint+1e-6*n);
                    end2.append(nearPoint-1e-6*n);
                    gapSize2.append(gapSize.last());
                }
                // Inside
                {
                    start.append(nearPoint-1e-6*n);
                    end.append(nearPoint-nearGap*n);
                    gapSize.append(nearGap);
                    // Second vector so we get pairs of intersections
                    start2.append(nearPoint-1e-6*n);
                    end2.append(nearPoint+1e-6*n);
                    gapSize2.append(gapSize.last());
                }
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
            }
        }
        else
        {
            // Situation 'A' or 'B' above: cell well away. Test if
            // cell on correct side of surface and shoot ray through
            // cell centre. Note: no need to shoot ray in other
            // direction since we're trying to detect cell inside
            // the gap.

            scalar s = (v&nearNormal);

            if
            (
                (mode == volumeType::MIXED)
             || (mode == volumeType::OUTSIDE && s > SMALL)
             || (mode == volumeType::INSIDE && s < -SMALL)
            )
            {
899
                //// Use single vector through cell centre
900
901
902
903
904
905
906
907
908
909
910
                //vector n(v/(magV+ROOTVSMALL));
                //
                //start.append(cc);
                //end.append(cc+nearGap*n);
                //gapSize.append(nearGap);
                //
                //start2.append(cc);
                //end2.append(cc-nearGap*n);
                //gapSize2.append(nearGap);


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
                //// Shoot some rays through the cell centre
                //// X-direction:
                //start.append(cc);
                //end.append(cc+nearGap*vector(1, 0, 0));
                //gapSize.append(nearGap);
                //
                //start2.append(cc);
                //end2.append(cc-nearGap*vector(1, 0, 0));
                //gapSize2.append(nearGap);
                //
                //// Y-direction:
                //start.append(cc);
                //end.append(cc+nearGap*vector(0, 1, 0));
                //gapSize.append(nearGap);
                //
                //start2.append(cc);
                //end2.append(cc-nearGap*vector(0, 1, 0));
                //gapSize2.append(nearGap);
                //
                //// Z-direction:
                //start.append(cc);
                //end.append(cc+nearGap*vector(0, 0, 1));
                //gapSize.append(nearGap);
                //
                //start2.append(cc);
                //end2.append(cc-nearGap*vector(0, 0, 1));
                //gapSize2.append(nearGap);


                // 3 axes aligned with normal

                // Use vector through cell centre
                vector n(v/(magV+ROOTVSMALL));

                // Get second vector. Make sure it is sufficiently perpendicular
                vector e2(1, 0, 0);
                scalar s = (e2 & n);
                if (mag(s) < 0.9)
                {
                    e2 -= s*n;
                }
                else
                {
                    e2 = vector(0, 1, 0);
                    e2 -= (e2 & n)*n;
                }
                e2 /= mag(e2);

                // Third vector
                vector e3 = n ^ e2;


                // Rays in first direction
964
                start.append(cc);
965
                end.append(cc+nearGap*n);
966
967
968
                gapSize.append(nearGap);

                start2.append(cc);
969
                end2.append(cc-nearGap*n);
970
971
                gapSize2.append(nearGap);

972
                // Rays in second direction
973
                start.append(cc);
974
                end.append(cc+nearGap*e2);
975
976
977
                gapSize.append(nearGap);

                start2.append(cc);
978
                end2.append(cc-nearGap*e2);
979
980
                gapSize2.append(nearGap);

981
                // Rays in third direction
982
                start.append(cc);
983
                end.append(cc+nearGap*e3);
984
985
986
                gapSize.append(nearGap);

                start2.append(cc);
987
                end2.append(cc-nearGap*e3);
988
                gapSize2.append(nearGap);
989
990
991
992
            }
        }
    }

993
    return start.size()-nOldRays;
994
995
996
997
998
999
1000
1001
1002
}


void Foam::meshRefinement::selectGapCandidates
(
    const labelList& refineCell,
    const label nRefine,

    labelList& cellMap,
1003
    List<FixedList<label, 3>>& shellGapInfo,
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
    List<volumeType>& shellGapMode
) const
{
    const labelList& cellLevel = meshCutter_.cellLevel();
    const pointField& cellCentres = mesh_.cellCentres();

    // Collect cells to test
    cellMap.setSize(cellLevel.size()-nRefine);
    label compactI = 0;

    forAll(cellLevel, cellI)
    {
        if (refineCell[cellI] == -1)
        {
            cellMap[compactI++] = cellI;
        }
    }
    Info<< "Selected " << returnReduce(compactI, sumOp<label>())
        << " unmarked cells out of "
        << mesh_.globalData().nTotalCells() << endl;
    cellMap.setSize(compactI);

    // Do test to see whether cells are inside/outside shell with
    // applicable specification (minLevel <= celllevel < maxLevel)
    shells_.findHigherGapLevel
    (
        pointField(cellCentres, cellMap),
1031
        labelUIndList(cellLevel, cellMap)(),
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
        shellGapInfo,
        shellGapMode
    );

    // Compact out hits

    labelList map(shellGapInfo.size());
    compactI = 0;
    forAll(shellGapInfo, i)
    {
        if (shellGapInfo[i][2] > 0)
        {
            map[compactI++] = i;
        }
    }

    Info<< "Selected " << returnReduce(compactI, sumOp<label>())
        << " cells inside gap shells out of "
        << mesh_.globalData().nTotalCells() << endl;

    map.setSize(compactI);
1053
    cellMap = labelUIndList(cellMap, map)();
1054
    shellGapInfo = UIndirectList<FixedList<label, 3>>(shellGapInfo, map)();
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
    shellGapMode = UIndirectList<volumeType>(shellGapMode, map)();
}


void Foam::meshRefinement::mergeGapInfo
(
    const FixedList<label, 3>& shellGapInfo,
    const volumeType shellGapMode,
    const FixedList<label, 3>& surfGapInfo,
    const volumeType surfGapMode,
    FixedList<label, 3>& gapInfo,
    volumeType& gapMode
) const
{
    if (surfGapInfo[0] == 0)
    {
        gapInfo = shellGapInfo;
        gapMode = shellGapMode;
    }
    else if (shellGapInfo[0] == 0)
    {
        gapInfo = surfGapInfo;
        gapMode = surfGapMode;
    }
    else
    {
        // Both specify a level. Does surface level win? Or does information
        // need to be merged?

        //gapInfo[0] = max(surfGapInfo[0], shellGapInfo[0]);
        //gapInfo[1] = min(surfGapInfo[1], shellGapInfo[1]);
        //gapInfo[2] = max(surfGapInfo[2], shellGapInfo[2]);
        gapInfo = surfGapInfo;
        gapMode = surfGapMode;
    }
}


Foam::label Foam::meshRefinement::markInternalGapRefinement
(
    const scalar planarCos,
1096
    const bool spreadGapSize,
1097
1098
1099
    const label nAllowRefine,

    labelList& refineCell,
1100
1101
1102
    label& nRefine,
    labelList& numGapCells,
    scalarField& detectedGapSize
1103
1104
) const
{
1105
1106
1107
1108
1109
    detectedGapSize.setSize(mesh_.nCells());
    detectedGapSize = GREAT;
    numGapCells.setSize(mesh_.nCells());
    numGapCells = -1;

1110
1111
1112
1113
    const labelList& cellLevel = meshCutter_.cellLevel();
    const pointField& cellCentres = mesh_.cellCentres();
    const scalar edge0Len = meshCutter_.level0EdgeLength();

1114
    const List<FixedList<label, 3>>& extendedGapLevel =
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
        surfaces_.extendedGapLevel();
    const List<volumeType>& extendedGapMode = surfaces_.extendedGapMode();

    // Get the gap level for the shells
    const labelList maxLevel(shells_.maxGapLevel());

    label oldNRefine = nRefine;

    if (max(maxLevel) > 0)
    {
        // Collect cells to test
        labelList cellMap;
1127
        List<FixedList<label, 3>> shellGapInfo;
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
        List<volumeType> shellGapMode;
        selectGapCandidates
        (
            refineCell,
            nRefine,

            cellMap,
            shellGapInfo,
            shellGapMode
        );

        // Find nearest point and normal on the surfaces
        List<pointIndexHit> nearInfo;
        vectorField nearNormal;
        labelList nearSurface;
        labelList nearRegion;
        {
            // Now we have both the cell-level and the gap size information. Use
            // this to calculate the gap size
            scalarField gapSize(cellMap.size());
            forAll(cellMap, i)
            {
                label cellI = cellMap[i];
1151
                scalar cellSize = edge0Len/pow(2.0, cellLevel[cellI]);
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
                gapSize[i] = shellGapInfo[i][0]*cellSize;
            }

            surfaces_.findNearestRegion
            (
                identity(surfaces_.surfaces().size()),
                pointField(cellCentres, cellMap),
                sqr(gapSize),
                nearSurface,
                nearInfo,
                nearRegion,
                nearNormal
            );
        }



1169
1170
1171
1172
1173
1174
1175
1176
        DynamicList<label> map(nearInfo.size());
        DynamicField<point> rayStart(nearInfo.size());
        DynamicField<point> rayEnd(nearInfo.size());
        DynamicField<scalar> gapSize(nearInfo.size());

        DynamicField<point> rayStart2(nearInfo.size());
        DynamicField<point> rayEnd2(nearInfo.size());
        DynamicField<scalar> gapSize2(nearInfo.size());
1177

1178
        label nTestCells = 0;
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202

        forAll(nearInfo, i)
        {
            if (nearInfo[i].hit())
            {
                label globalRegionI = surfaces_.globalRegion
                (
                    nearSurface[i],
                    nearRegion[i]
                );

                // Combine info from shell and surface
                FixedList<label, 3> gapInfo;
                volumeType gapMode;
                mergeGapInfo
                (
                    shellGapInfo[i],
                    shellGapMode[i],
                    extendedGapLevel[globalRegionI],
                    extendedGapMode[globalRegionI],
                    gapInfo,
                    gapMode
                );

1203
1204
1205
1206
1207
1208
1209
                // Store wanted number of cells in gap
                label cellI = cellMap[i];
                label cLevel = cellLevel[cellI];
                if (cLevel >= gapInfo[1] && cLevel < gapInfo[2])
                {
                    numGapCells[cellI] = max(numGapCells[cellI], gapInfo[0]);
                }
1210

1211
1212
                // Construct one or more rays to test for oppositeness
                label nRays = generateRays
1213
1214
1215
1216
1217
1218
1219
                (
                    false,
                    nearInfo[i].hitPoint(),
                    nearNormal[i],
                    gapInfo,
                    gapMode,

1220
1221
                    cellCentres[cellI],
                    cLevel,
1222

1223
1224
1225
1226
1227
1228
1229
                    rayStart,
                    rayEnd,
                    gapSize,

                    rayStart2,
                    rayEnd2,
                    gapSize2
1230
                );
1231
                if (nRays > 0)
1232
                {
1233
1234
1235
1236
1237
                    nTestCells++;
                    for (label j = 0; j < nRays; j++)
                    {
                        map.append(i);
                    }
1238
1239
1240
1241
                }
            }
        }

1242
        Info<< "Selected " << returnReduce(nTestCells, sumOp<label>())
1243
1244
            << " cells for testing out of "
            << mesh_.globalData().nTotalCells() << endl;
1245
1246
1247
1248
1249
1250
1251
1252
        map.shrink();
        rayStart.shrink();
        rayEnd.shrink();
        gapSize.shrink();

        rayStart2.shrink();
        rayEnd2.shrink();
        gapSize2.shrink();
1253

1254
        cellMap = labelUIndList(cellMap, map)();
1255
1256
1257
1258
1259
1260
1261
1262
        nearNormal = UIndirectList<vector>(nearNormal, map)();
        shellGapInfo.clear();
        shellGapMode.clear();
        nearInfo.clear();
        nearSurface.clear();
        nearRegion.clear();


1263
1264
1265
1266
        // Do intersections in pairs
        labelList surf1;
        List<pointIndexHit> hit1;
        vectorField normal1;
1267
1268
        surfaces_.findNearestIntersection
        (
1269
1270
1271
1272
1273
            rayStart,
            rayEnd,
            surf1,
            hit1,
            normal1
1274
        );
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289

        labelList surf2;
        List<pointIndexHit> hit2;
        vectorField normal2;
        surfaces_.findNearestIntersection
        (
            rayStart2,
            rayEnd2,
            surf2,
            hit2,
            normal2
        );

        // Extract cell based gap size
        forAll(surf1, i)
1290
        {
1291
            if (surf1[i] != -1 && surf2[i] != -1)
1292
            {
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
                // Found intersections with surface. Check for
                // - small gap
                // - coplanar normals

                label cellI = cellMap[i];

                scalar d2 = magSqr(hit1[i].hitPoint()-hit2[i].hitPoint());

                if
                (
                    cellI != -1
                 && (mag(normal1[i]&normal2[i]) > planarCos)
                 && (d2 < Foam::sqr(gapSize[i]))
                )
1307
                {
1308
1309
1310
1311
1312
                    detectedGapSize[cellI] = min
                    (
                        detectedGapSize[cellI],
                        Foam::sqrt(d2)
                    );
1313
1314
1315
1316
                }
            }
        }

1317
1318
        // Spread it
        if (spreadGapSize)
1319
        {
1320
1321
1322
1323
1324
1325
            // Field on cells and faces
            List<transportData> cellData(mesh_.nCells());
            List<transportData> faceData(mesh_.nFaces());

            // Start of walk
            const pointField& faceCentres = mesh_.faceCentres();
1326

1327
1328
1329
            DynamicList<label> frontFaces(mesh_.nFaces());
            DynamicList<transportData> frontData(mesh_.nFaces());
            for (label faceI = 0; faceI < mesh_.nInternalFaces(); faceI++)
1330
            {
1331
1332
                label own = mesh_.faceOwner()[faceI];
                label nei = mesh_.faceNeighbour()[faceI];
1333

1334
1335
1336
1337
1338
                scalar minSize = min
                (
                    detectedGapSize[own],
                    detectedGapSize[nei]
                );
1339

1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
                if (minSize < GREAT)
                {
                    frontFaces.append(faceI);
                    frontData.append
                    (
                        transportData
                        (
                            faceCentres[faceI],
                            minSize,
                            0.0
                        )
                    );
                }
            }
            for
            (
                label faceI = mesh_.nInternalFaces();
                faceI < mesh_.nFaces();
                faceI++
            )
            {
                label own = mesh_.faceOwner()[faceI];

                if (detectedGapSize[own] < GREAT)
                {
                    frontFaces.append(faceI);
                    frontData.append
                    (
                        transportData
                        (
                            faceCentres[faceI],
                            detectedGapSize[own],
                            0.0
                        )
                    );
                }
            }

            Info<< "Selected "
                << returnReduce(frontFaces.size(), sumOp<label>())
                << " faces for spreading gap size out of "
                << mesh_.globalData().nTotalFaces() << endl;


1384
            transportData::trackData td(surfaceIndex());
1385
1386

            FaceCellWave<transportData, transportData::trackData> deltaCalc
1387
1388
1389
1390
1391
1392
            (
                mesh_,
                frontFaces,
                frontData,
                faceData,
                cellData,
1393
1394
                mesh_.globalData().nTotalCells()+1,
                td
1395
1396
1397
1398
1399
1400
            );


            forAll(cellMap, i)
            {
                label cellI = cellMap[i];
1401
1402
                if
                (
1403
1404
1405
                    cellI != -1
                 && cellData[cellI].valid(deltaCalc.data())
                 && numGapCells[cellI] != -1
1406
1407
                )
                {
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
                    // Update transported gap size
                    detectedGapSize[cellI] = min
                    (
                        detectedGapSize[cellI],
                        cellData[cellI].data()
                    );
                }
            }
        }


        // Use it
        forAll(cellMap, i)
        {
            label cellI = cellMap[i];

            if (cellI != -1 && numGapCells[cellI] != -1)
            {
                // Needed gap size
                label cLevel = cellLevel[cellI];
1428
1429
                scalar cellSize =
                    meshCutter_.level0EdgeLength()/pow(2.0, cLevel);
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
                scalar neededGapSize = numGapCells[cellI]*cellSize;

                if (neededGapSize > detectedGapSize[cellI])
                {
                    if
                    (
                       !markForRefine
                        (
                            123,
                            nAllowRefine,
                            refineCell[cellI],
                            nRefine
                        )
                    )
                    {
                        break;
                    }
1447
1448
1449
1450
                }
            }
        }

1451

1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
        if
        (
            returnReduce(nRefine, sumOp<label>())
          > returnReduce(nAllowRefine, sumOp<label>())
        )
        {
            Info<< "Reached refinement limit." << endl;
        }
    }

    return returnReduce(nRefine-oldNRefine, sumOp<label>());
}


Foam::label Foam::meshRefinement::markSmallFeatureRefinement
(
    const scalar planarCos,
    const label nAllowRefine,
    const labelList& neiLevel,
    const pointField& neiCc,

    labelList& refineCell,
    label& nRefine
) const
{
    const labelList& cellLevel = meshCutter_.cellLevel();
    const labelList& surfaceIndices = surfaces_.surfaces();
1479
    const List<FixedList<label, 3>>& extendedGapLevel =
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
        surfaces_.extendedGapLevel();
    const List<volumeType>& extendedGapMode = surfaces_.extendedGapMode();

    label oldNRefine = nRefine;

    // Check that we're using any gap refinement
    labelList shellMaxLevel(shells_.maxGapLevel());

    if (max(shellMaxLevel) == 0)
    {
        return 0;
    }

    //- Force calculation of tetBasePt
    (void)mesh_.tetBasePtIs();
    (void)mesh_.cellTree();


    forAll(surfaceIndices, surfI)
    {
        label geomI = surfaceIndices[surfI];
        const searchableSurface& geom = surfaces_.geometry()[geomI];


        // Get the element index in a roundabout way. Problem is e.g.
        // distributed surface where local indices differ from global
        // ones (needed for getRegion call)

        pointField ctrs;
        labelList region;
        vectorField normal;
        {
            // Representative local coordinates and bounding sphere
            scalarField radiusSqr;
            geom.boundingSpheres(ctrs, radiusSqr);

            List<pointIndexHit> info;
            geom.findNearest(ctrs, radiusSqr, info);

            forAll(info, i)
            {
                if (!info[i].hit())
                {
1523
                    FatalErrorInFunction
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
                        << "fc:" << ctrs[i]
                        << " radius:" << radiusSqr[i]
                        << exit(FatalError);
                }
            }

            geom.getRegion(info, region);
            geom.getNormal(info, normal);
        }

        // Do test to see whether triangles are inside/outside shell with
        // applicable specification (minLevel <= celllevel < maxLevel)
1536
        List<FixedList<label, 3>> shellGapInfo;
1537
1538
1539
1540
        List<volumeType> shellGapMode;
        shells_.findHigherGapLevel
        (
            ctrs,
1541
            labelList(ctrs.size(), Zero),
1542
1543
1544
1545
1546
            shellGapInfo,
            shellGapMode
        );


1547
1548
        DynamicList<label> map(ctrs.size());
        DynamicList<label> cellMap(ctrs.size());
1549

1550
1551
1552
1553
1554
        DynamicField<point> rayStart(ctrs.size());
        DynamicField<point> rayEnd(ctrs.size());
        DynamicField<scalar> gapSize(ctrs.size());

        label nTestCells = 0;
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575

        forAll(ctrs, i)
        {
            if (shellGapInfo[i][2] > 0)
            {
                label globalRegionI = surfaces_.globalRegion(surfI, region[i]);

                // Combine info from shell and surface
                FixedList<label, 3> gapInfo;
                volumeType gapMode;
                mergeGapInfo
                (
                    shellGapInfo[i],
                    shellGapMode[i],
                    extendedGapLevel[globalRegionI],
                    extendedGapMode[globalRegionI],
                    gapInfo,
                    gapMode
                );

                //- Option 1: use octree nearest searching inside polyMesh
1576
                //label cellI = mesh_.findCell(pt, polyMesh::CELL_TETS);
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592

                //- Option 2: use octree 'inside' searching inside polyMesh. Is
                //            much faster.
                label cellI = -1;
                const indexedOctree<treeDataCell>& tree = mesh_.cellTree();
                if (tree.nodes().size() && tree.bb().contains(ctrs[i]))
                {
                    cellI = tree.findInside(ctrs[i]);
                }

                if (cellI != -1 && refineCell[cellI] == -1)
                {
                    // Construct one or two rays to test for oppositeness
                    // Note that we always want to use the surface normal
                    // and not the vector from cell centre to surface point

1593
                    label nRays = generateRays
1594
1595
1596
1597
1598
1599
1600
1601
                    (
                        ctrs[i],
                        normal[i],
                        gapInfo,
                        gapMode,

                        cellLevel[cellI],

1602
1603
                        rayStart,
                        rayEnd
1604
                    );
1605
1606

                    if (nRays > 0)
1607
                    {
1608
1609
1610
1611
1612
1613
                        nTestCells++;
                        for (label j = 0; j < nRays; j++)
                        {
                            cellMap.append(cellI);
                            map.append(i);
                        }
1614
1615
1616
1617
1618
                    }
                }
            }
        }

1619
        Info<< "Selected " << returnReduce(nTestCells, sumOp<label>())
1620
1621
            << " cells containing triangle centres out of "
            << mesh_.globalData().nTotalCells() << endl;
1622
1623
1624
1625
        map.shrink();
        cellMap.shrink();
        rayStart.shrink();
        rayEnd.shrink();
1626
1627
1628
1629
1630
1631
1632

        ctrs.clear();
        region.clear();
        shellGapInfo.clear();
        shellGapMode.clear();
        normal = UIndirectList<vector>(normal, map)();

1633
        // Do intersections.
1634
1635
1636
1637
        labelList surfaceHit;
        vectorField surfaceNormal;
        surfaces_.findNearestIntersection
        (
1638
1639
            rayStart,
            rayEnd,
1640
1641
1642
1643
1644
            surfaceHit,
            surfaceNormal
        );


1645
1646
        label nOldRefine = 0;

1647
1648
1649

        forAll(surfaceHit, i)
        {
1650
            if (surfaceHit[i] != -1) // && surf2[i] != -1)
1651
            {
1652
1653
                // Found intersection with surface. Check coplanar normals.
                label cellI = cellMap[i];
1654

1655
1656
1657
                if (mag(normal[i]&surfaceNormal[i]) > planarCos)
                {
                    if
1658
                    (
1659
1660
1661
1662
1663
1664
1665
                       !markForRefine
                        (
                            surfaceHit[i],
                            nAllowRefine,
                            refineCell[cellI],
                            nRefine
                        )
1666
                    )
1667
1668
1669
                    {
                        break;
                    }
1670
1671
1672
1673
1674
                }
            }
        }

        Info<< "For surface " << geom.name() << " found "
1675
            << returnReduce(nRefine-nOldRefine, sumOp<label>())
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
            << " cells in small gaps" << endl;

        if
        (
            returnReduce(nRefine, sumOp<label>())
          > returnReduce(nAllowRefine, sumOp<label>())
        )
        {
            Info<< "Reached refinement limit." << endl;
        }
    }

    return returnReduce(nRefine-oldNRefine, sumOp<label>());
}


// ************************************************************************* //