This file is indexed.

/usr/include/openvdb/tools/ParticleAtlas.h is in libopenvdb-dev 3.2.0-2.1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 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
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 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
 704
 705
 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
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 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
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 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
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
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
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2012-2016 DreamWorks Animation LLC
//
// All rights reserved. This software is distributed under the
// Mozilla Public License 2.0 ( http://www.mozilla.org/MPL/2.0/ )
//
// Redistributions of source code must retain the above copyright
// and license notice and the following restrictions and disclaimer.
//
// *     Neither the name of DreamWorks Animation nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// IN NO EVENT SHALL THE COPYRIGHT HOLDERS' AND CONTRIBUTORS' AGGREGATE
// LIABILITY FOR ALL CLAIMS REGARDLESS OF THEIR BASIS EXCEED US$250.00.
//
///////////////////////////////////////////////////////////////////////////
//
/// @file     ParticleAtlas.h
///
/// @brief    Space-partitioning acceleration structure for particles, points with
///           radius. Partitions particle indices into voxels to accelerate range
///           and nearest neighbor searches.
///
/// @note     This acceleration structure only stores integer offsets into an external particle
///           data structure that conforms to the ParticleArray interface. 
///
/// @details  Constructs and maintains a sequence of @c PointIndexGrids each of progressively
///           lower resolution. Particles are uniquely assigned to a particular resolution
///           level based on their radius. This strategy has proven efficient for accelerating
///           spatial queries on particle data sets with varying radii.
///
/// @details  The data structure automatically detects and adapts to particle data sets with
///           uniform radii. The construction is simplified and spatial queries pre-cache the
///           uniform particle radius to avoid redundant access calls to the
///           ParticleArray::getRadius method.
///
/// @author   Mihai Alden


#ifndef OPENVDB_TOOLS_PARTICLE_ATLAS_HAS_BEEN_INCLUDED
#define OPENVDB_TOOLS_PARTICLE_ATLAS_HAS_BEEN_INCLUDED

#include "PointIndexGrid.h"

#include <openvdb/Grid.h>
#include <openvdb/Types.h>
#include <openvdb/math/Transform.h>
#include <openvdb/tree/Tree.h>
#include <openvdb/tree/LeafNode.h>

#include <boost/scoped_array.hpp>
#include <tbb/blocked_range.h>
#include <tbb/parallel_for.h>
#include <tbb/parallel_reduce.h>
#include <deque>


namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace tools {


////////////////////////////////////////


/// @brief  Partition particles and performs range and nearest-neighbor searches.
///
/// @interface ParticleArray
/// Expected interface for the ParticleArray container:
/// @code
/// template<typename VectorType>
/// struct ParticleArray
/// {
///     // The type used to represent world-space positions
///     typedef VectorType                      PosType;
///     typedef typename PosType::value_type    ScalarType;
///
///     // Return the number of particles in the array
///     size_t size() const;
///
///     // Return the world-space position for the nth particle.
///     void getPos(size_t n, PosType& xyz) const;
///
///     // Return the world-space radius for the nth particle.
///     void getRadius(size_t n, ScalarType& radius) const;
/// };
/// @endcode
///
/// @details    Constructs a collection of @c PointIndexGrids of different resolutions
///             to accelerate spatial searches for particles with varying radius.
template<typename PointIndexGridType = PointIndexGrid>
struct ParticleAtlas
{
    typedef boost::shared_ptr<ParticleAtlas>            Ptr;
    typedef boost::shared_ptr<const ParticleAtlas>      ConstPtr;

    typedef typename PointIndexGridType::Ptr            PointIndexGridPtr;
    typedef typename PointIndexGridType::ValueType      IndexType;

    struct Iterator;

    //////////

    ParticleAtlas() : mIndexGridArray(), mMinRadiusArray(), mMaxRadiusArray() {}

    /// @brief Partitions particle indices
    ///
    /// @param particles        container conforming to the ParticleArray interface
    /// @param minVoxelSize     minimum voxel size limit
    /// @param maxLevels        maximum number of resolution levels
    template<typename ParticleArrayType>
    void construct(const ParticleArrayType& particles, double minVoxelSize, size_t maxLevels = 50);

    /// @brief Create a new @c ParticleAtlas from the given @a particles.
    ///
    /// @param particles        container conforming to the ParticleArray interface
    /// @param minVoxelSize     minimum voxel size limit
    /// @param maxLevels        maximum number of resolution levels
    template<typename ParticleArrayType>
    static Ptr create(const ParticleArrayType& particles, double minVoxelSize, size_t maxLevels = 50);

    /// @brief Returns the number of resolution levels.
    size_t levels() const { return mIndexGridArray.size(); }
    /// @brief true if the container size is 0, false otherwise.
    bool empty() const { return mIndexGridArray.empty(); }

    /// @brief Returns minimum particle radius for level @a n.
    double minRadius(size_t n) const { return mMinRadiusArray[n]; }
    /// @brief Returns maximum particle radius for level @a n.
    double maxRadius(size_t n) const { return mMaxRadiusArray[n]; }

    /// @brief Returns the @c PointIndexGrid that represents the given level @a n.
    PointIndexGridType& pointIndexGrid(size_t n) { return *mIndexGridArray[n]; }
    /// @brief Returns the @c PointIndexGrid that represents the given level @a n.
    const PointIndexGridType& pointIndexGrid(size_t n) const { return *mIndexGridArray[n]; }

private:
    // Disallow copying
    ParticleAtlas(const ParticleAtlas&);
    ParticleAtlas& operator=(const ParticleAtlas&);

    std::vector<PointIndexGridPtr>  mIndexGridArray;
    std::vector<double> mMinRadiusArray, mMaxRadiusArray;
}; // struct ParticleAtlas


typedef ParticleAtlas<PointIndexGrid> ParticleIndexAtlas;


////////////////////////////////////////


/// @brief Provides accelerated range and nearest-neighbor searches for
///        particles that are partitioned using the ParticleAtlas.
///
/// @note  Prefer to construct the iterator object once and reuse it
///        for subsequent queries.
template<typename PointIndexGridType>
struct ParticleAtlas<PointIndexGridType>::Iterator
{
    typedef typename PointIndexGridType::TreeType   TreeType;
    typedef tree::ValueAccessor<const TreeType>     ConstAccessor;
    typedef boost::scoped_ptr<ConstAccessor>        ConstAccessorPtr;

    /////

    /// @brief Construct an iterator from the given @a atlas.
    explicit Iterator(const ParticleAtlas& atlas);

    /// @brief Clear the iterator and update it with the result of the given
    ///        world-space radial query.
    /// @param center    world-space center
    /// @param radius    world-space search radius
    /// @param particles container conforming to the ParticleArray interface
    template<typename ParticleArrayType>
    void worldSpaceSearchAndUpdate(const Vec3d& center, double radius, const ParticleArrayType& particles);

    /// @brief Clear the iterator and update it with the result of the given
    ///        world-space radial query.
    /// @param bbox      world-space bounding box
    /// @param particles container conforming to the ParticleArray interface
    template<typename ParticleArrayType>
    void worldSpaceSearchAndUpdate(const BBoxd& bbox, const ParticleArrayType& particles);

    /// @brief Returns the total number of resolution levels.
    size_t levels() const { return mAtlas->levels(); }

    /// @brief Clear the iterator and update it with all particles that reside
    ///        at the given resolution @a level.
    void updateFromLevel(size_t level);

    /// Reset the iterator to point to the first item.
    void reset();

    /// Return a const reference to the item to which this iterator is pointing.
    const IndexType& operator*() const { return *mRange.first; }

    /// @{
    /// @brief  Return @c true if this iterator is not yet exhausted.
    bool test() const { return mRange.first < mRange.second || mIter != mRangeList.end(); }
    operator bool() const { return this->test(); }
    /// @}

    /// Advance iterator to next item.
    void increment();

    /// Advance iterator to next item.
    void operator++() { this->increment(); }

    /// @brief Advance iterator to next item.
    /// @return @c true if this iterator is not yet exhausted.
    bool next();

    /// Return the number of point indices in the iterator range.
    size_t size() const;

    /// Return @c true if both iterators point to the same element.
    bool operator==(const Iterator& p) const { return mRange.first == p.mRange.first; }
    bool operator!=(const Iterator& p) const { return !this->operator==(p); }

private:
    Iterator(const Iterator& rhs);
    Iterator& operator=(const Iterator& rhs);

    void clear();

    typedef std::pair<const IndexType*, const IndexType*> Range;
    typedef std::deque<Range>                             RangeDeque;
    typedef typename RangeDeque::const_iterator           RangeDequeCIter;
    typedef boost::scoped_array<IndexType>                IndexArray;

    ParticleAtlas const * const mAtlas;
    boost::scoped_array<ConstAccessorPtr> mAccessorList;

    // Primary index collection
    Range           mRange;
    RangeDeque      mRangeList;
    RangeDequeCIter mIter;
    // Secondary index collection
    IndexArray      mIndexArray;
    size_t          mIndexArraySize, mAccessorListSize;
}; // struct ParticleAtlas::Iterator


////////////////////////////////////////

// Internal operators and implementation details


namespace particle_atlas_internal {


template<typename ParticleArrayT>
struct ComputeExtremas {
    typedef typename ParticleArrayT::PosType    PosType;
    typedef typename PosType::value_type        ScalarType;

    ComputeExtremas(const ParticleArrayT& particles)
        : particleArray(&particles)
        , minRadius(std::numeric_limits<ScalarType>::max())
        , maxRadius(-std::numeric_limits<ScalarType>::max())
    {
    }

    ComputeExtremas(ComputeExtremas& rhs, tbb::split)
        : particleArray(rhs.particleArray)
        , minRadius(std::numeric_limits<ScalarType>::max())
        , maxRadius(-std::numeric_limits<ScalarType>::max())
    {
    }

    void operator()(const tbb::blocked_range<size_t>& range) {

        ScalarType radius, tmpMin = minRadius, tmpMax = maxRadius;

        for (size_t n = range.begin(), N = range.end(); n != N; ++n) {
            particleArray->getRadius(n, radius);
            tmpMin = std::min(radius, tmpMin);
            tmpMax = std::max(radius, tmpMax);
        }

        minRadius = std::min(minRadius, tmpMin);
        maxRadius = std::max(maxRadius, tmpMax);
    }

    void join(const ComputeExtremas& rhs) {
        minRadius = std::min(minRadius, rhs.minRadius);
        maxRadius = std::max(maxRadius, rhs.maxRadius);
    }

    ParticleArrayT const * const particleArray;
    ScalarType minRadius, maxRadius;
}; // struct ComputeExtremas


template<typename ParticleArrayT, typename PointIndex>
struct SplittableParticleArray
{
    typedef boost::shared_ptr<SplittableParticleArray>          Ptr;
    typedef boost::shared_ptr<const SplittableParticleArray>    ConstPtr;
    typedef ParticleArrayT                                      ParticleArray;

    typedef typename ParticleArray::PosType                     PosType;
    typedef typename PosType::value_type                        ScalarType;

    SplittableParticleArray(const ParticleArrayT& particles)
        : mIndexMap(), mParticleArray(&particles), mSize(particles.size())
    {
        updateExtremas();
    }

    SplittableParticleArray(const ParticleArrayT& particles, double minR, double maxR)
        : mIndexMap(), mParticleArray(&particles), mSize(particles.size())
    {
        mMinRadius = ScalarType(minR);
        mMaxRadius = ScalarType(maxR);
    }

    const ParticleArrayT& particleArray() const { return *mParticleArray; }

    size_t size() const { return mSize; }

    void getPos(size_t n, PosType& xyz) const { return mParticleArray->getPos(getGlobalIndex(n), xyz); }
    void getRadius(size_t n, ScalarType& radius) const { return mParticleArray->getRadius(getGlobalIndex(n), radius); }

    ScalarType minRadius() const { return mMinRadius; }
    ScalarType maxRadius() const { return mMaxRadius; }

    size_t getGlobalIndex(size_t n) const { return mIndexMap ? size_t(mIndexMap[n]) : n; }

    /// Move all particle indices that have a radius larger or equal to @a maxRadiusLimit
    /// into a separate container.
    Ptr split(ScalarType maxRadiusLimit) {

        if (mMaxRadius < maxRadiusLimit) return Ptr();

        boost::scoped_array<bool> mask(new bool[mSize]);

        tbb::parallel_for(tbb::blocked_range<size_t>(0, mSize),
            MaskParticles(*this, mask, maxRadiusLimit));

        Ptr output(new SplittableParticleArray(*this, mask));
        if (output->size() == 0) return Ptr();

        size_t newSize = 0;
        for (size_t n = 0, N = mSize; n < N; ++n) {
            newSize += size_t(!mask[n]);
        }

        boost::scoped_array<PointIndex> newIndexMap(new PointIndex[newSize]);

        setIndexMap(newIndexMap, mask, false);

        mSize = newSize;
        mIndexMap.swap(newIndexMap);
        updateExtremas();

        return output;
    }


private:
    // Disallow copying
    SplittableParticleArray(const SplittableParticleArray&);
    SplittableParticleArray& operator=(const SplittableParticleArray&);

    // Masked copy constructor
    SplittableParticleArray(const SplittableParticleArray& other, const boost::scoped_array<bool>& mask)
        : mIndexMap(), mParticleArray(&other.particleArray()), mSize(0)
    {
        for (size_t n = 0, N = other.size(); n < N; ++n) {
            mSize += size_t(mask[n]);
        }

        if (mSize != 0) {
            mIndexMap.reset(new PointIndex[mSize]);
            other.setIndexMap(mIndexMap, mask, true);
        }

        updateExtremas();
    }

    struct MaskParticles {
        MaskParticles(const SplittableParticleArray& particles,
            const boost::scoped_array<bool>& mask, ScalarType radius)
            : particleArray(&particles)
            , particleMask(mask.get())
            , radiusLimit(radius)
        {
        }

        void operator()(const tbb::blocked_range<size_t>& range) const {
            const ScalarType maxRadius = radiusLimit;
            ScalarType radius;
            for (size_t n = range.begin(), N = range.end(); n != N; ++n) {
                particleArray->getRadius(n, radius);
                particleMask[n] = !(radius < maxRadius);
            }
        }

        SplittableParticleArray const * const particleArray;
        bool                          * const particleMask;
        ScalarType                      const radiusLimit;
    }; // struct MaskParticles

    inline void updateExtremas() {
        ComputeExtremas<SplittableParticleArray> op(*this);
        tbb::parallel_reduce(tbb::blocked_range<size_t>(0, mSize), op);
        mMinRadius = op.minRadius;
        mMaxRadius = op.maxRadius;
    }

    void setIndexMap(boost::scoped_array<PointIndex>& newIndexMap,
        const boost::scoped_array<bool>& mask, bool maskValue) const
    {
        if (mIndexMap.get() != NULL) {
                const PointIndex* indices = mIndexMap.get();
            for (size_t idx = 0, n = 0, N = mSize; n < N; ++n) {
                if (mask[n] == maskValue) newIndexMap[idx++] = indices[n];
            }
        } else {
            for (size_t idx = 0, n = 0, N = mSize; n < N; ++n) {
                if (mask[n] == maskValue) newIndexMap[idx++] = PointIndex(n);
            }
        }
    }


    //////////

    boost::scoped_array<PointIndex> mIndexMap;
    ParticleArrayT const * const    mParticleArray;
    size_t                          mSize;
    ScalarType                      mMinRadius, mMaxRadius;
}; // struct SplittableParticleArray


template<typename ParticleArrayType, typename PointIndexLeafNodeType>
struct RemapIndices {

    RemapIndices(const ParticleArrayType& particles, std::vector<PointIndexLeafNodeType*> nodes)
        : mParticles(&particles)
        , mNodes(nodes.empty() ? NULL : &nodes.front())
    {
    }

    void operator()(const tbb::blocked_range<size_t>& range) const {
        typedef typename PointIndexLeafNodeType::ValueType PointIndexType;
        for (size_t n = range.begin(), N = range.end(); n != N; ++n) {

            PointIndexLeafNodeType& node = *mNodes[n];
            const size_t numIndices = node.indices().size();

            if (numIndices > 0) {
                PointIndexType* begin = &node.indices().front();
                const PointIndexType* end = begin + numIndices;

                while (begin < end) {
                    *begin = PointIndexType(mParticles->getGlobalIndex(*begin));
                    ++begin;
                }
            }
        }
    }

    ParticleArrayType         const * const mParticles;
    PointIndexLeafNodeType  * const * const mNodes;
}; // struct RemapIndices


template<typename ParticleArrayType, typename IndexT>
struct RadialRangeFilter
{
    typedef typename ParticleArrayType::PosType             PosType;
    typedef typename PosType::value_type                    ScalarType;

    typedef std::pair<const IndexT*, const IndexT*>         Range;
    typedef std::deque<Range>                               RangeDeque;
    typedef std::deque<IndexT>                              IndexDeque;

    RadialRangeFilter(RangeDeque& ranges, IndexDeque& indices, const PosType& xyz,
        ScalarType radius, const ParticleArrayType& particles, bool hasUniformRadius = false)
        : mRanges(ranges)
        , mIndices(indices)
        , mCenter(xyz)
        , mRadius(radius)
        , mParticles(&particles)
        , mHasUniformRadius(hasUniformRadius)
    {
        if (mHasUniformRadius) {
            ScalarType uniformRadius;
            mParticles->getRadius(0, uniformRadius);
            mRadius = mRadius + uniformRadius;
            mRadius *= mRadius;
        }
    }

    template <typename LeafNodeType>
    void filterLeafNode(const LeafNodeType& leaf)
    {
        const size_t numIndices = leaf.indices().size();
        if (numIndices > 0) {
            const IndexT* begin = &leaf.indices().front();
            filterVoxel(leaf.origin(), begin, begin + numIndices);
        }
    }

    void filterVoxel(const Coord&, const IndexT* begin, const IndexT* end)
    {
        PosType pos;

        if (mHasUniformRadius) {

            const ScalarType searchRadiusSqr = mRadius;

            while (begin < end) {
                mParticles->getPos(size_t(*begin), pos);
                const ScalarType distSqr = (mCenter - pos).lengthSqr();
                if (distSqr < searchRadiusSqr) {
                    mIndices.push_back(*begin);
                }
                ++begin;
            }
        } else {
            while (begin < end) {
                const size_t idx = size_t(*begin);
                mParticles->getPos(idx, pos);

                ScalarType radius;
                mParticles->getRadius(idx, radius);

                ScalarType searchRadiusSqr = mRadius + radius;
                searchRadiusSqr *= searchRadiusSqr;

                const ScalarType distSqr = (mCenter - pos).lengthSqr();

                if (distSqr < searchRadiusSqr) {
                    mIndices.push_back(*begin);
                }

                ++begin;
            }
        }
    }

private:
    RadialRangeFilter(const RadialRangeFilter&);
    RadialRangeFilter& operator=(const RadialRangeFilter&);

    RangeDeque&                     mRanges;
    IndexDeque&                     mIndices;
    PosType                   const mCenter;
    ScalarType                      mRadius;
    ParticleArrayType const * const mParticles;
    bool                      const mHasUniformRadius;
}; // struct RadialRangeFilter


template<typename ParticleArrayType, typename IndexT>
struct BBoxFilter
{
    typedef typename ParticleArrayType::PosType     PosType;
    typedef typename PosType::value_type            ScalarType;

    typedef std::pair<const IndexT*, const IndexT*> Range;
    typedef std::deque<Range>                       RangeDeque;
    typedef std::deque<IndexT>                      IndexDeque;

    BBoxFilter(RangeDeque& ranges, IndexDeque& indices,
        const BBoxd& bbox, const ParticleArrayType& particles, bool hasUniformRadius = false)
        : mRanges(ranges)
        , mIndices(indices)
        , mBBox(PosType(bbox.min()), PosType(bbox.max()))
        , mCenter(mBBox.getCenter())
        , mParticles(&particles)
        , mHasUniformRadius(hasUniformRadius)
        , mUniformRadiusSqr(ScalarType(0.0))
    {
        if (mHasUniformRadius) {
            mParticles->getRadius(0, mUniformRadiusSqr);
            mUniformRadiusSqr *= mUniformRadiusSqr;
        }
    }

    template <typename LeafNodeType>
    void filterLeafNode(const LeafNodeType& leaf)
    {
        const size_t numIndices = leaf.indices().size();
        if (numIndices > 0) {
            const IndexT* begin = &leaf.indices().front();
            filterVoxel(leaf.origin(), begin, begin + numIndices);
        }
    }

    void filterVoxel(const Coord&, const IndexT* begin, const IndexT* end)
    {
        PosType pos;

        if (mHasUniformRadius) {
            const ScalarType radiusSqr = mUniformRadiusSqr;

            while (begin < end) {

                mParticles->getPos(size_t(*begin), pos);
                if (mBBox.isInside(pos)) {
                    mIndices.push_back(*begin++);
                    continue;
                }

                const ScalarType distSqr = pointToBBoxDistSqr(pos);
                if (!(distSqr > radiusSqr)) {
                    mIndices.push_back(*begin);
                }

                ++begin;
            }

        } else {
            while (begin < end) {

                const size_t idx = size_t(*begin);
                mParticles->getPos(idx, pos);
                if (mBBox.isInside(pos)) {
                    mIndices.push_back(*begin++);
                    continue;
                }

                ScalarType radius;
                mParticles->getRadius(idx, radius);
                const ScalarType distSqr = pointToBBoxDistSqr(pos);
                if (!(distSqr > (radius * radius))) {
                    mIndices.push_back(*begin);
                }

                ++begin;
            }
        }
    }

private:
    BBoxFilter(const BBoxFilter&);
    BBoxFilter& operator=(const BBoxFilter&);

    ScalarType pointToBBoxDistSqr(const PosType& pos) const
    {
        ScalarType distSqr = ScalarType(0.0);

        for (int i = 0; i < 3; ++i) {

            const ScalarType a = pos[i];

            ScalarType b = mBBox.min()[i];
            if (a < b) {
                ScalarType delta = b - a;
                distSqr += delta * delta;
            }

            b = mBBox.max()[i];
            if (a > b) {
                ScalarType delta = a - b;
                distSqr += delta * delta;
            }
        }

        return distSqr;
    }

    RangeDeque&                     mRanges;
    IndexDeque&                     mIndices;
    math::BBox<PosType>       const mBBox;
    PosType                   const mCenter;
    ParticleArrayType const * const mParticles;
    bool                      const mHasUniformRadius;
    ScalarType                      mUniformRadiusSqr;
}; // struct BBoxFilter


} // namespace particle_atlas_internal


////////////////////////////////////////


template<typename PointIndexGridType>
template<typename ParticleArrayType>
inline void
ParticleAtlas<PointIndexGridType>::construct(
    const ParticleArrayType& particles, double minVoxelSize, size_t maxLevels)
{
    typedef typename particle_atlas_internal::
        SplittableParticleArray<ParticleArrayType, IndexType>   SplittableParticleArray;
    typedef typename SplittableParticleArray::Ptr               SplittableParticleArrayPtr;
    typedef typename ParticleArrayType::ScalarType              ScalarType;

    /////

    particle_atlas_internal::ComputeExtremas<ParticleArrayType> extremas(particles);
    tbb::parallel_reduce(tbb::blocked_range<size_t>(0, particles.size()), extremas);
    const double firstMin = extremas.minRadius;
    const double firstMax = extremas.maxRadius;
    const double firstVoxelSize = std::max(minVoxelSize, firstMin);

    if (!(firstMax < (firstVoxelSize * double(2.0))) && maxLevels > 1) {

        std::vector<SplittableParticleArrayPtr> levels;
        levels.push_back(SplittableParticleArrayPtr(
                new SplittableParticleArray(particles, firstMin, firstMax)));

        std::vector<double> voxelSizeArray;
        voxelSizeArray.push_back(firstVoxelSize);

        for (size_t n = 0; n < maxLevels; ++n) {

            const double maxParticleRadius = double(levels.back()->maxRadius());
            const double particleRadiusLimit = voxelSizeArray.back() * double(2.0);
            if (maxParticleRadius < particleRadiusLimit) break;

            SplittableParticleArrayPtr newLevel = levels.back()->split(ScalarType(particleRadiusLimit));
            if (!newLevel) break;

            levels.push_back(newLevel);
            voxelSizeArray.push_back(double(newLevel->minRadius()));
        }

        size_t numPoints = 0;

        typedef typename PointIndexGridType::TreeType       PointIndexTreeType;
        typedef typename PointIndexTreeType::LeafNodeType   PointIndexLeafNodeType;

        std::vector<PointIndexLeafNodeType*> nodes;

        for (size_t n = 0, N = levels.size(); n < N; ++n) {

            const SplittableParticleArray& particleArray = *levels[n];

            numPoints += particleArray.size();

            mMinRadiusArray.push_back(double(particleArray.minRadius()));
            mMaxRadiusArray.push_back(double(particleArray.maxRadius()));

            PointIndexGridPtr grid = createPointIndexGrid<PointIndexGridType>(particleArray, voxelSizeArray[n]);

            nodes.clear();
            grid->tree().getNodes(nodes);

            tbb::parallel_for(tbb::blocked_range<size_t>(0, nodes.size()),
                particle_atlas_internal::RemapIndices<SplittableParticleArray, PointIndexLeafNodeType>
                (particleArray, nodes));

            mIndexGridArray.push_back(grid);
        }

    } else {
        mMinRadiusArray.push_back(firstMin);
        mMaxRadiusArray.push_back(firstMax);
        mIndexGridArray.push_back(
            createPointIndexGrid<PointIndexGridType>(particles, firstVoxelSize));
    }
}


template<typename PointIndexGridType>
template<typename ParticleArrayType>
inline typename ParticleAtlas<PointIndexGridType>::Ptr
ParticleAtlas<PointIndexGridType>::create(
    const ParticleArrayType& particles, double minVoxelSize, size_t maxLevels)
{
    Ptr ret(new ParticleAtlas());
    ret->construct(particles, minVoxelSize, maxLevels);
    return ret;
}


////////////////////////////////////////

// ParticleAtlas::Iterator implementation

template<typename PointIndexGridType>
inline
ParticleAtlas<PointIndexGridType>::Iterator::Iterator(const ParticleAtlas& atlas)
    : mAtlas(&atlas)
    , mAccessorList()
    , mRange(static_cast<IndexType*>(NULL), static_cast<IndexType*>(NULL))
    , mRangeList()
    , mIter(mRangeList.begin())
    , mIndexArray()
    , mIndexArraySize(0)
    , mAccessorListSize(atlas.levels())
{
    if (mAccessorListSize > 0) {
        mAccessorList.reset(new ConstAccessorPtr[mAccessorListSize]);
        for (size_t n = 0, N = mAccessorListSize; n < N; ++n) {
            mAccessorList[n].reset(new ConstAccessor(atlas.pointIndexGrid(n).tree()));
        }
    }
}


template<typename PointIndexGridType>
inline void
ParticleAtlas<PointIndexGridType>::Iterator::reset()
{
    mIter = mRangeList.begin();
    if (!mRangeList.empty()) {
        mRange = mRangeList.front();
    } else if (mIndexArray) {
        mRange.first = mIndexArray.get();
        mRange.second = mRange.first + mIndexArraySize;
    } else {
        mRange.first = static_cast<IndexType*>(NULL);
        mRange.second = static_cast<IndexType*>(NULL);
    }
}


template<typename PointIndexGridType>
inline void
ParticleAtlas<PointIndexGridType>::Iterator::increment()
{
    ++mRange.first;
    if (mRange.first >= mRange.second && mIter != mRangeList.end()) {
        ++mIter;
        if (mIter != mRangeList.end()) {
            mRange = *mIter;
        } else if (mIndexArray) {
            mRange.first = mIndexArray.get();
            mRange.second = mRange.first + mIndexArraySize;
        }
    }
}


template<typename PointIndexGridType>
inline bool
ParticleAtlas<PointIndexGridType>::Iterator::next()
{
    if (!this->test()) return false;
    this->increment();
    return this->test();
}


template<typename PointIndexGridType>
inline size_t
ParticleAtlas<PointIndexGridType>::Iterator::size() const
{
    size_t count = 0;
    typename RangeDeque::const_iterator it =
        mRangeList.begin(), end = mRangeList.end();

    for ( ; it != end; ++it) {
        count += it->second - it->first;
    }

    return count + mIndexArraySize;
}


template<typename PointIndexGridType>
inline void
ParticleAtlas<PointIndexGridType>::Iterator::clear()
{
    mRange.first = static_cast<IndexType*>(NULL);
    mRange.second = static_cast<IndexType*>(NULL);
    mRangeList.clear();
    mIter = mRangeList.end();
    mIndexArray.reset();
    mIndexArraySize = 0;
}


template<typename PointIndexGridType>
inline void
ParticleAtlas<PointIndexGridType>::Iterator::updateFromLevel(size_t level)
{
    typedef typename PointIndexGridType::TreeType   TreeType;
    typedef typename TreeType::LeafNodeType         LeafNodeType;

    this->clear();

    if (mAccessorListSize > 0) {
        const size_t levelIdx = std::min(mAccessorListSize - 1, level);

        const TreeType& tree = mAtlas->pointIndexGrid(levelIdx).tree();


        std::vector<const LeafNodeType*> nodes;
        tree.getNodes(nodes);

        for (size_t n = 0, N = nodes.size(); n < N; ++n) {

            const LeafNodeType& node = *nodes[n];
            const size_t numIndices = node.indices().size();

            if (numIndices > 0) {
                const IndexType* begin = &node.indices().front();
                mRangeList.push_back(Range(begin, (begin + numIndices)));
            }
        }
    }

    this->reset();
}


template<typename PointIndexGridType>
template<typename ParticleArrayType>
inline void
ParticleAtlas<PointIndexGridType>::Iterator::worldSpaceSearchAndUpdate(
    const Vec3d& center, double radius, const ParticleArrayType& particles)
{
    typedef typename ParticleArrayType::PosType     PosType;
    typedef typename ParticleArrayType::ScalarType  ScalarType;

    /////

    this->clear();

    std::deque<IndexType> filteredIndices;
    std::vector<CoordBBox> searchRegions;

    const double iRadius = radius * double(1.0 / std::sqrt(3.0));

    const Vec3d ibMin(center[0] - iRadius, center[1] - iRadius, center[2] - iRadius);
    const Vec3d ibMax(center[0] + iRadius, center[1] + iRadius, center[2] + iRadius);

    const Vec3d bMin(center[0] - radius, center[1] - radius, center[2] - radius);
    const Vec3d bMax(center[0] + radius, center[1] + radius, center[2] + radius);

    const PosType pos = PosType(center);
    const ScalarType dist = ScalarType(radius);

    for (size_t n = 0, N = mAccessorListSize; n < N; ++n) {

        const double maxRadius = mAtlas->maxRadius(n);
        const bool uniformRadius = math::isApproxEqual(mAtlas->minRadius(n), maxRadius);

        const openvdb::math::Transform& xform = mAtlas->pointIndexGrid(n).transform();

        ConstAccessor& acc = *mAccessorList[n];

        openvdb::CoordBBox inscribedRegion(
            xform.worldToIndexCellCentered(ibMin),
            xform.worldToIndexCellCentered(ibMax));

        inscribedRegion.expand(-1); // erode by one voxel

        // collect indices that don't need to be tested
        point_index_grid_internal::pointIndexSearch(mRangeList, acc, inscribedRegion);

        searchRegions.clear();

        const openvdb::CoordBBox region(
            xform.worldToIndexCellCentered(bMin - maxRadius),
            xform.worldToIndexCellCentered(bMax + maxRadius));

        inscribedRegion.expand(1);
        point_index_grid_internal::constructExclusiveRegions(searchRegions, region, inscribedRegion);

        typedef particle_atlas_internal::RadialRangeFilter<ParticleArrayType, IndexType> FilterType;
        FilterType filter(mRangeList, filteredIndices, pos, dist, particles, uniformRadius);

        for (size_t i = 0, I = searchRegions.size(); i < I; ++i) {
            point_index_grid_internal::filteredPointIndexSearch(filter, acc, searchRegions[i]);
        }
    }

    point_index_grid_internal::dequeToArray(filteredIndices, mIndexArray, mIndexArraySize);

    this->reset();
}


template<typename PointIndexGridType>
template<typename ParticleArrayType>
inline void
ParticleAtlas<PointIndexGridType>::Iterator::worldSpaceSearchAndUpdate(
    const BBoxd& bbox, const ParticleArrayType& particles)
{
    typedef typename ParticleArrayType::PosType     PosType;
    typedef typename ParticleArrayType::ScalarType  ScalarType;

    /////

    this->clear();

    std::deque<IndexType> filteredIndices;
    std::vector<CoordBBox> searchRegions;

    for (size_t n = 0, N = mAccessorListSize; n < N; ++n) {

        const double maxRadius = mAtlas->maxRadius(n);
        const bool uniformRadius = math::isApproxEqual(mAtlas->minRadius(n), maxRadius);
        const openvdb::math::Transform& xform = mAtlas->pointIndexGrid(n).transform();

        ConstAccessor& acc = *mAccessorList[n];

        openvdb::CoordBBox inscribedRegion(
            xform.worldToIndexCellCentered(bbox.min()),
            xform.worldToIndexCellCentered(bbox.max()));

        inscribedRegion.expand(-1); // erode by one voxel

        // collect indices that don't need to be tested
        point_index_grid_internal::pointIndexSearch(mRangeList, acc, inscribedRegion);

        searchRegions.clear();

        const openvdb::CoordBBox region(
            xform.worldToIndexCellCentered(bbox.min() - maxRadius),
            xform.worldToIndexCellCentered(bbox.max() + maxRadius));

        inscribedRegion.expand(1);
        point_index_grid_internal::constructExclusiveRegions(searchRegions, region, inscribedRegion);

        typedef particle_atlas_internal::BBoxFilter<ParticleArrayType, IndexType> FilterType;
        FilterType filter(mRangeList, filteredIndices, bbox, particles, uniformRadius);

        for (size_t i = 0, I = searchRegions.size(); i < I; ++i) {
            point_index_grid_internal::filteredPointIndexSearch(filter, acc, searchRegions[i]);
        }
    }

    point_index_grid_internal::dequeToArray(filteredIndices, mIndexArray, mIndexArraySize);

    this->reset();
}


} // namespace tools
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb

#endif // OPENVDB_TOOLS_PARTICLE_ATLAS_HAS_BEEN_INCLUDED

// Copyright (c) 2012-2016 DreamWorks Animation LLC
// All rights reserved. This software is distributed under the
// Mozilla Public License 2.0 ( http://www.mozilla.org/MPL/2.0/ )