FOctree.hpp 59.1 KB
Newer Older
1
// ===================================================================================
2
// Copyright ScalFmm 2011 INRIA, Olivier Coulaud, Berenger Bramas, Matthias Messner
3 4 5 6
// olivier.coulaud@inria.fr, berenger.bramas@inria.fr
// This software is a computer program whose purpose is to compute the FMM.
//
// This software is governed by the CeCILL-C and LGPL licenses and
7 8
// abiding by the rules of distribution of free software.
//
9 10 11 12
// This program 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 and CeCILL-C Licenses for more details.
13
// "http://www.cecill.info".
14
// "http://www.gnu.org/licenses".
15
// ===================================================================================
16 17
#ifndef FOCTREE_HPP
#define FOCTREE_HPP
18

19
#include <functional>
20 21

#include "FSubOctree.hpp"
22
#include "FTreeCoordinate.hpp"
BRAMAS Berenger's avatar
BRAMAS Berenger committed
23
#include "FBlockAllocator.hpp"
24

BRAMAS Berenger's avatar
BRAMAS Berenger committed
25
#include "../Utils/FLog.hpp"
26
#include "../Utils/FGlobal.hpp"
27
#include "../Utils/FGlobalPeriodic.hpp"
BRAMAS Berenger's avatar
BRAMAS Berenger committed
28
#include "../Utils/FPoint.hpp"
29
#include "../Utils/FMath.hpp"
30
#include "../Utils/FNoCopyable.hpp"
BRAMAS Berenger's avatar
BRAMAS Berenger committed
31
#include "../Utils/FAssert.hpp"
32
#include "FCoordinateComputer.hpp"
33

34 35 36 37 38 39 40 41
/**
 * @author Berenger Bramas (berenger.bramas@inria.fr)
 * @class FOctree
 * Please read the license
 *
 * This class is an octree container.
 *
 * Please refere to testOctree.cpp to see an example.
42
 * @code
43
 * // can be used as : <br>
44
 * FOctree<TestParticle, TestCell> tree(1.0,FPoint<FReal>(0.5,0.5,0.5));
45
 * @endcode
46 47 48
 *
 * Particles and cells has to respect the Abstract class definition.
 * Particle must extend {FExtendPosition}
49
 * Cell must extend extend proposes accessors to FTreeCoordinate and MortonIndex.
50 51 52
 *
 * If the octree as an height H, then it goes from 0 to H-1
 * at level 0 the space is not split
BRAMAS Berenger's avatar
BRAMAS Berenger committed
53
 * CellAllocator can be FListBlockAllocator<CellClass, 10> or FBasicBlockAllocator<CellClass>
54
 */
55
template<class FReal, class CellClass, class ContainerClass, class LeafClass, class CellAllocatorClass = FBasicBlockAllocator<CellClass> /*FListBlockAllocator<CellClass, 15>*/ >
BRAMAS Berenger's avatar
BRAMAS Berenger committed
56
class FOctree : public FNoCopyable {
57 58 59
    typedef FOctree<FReal, CellClass , ContainerClass, LeafClass, CellAllocatorClass>      OctreeType;
    typedef  FSubOctreeWithLeafs<FReal, CellClass , ContainerClass, LeafClass, CellAllocatorClass> SubOctreeWithLeaves;
    typedef FSubOctree<FReal, CellClass , ContainerClass, LeafClass, CellAllocatorClass>           SubOctree;
BRAMAS Berenger's avatar
BRAMAS Berenger committed
60

61
    FAbstractSubOctree<FReal, CellClass , ContainerClass, LeafClass, CellAllocatorClass>* root;   //< root suboctree
BRAMAS Berenger's avatar
BRAMAS Berenger committed
62 63 64 65 66 67 68

    FReal*const boxWidthAtLevel;	//< to store the width of each boxs at all levels

    const int height;                   //< tree height
    const int subHeight;		//< tree height
    const int leafIndex;		//< index of leaf int array

69 70
    const FPoint<FReal> boxCenter;	//< the space system center
    const FPoint<FReal> boxCorner;	//< the space system corner (used to compute morton index)
BRAMAS Berenger's avatar
BRAMAS Berenger committed
71 72 73 74 75 76 77 78 79

    const FReal boxWidth;       //< the space system width


    /**
     * Get morton index from a position for the leaf leavel
     * @param inPosition position to compute
     * @return the morton index
     */
80
    FTreeCoordinate getCoordinateFromPosition(const FPoint<FReal>& inPosition) const {
81
        return FCoordinateComputer::GetCoordinateFromPositionAndCorner<FReal>(this->boxCorner, this->boxWidth, height, inPosition);
BRAMAS Berenger's avatar
BRAMAS Berenger committed
82 83 84 85 86 87 88 89 90
    }

    /**
     * Get the box number from a position
     * at a position POS with a leaf level box width of WI, the position is RELATIVE_TO_CORNER(POS)/WI
     * @param inRelativePosition a position from the corner of the box
     * @return the box num at the leaf level that contains inRelativePosition
     */
    int getTreeCoordinate(const FReal inRelativePosition) const {
91
        return FCoordinateComputer::GetTreeCoordinate<FReal>(inRelativePosition, this->boxWidth, this->boxWidthAtLevel[this->leafIndex], height);
BRAMAS Berenger's avatar
BRAMAS Berenger committed
92
    }
93 94

public:
BRAMAS Berenger's avatar
BRAMAS Berenger committed
95 96 97 98 99 100 101 102
    /**
     * Constructor
     * @param inHeight the octree height
     * @param inSubHeight the octree subheight
     * @param inBoxWidth box width for this simulation
     * @param inBoxCenter box center for this simulation
     */
    FOctree(const int inHeight, const int inSubHeight,
103
            const FReal inBoxWidth, const FPoint<FReal>& inBoxCenter)
104
        : root(nullptr), boxWidthAtLevel(new FReal[inHeight]),
BRAMAS Berenger's avatar
BRAMAS Berenger committed
105 106 107 108 109 110
          height(inHeight) , subHeight(inSubHeight), leafIndex(this->height-1),
          boxCenter(inBoxCenter), boxCorner(inBoxCenter,-(inBoxWidth/2)), boxWidth(inBoxWidth)
    {
        FAssertLF(subHeight <= height - 1, "Subheight cannot be greater than height", __LINE__, __FILE__ );
        // Does we only need one suboctree?
        if(subHeight == height - 1){
111
            root = new FSubOctreeWithLeafs< FReal, CellClass , ContainerClass, LeafClass,CellAllocatorClass>(nullptr, 0, this->subHeight, 1);
BRAMAS Berenger's avatar
BRAMAS Berenger committed
112 113
        }
        else {// if(subHeight < height - 1)
114
            root = new FSubOctree< FReal, CellClass , ContainerClass, LeafClass,CellAllocatorClass>(nullptr, 0, this->subHeight, 1);
BRAMAS Berenger's avatar
BRAMAS Berenger committed
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
        }

        FReal tempWidth = this->boxWidth;
        // pre compute box width for each level
        for(int indexLevel = 0; indexLevel < this->height; ++indexLevel ){
            this->boxWidthAtLevel[indexLevel] = tempWidth;
            tempWidth /= FReal(2.0);
        }
    }

    /** Desctructor */
    virtual ~FOctree() {
        delete [] boxWidthAtLevel;
        delete root;
    }

    /** To get the tree height */
    int getHeight() const {
        return this->height;
    }

    /** To get the tree subheight */
    int getSubHeight() const{
        return this->subHeight;
    }

    /** To get the box width */
    FReal getBoxWidth() const{
        return this->boxWidth;
    }

    /** To get the center of the box */
147
    const FPoint<FReal>& getBoxCenter() const{
BRAMAS Berenger's avatar
BRAMAS Berenger committed
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
        return this->boxCenter;
    }

    /** Count the number of cells per level,
     * it will iter on the tree to do that!
     */
    void getNbCellsPerLevel(int inNbCells[]){
        Iterator octreeIterator(this);
        octreeIterator.gotoBottomLeft();

        Iterator avoidGoLeft(octreeIterator);

        for(int idxLevel = height - 1 ; idxLevel > 0; --idxLevel ){
            int counter = 0;
            do{
                ++counter;
            } while(octreeIterator.moveRight());
            avoidGoLeft.moveUp();
            octreeIterator = avoidGoLeft;
            inNbCells[idxLevel] = counter;
        }

        inNbCells[0] = 0;
    }

    /**
     * Insert a particle on the tree
     * algorithm is :
     * Compute morton index for the particle
     * ask node to insert this particle
     * @param inParticle the particle to insert (must inherite from FAbstractParticle)
     */
    template<typename... Args>
181
    void insert(const FPoint<FReal>& inParticlePosition, Args... args){
BRAMAS Berenger's avatar
BRAMAS Berenger committed
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
        const FTreeCoordinate host = getCoordinateFromPosition( inParticlePosition );
        const MortonIndex particleIndex = host.getMortonIndex(leafIndex);
        if(root->isLeafPart()){
            ((SubOctreeWithLeaves*)root)->insert( particleIndex, host, this->height, inParticlePosition, args... );
        }
        else{
            ((SubOctree*)root)->insert( particleIndex, host, this->height, inParticlePosition, args... );
        }
    }

    /** Remove a leaf from its morton index
     * @param indexToRemove the index of the leaf to remove
     */
    LeafClass* createLeaf(const MortonIndex indexToCreate ){
        const FTreeCoordinate host(indexToCreate,this->height-1);
        if(root->isLeafPart()){
            return ((SubOctreeWithLeaves*)root)->createLeaf( indexToCreate, host, this->height );
        }
        else{
            return ((SubOctree*)root)->createLeaf( indexToCreate, host, this->height );
        }
    }

    /** Remove a leaf from its morton index
     * @param indexToRemove the index of the leaf to remove
     */
    void removeLeaf(const MortonIndex indexToRemove ){
        root->removeLeaf( indexToRemove , this->height);
    }

    /**
     * Get a morton index from a real position
     * @param position a position to compute MI
     * @return the morton index
     */
217
    MortonIndex getMortonFromPosition(const FPoint<FReal>& position) const {
BRAMAS Berenger's avatar
BRAMAS Berenger committed
218 219 220
        return getCoordinateFromPosition(position).getMortonIndex(leafIndex);
    }

221 222 223 224 225 226 227
    /*
     * Indicate if tree is empty or not.
     */
    bool isEmpty(){
        return root->getRightLeafIndex() < 0;
    }

BRAMAS Berenger's avatar
BRAMAS Berenger committed
228 229 230 231 232 233 234
    /**
     * The class works on suboctree. Most of the resources needed
     * are avaiblable by using FAbstractSubOctree. But when accessing
     * to the leaf we have to use FSubOctree or FSubOctreeWithLeafs
     * depending if we are working on the bottom of the tree.
     */
    union SubOctreeTypes {
235 236 237
        FAbstractSubOctree<FReal,CellClass,ContainerClass,LeafClass,CellAllocatorClass>* tree;     //< Usual pointer to work
        FSubOctree<FReal,CellClass,ContainerClass,LeafClass,CellAllocatorClass>* middleTree;       //< To access to sub-octree under
        FSubOctreeWithLeafs<FReal,CellClass,ContainerClass,LeafClass,CellAllocatorClass>* leafTree;//< To access to particles lists
BRAMAS Berenger's avatar
BRAMAS Berenger committed
238 239 240 241 242 243
    };

    /**
     * This class is a const SubOctreeTypes
     */
    union SubOctreeTypesConst {
244 245 246
        const FAbstractSubOctree<FReal,CellClass,ContainerClass,LeafClass,CellAllocatorClass>* tree;     //< Usual pointer to work
        const FSubOctree<FReal,CellClass,ContainerClass,LeafClass,CellAllocatorClass>* middleTree;       //< To access to sub-octree under
        const FSubOctreeWithLeafs<FReal,CellClass,ContainerClass,LeafClass,CellAllocatorClass>* leafTree;//< To access to particles lists
BRAMAS Berenger's avatar
BRAMAS Berenger committed
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
    };

    /**
     * This has to be used to iterate on an octree
     * It simply stores an pointer on a suboctree and moves to right/left/up/down.
     * Please refere to testOctreeIter file to see how it works.
     *
     * @code
     * FOctree<TestParticle, TestCell, NbLevels, NbSubLevels>::Iterator octreeIterator(&tree); <br>
     * octreeIterator.gotoBottomLeft(); <br>
     * for(int idx = 0 ; idx < NbLevels - 1; ++idx ){ <br>
     *     do{ <br>
     *         // ...  <br>
     *     } while(octreeIterator.moveRight()); <br>
     *     octreeIterator.moveUp(); <br>
     *     octreeIterator.gotoLeft(); <br>
     * } <br>
     * @endcode
     * Remark :
     * It uses the left right limit on each suboctree and their morton index.
     * Please have a look to the move functions to understand how the system is working.
     */
    class Iterator  {
        SubOctreeTypes current; //< Current suboctree

        int currentLocalIndex;  //< Current index (array position) in the current_suboctree.cells[ currentLocalLevel ]
        int currentLocalLevel;  //< Current level in the current suboctree

        /**
         * To know what is the left limit on the current level on the current subtree
         * @return suboctree.left_limit >> 3 * diff(leaf_index, current_index).
         */
        static int TransposeIndex(const int indexInLeafLevel, const int distanceFromLeafLevel) {
            return indexInLeafLevel >> (3 * distanceFromLeafLevel);
        }


    public:
        /**
         * Constructor
         * @param inTarget the octree to iterate on
         * After building a iterator, this one is positioned at the level 0
         * of the root (level 1 of octree) at the left limit index
         */
        explicit Iterator(FOctree* const inTarget)
            : currentLocalIndex(0) , currentLocalLevel(0) {
            FAssertLF(inTarget, "Target for Octree::Iterator cannot be null", __LINE__, __FILE__);
            FAssertLF(inTarget->root->getRightLeafIndex() >= 0, "Octree seems to be empty, getRightLeafIndex == 0", __LINE__, __FILE__);

            // Start by the root
            this->current.tree = inTarget->root;
            // On the left limit
            this->currentLocalIndex = TransposeIndex(this->current.tree->getLeftLeafIndex(), (this->current.tree->getSubOctreeHeight() - this->currentLocalLevel - 1) );
        }

        Iterator() : currentLocalIndex(0),currentLocalLevel(0) {
303
            current.tree = nullptr;
BRAMAS Berenger's avatar
BRAMAS Berenger committed
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
        }

        /** Copy constructor
         * @param other source iterator to copy
         */
        Iterator(const Iterator& other){
            this->current = other.current ;
            this->currentLocalLevel = other.currentLocalLevel ;
            this->currentLocalIndex = other.currentLocalIndex ;
        }

        /** Copy operator
         * @param other source iterator to copy
         * @return this after copy
         */
        Iterator& operator=(const Iterator& other){
            this->current = other.current ;
            this->currentLocalLevel = other.currentLocalLevel ;
            this->currentLocalIndex = other.currentLocalIndex ;
            return *this;
        }

        /**
         * Move iterator to the top! (level 0 of root suboctree, level 1 of octree)
         * after this function : index = left limit at root level
         * the Algorithm is :
         *     going to root suboctree
         *     going to the first level and most left node
         */
        void gotoTop(){
            while(this->current.tree->hasParent()){
                this->current.tree = this->current.tree->getParent();
            }
            this->currentLocalLevel = 0;
            this->currentLocalIndex = TransposeIndex(this->current.tree->getLeftLeafIndex(), (this->current.tree->getSubOctreeHeight() - 1) );
        }

        /**
         * Move iterator to the bottom left place
         * We are on a leaf a the most left node
         * the Algorithm is :
         *     first go to top
         *     then stay on the left and go downward
         */
        void gotoBottomLeft(){
            gotoTop();
            while(1) {
                this->currentLocalLevel = this->current.tree->getSubOctreeHeight() - 1;
                this->currentLocalIndex = this->current.tree->getLeftLeafIndex();
                if( isAtLeafLevel() ){
                    return;
                }
                this->current.tree = this->current.middleTree->leafs( this->currentLocalIndex );
            }
        }

        /**
         * Move iterator to the left place at the same level
         * if needed we go on another suboctree but we stay on at the same level
         * the Algorithm is :
         *     go to top
         *     go downard until we are a the same level
         */
        void gotoLeft(){
            //  Function variables
            const int currentLevel = level();

            // Goto root sutoctree
            while( this->current.tree->hasParent() ){
                this->current.tree = this->current.tree->getParent();
            }

            // Go down on the left until arriving on the same global level
            while( this->current.tree->getSubOctreeHeight() + this->current.tree->getSubOctreePosition() - 1 < currentLevel ) {
                this->current.tree = this->current.middleTree->leafs(this->current.tree->getLeftLeafIndex());
            }

            // Level still unchanged we only go to the left
            // The left limit on this tree at the level we want to stay
            this->currentLocalIndex = TransposeIndex(this->current.tree->getLeftLeafIndex(), (this->current.tree->getSubOctreeHeight() - this->currentLocalLevel - 1));
        }

        /**
         * Move iterator to the right place at the same level
         * if needed we go on another suboctree but we stay on at the same level
         * the Algorithm is :
         *     go to top
         *     go downard until we are a the same level
         */
        void gotoRight(){
            //  Function variables
            const int currentLevel = level();
            // Goto root sutoctree
            while( this->current.tree->hasParent() ){
                this->current.tree = this->current.tree->getParent();
            }
            // Go down on the left until arriving on the same global level
            while( this->current.tree->getSubOctreeHeight() + this->current.tree->getSubOctreePosition() - 1 < currentLevel ) {
                this->current.tree = this->current.middleTree->leafs(this->current.tree->getRightLeafIndex());
            }
            // Level still unchanged we only go to the left
            // The left limit on this tree at the level we want to stay
            this->currentLocalIndex = TransposeIndex(this->current.tree->getRightLeafIndex(), (this->current.tree->getSubOctreeHeight() - this->currentLocalLevel - 1));
        }

        /**
         * Goto the next value on the right at the same level
         *
         * The algorithm here is :
         * As long as we are on the right limit, go to the parent suboctree
         * if we are on the root and on the right then return (there is no more data on the right)
         *
         * After that point we do not know where we are but we know that there is some data
         * on the right (without knowing our position!)
         *
         * We gotoNext on the brother to find an allocated cell (->)
         * for example if we are on index 2 we will look until 8 = 2 | 7 + 1
         * if we arrive a 8 without finding a cell we go upper and do the same
         * we know we will find something because we are not at the right limit
         *
         * We find an allocated cell.
         * We have to go down, we go on the left child of this cells
         * until : the current level if we did not have change the current suboctree
         * or : the leaf level
         *
         * In the second case, it meanse we need to change octree downward
         * but it is easy because we can use the left limit!
         *
         * @return true if we succeed to go to the right, else false
         */
        bool moveRight(){
            //  Function variables
            SubOctreeTypes workingTree = this->current;    // To cover parent other sub octre
            int workingLevel = this->currentLocalLevel;        // To know where we are
            int workingIndex = this->currentLocalIndex;        // To know where we are

            // -- First we have to go in a tree where we can move on the right --
            // Number of time we go into parent subtree
            int countUpward = 0;
            // We stop when we can right move or if there is no more parent (root)
            while( workingIndex == TransposeIndex(workingTree.tree->getRightLeafIndex(), (workingTree.tree->getSubOctreeHeight() - workingLevel - 1) )
                   && workingTree.tree->hasParent() ){
                // Goto the leaf level into parent at current_tree.position_into_parent_array
                workingIndex        = workingTree.tree->getIndexInParent();
                workingTree.tree    = workingTree.tree->getParent();
                workingLevel        = workingTree.tree->getSubOctreeHeight() - 1;
                // inc counter
                ++countUpward;
            }

            // Do we stop because we are on the root (means we cannot move right?)
            if( workingIndex < TransposeIndex(workingTree.tree->getRightLeafIndex(), (workingTree.tree->getSubOctreeHeight() - workingLevel - 1) ) ){
                // Move to the first right cell pointer(!)
                ++workingIndex;

                // Maybe it is null, but we know there is almost one cell on the right
                // we need to find it
                if( !workingTree.tree->cellsAt(workingLevel)[workingIndex] ){
                    // While we are not on a allocated cell
                    while( true ){
                        // Test element on the right (test brothers)
                        const int rightLimite = (workingIndex | 7) + 1;
                        while( workingIndex < rightLimite && !workingTree.tree->cellsAt(workingLevel)[workingIndex]){
                            ++workingIndex;
                        }
                        // Stop if we are on an allocated cell
                        if( workingTree.tree->cellsAt(workingLevel)[workingIndex] ){
                            break;
                        }
                        // Else go to the upper level
                        --workingLevel;
                        workingIndex >>= 3;
                    }
                }

                // if wokring tree != current tree => working tree leafs level ; else current level
                const int objectiveLevel = (countUpward ? workingTree.tree->getSubOctreeHeight() - 1 : this->currentLocalLevel );

                // We need to go down as left as possible
                while( workingLevel != objectiveLevel ){
                    ++workingLevel;
                    workingIndex <<= 3;
                    const int rightLimite = (workingIndex | 7); // not + 1 because if the 7th first are null it must be the 8th!
                    while( workingIndex < rightLimite && !workingTree.tree->cellsAt(workingLevel)[workingIndex]){
                        ++workingIndex;
                    }
                }

                // Do we change from the current sub octree?
                if( countUpward ){
                    // Then we simply need to go down the same number of time
                    workingTree.tree = workingTree.middleTree->leafs(workingIndex);
                    while( --countUpward ){
                        workingTree.tree = workingTree.middleTree->leafs(workingTree.tree->getLeftLeafIndex());
                    }
                    // level did not change, simpli set octree and get left limit of this octree at the current level
                    this->current = workingTree;
                    this->currentLocalIndex = TransposeIndex(workingTree.tree->getLeftLeafIndex(), (workingTree.tree->getSubOctreeHeight() - this->currentLocalLevel - 1) );
                }
                else{
                    // We are on the right tree
                    this->currentLocalIndex = workingIndex;
                }

                return true;
            }
            return false;
        }

        /**
         * Move to the upper level
         * It may cause to change the suboctree we are working on
         * but we are using the same morton index >> 3
         * @return true if succeed
         */
        bool moveUp() {
            // It is on the top level?
            if( this->currentLocalLevel ){
                // No so simply go up
                --this->currentLocalLevel;
                this->currentLocalIndex >>= 3;
            }
            // Yes need to change suboctree
            else if( this->current.tree->hasParent() ){
                this->currentLocalIndex = this->current.tree->getIndexInParent();
                this->current.tree = this->current.tree->getParent();
                this->currentLocalLevel =  this->current.tree->getSubOctreeHeight() - 1;
            }
            else{
                return false;
            }
            return true;
        }

        /**
         * Move down
         * It may cause to change the suboctree we are working on
         * We point on the first child found from left to right in the above
         * level
         * @return true if succeed
         */
        bool moveDown(){
            if( !isAtLeafLevel() ){
                // We are on the leaf of the current suboctree?
                if(this->currentLocalLevel + 1 == this->current.tree->getSubOctreeHeight()){
                    // Yes change sub octree
                    this->current.tree = this->current.middleTree->leafs(this->currentLocalIndex);
                    this->currentLocalIndex = 0;
                    this->currentLocalLevel = 0;
                }
                // No simply go down
                else{
                    ++this->currentLocalLevel;
                    this->currentLocalIndex <<= 3;
                }
                // Find the first allocated cell from left to right
                while(!this->current.tree->cellsAt(this->currentLocalLevel)[this->currentLocalIndex]){
                    ++this->currentLocalIndex;
                }
                return true;
            }
            return false;
        }

        /**
         * To know if we are not on the root level
         * @return true if we can move up
         */
        bool canProgressToUp() const {
            return this->currentLocalLevel || this->current.tree->hasParent();
        }

        /**
         * To know if we are not on the leafs level
         * @return true if we can move down
         */
        bool canProgressToDown() const {
            return !isAtLeafLevel();
        }

        /**
         * To know if we are on the leafs level
         * @return true if we are at the bottom of the tree
         */
        bool isAtLeafLevel() const {
            return this->current.tree->isLeafPart() && this->currentLocalLevel + 1 == this->current.tree->getSubOctreeHeight();
        }

        /**
         * To know the current level (not local but global)
         * @return the level in the entire octree
         */
        int level() const {
            return this->currentLocalLevel + this->current.tree->getSubOctreePosition();
        }

        /** Get the current pointed leaf
         * @return current leaf element
         */
        LeafClass* getCurrentLeaf() const {
            return this->current.leafTree->getLeaf(this->currentLocalIndex);
        }

        /** To access the current particles list
         * You have to be at the leaf level to call this function!
         * @return current element list
         */
        ContainerClass* getCurrentListSrc() const {
            return this->current.leafTree->getLeafSrc(this->currentLocalIndex);
        }

        /** To access the current particles list
         * You have to be at the leaf level to call this function!
         * @return current element list
         */
        ContainerClass* getCurrentListTargets() const {
            return this->current.leafTree->getLeafTargets(this->currentLocalIndex);
        }

        /** Get the current pointed cell
         * @return current cell element
         */
        CellClass* getCurrentCell() const {
            return this->current.tree->cellsAt(this->currentLocalLevel)[this->currentLocalIndex];
        }

630 631 632 633 634 635
        /** Gets the children of the current cell.
         *
         * This function return an array of 8 CellClass. To konw whether
         * a child cell exists or not, the pointer must be checked.
         *
         * @return the 8-child array.
BRAMAS Berenger's avatar
BRAMAS Berenger committed
636 637 638 639 640 641
         */
        CellClass** getCurrentChild() const {
            // are we at the bottom of the suboctree
            if(this->current.tree->getSubOctreeHeight() - 1 == this->currentLocalLevel ){
                // then return first level of the suboctree under
                return &this->current.middleTree->leafs(this->currentLocalIndex)->cellsAt(0)[0];
642
            } else {
BRAMAS Berenger's avatar
BRAMAS Berenger committed
643 644 645 646 647
                // else simply return the array at the right position
                return &this->current.tree->cellsAt(this->currentLocalLevel + 1)[this->currentLocalIndex << 3];
            }
        }

648 649 650 651 652 653 654 655 656 657 658
        /** Gets the children of the current cell.
         *
         * This function return an array of 8 CellClass. To konw whether
         * a child cell exists or not, the pointer must be checked.
         *
         * @return the 8-child array.
         */
        CellClass** getCurrentChildren() const {
            return getCurrentChild();
        }

BRAMAS Berenger's avatar
BRAMAS Berenger committed
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
        /** Get the part of array that contains all the pointers
         *
         */
        CellClass** getCurrentBox() const {
            return &this->current.tree->cellsAt(this->currentLocalLevel)[this->currentLocalIndex & ~7];
        }

        /** Get the Morton index of the current cell pointed by the iterator
         * @return The global morton index
         * <code>iter.getCurrentGlobalIndex();<br>
         * // is equivalent to :<br>
         * iter.getCurrentCell()->getMortonIndex();</code>
         */
        MortonIndex getCurrentGlobalIndex() const{
            return this->current.tree->cellsAt(this->currentLocalLevel)[this->currentLocalIndex]->getMortonIndex();
        }

        /** To get the tree coordinate of the current working cell
         *
         */
        const FTreeCoordinate& getCurrentGlobalCoordinate() const{
            return this->current.tree->cellsAt(this->currentLocalLevel)[this->currentLocalIndex]->getCoordinate();
        }

    };

    // To be able to access octree root & data
    friend class Iterator;

    ///////////////////////////////////////////////////////////////////////////
    // This part is related to the FMM algorithm (needed by M2M,M2L,etc.)
    ///////////////////////////////////////////////////////////////////////////

    /** This function return a cell (if it exists) from a morton index and a level
     * @param inIndex the index of the desired cell
     * @param inLevel the level of the desired cell (cannot be infered from the index)
     * @return the cell if it exist or null (0)
     * This function starts from the root until it find a missing cell or the right cell
     */
    CellClass* getCell(const MortonIndex inIndex, const int inLevel) const{
        SubOctreeTypesConst workingTree;
700
        workingTree.tree = this->root;
BRAMAS Berenger's avatar
BRAMAS Berenger committed
701 702 703 704 705 706 707 708
        const MortonIndex treeSubLeafMask = ~(~0x00LL << (3 *  workingTree.tree->getSubOctreeHeight() ));

        // Find the suboctree a the correct level
        while(inLevel >= workingTree.tree->getSubOctreeHeight() + workingTree.tree->getSubOctreePosition()) {
            // compute the leaf index
            const MortonIndex fullIndex = inIndex >> (3 * (inLevel + 1 - (workingTree.tree->getSubOctreeHeight() + workingTree.tree->getSubOctreePosition()) ) );
            // point to next suboctree
            workingTree.tree = workingTree.middleTree->leafs(treeSubLeafMask & fullIndex);
709
            if(!workingTree.tree) return nullptr;
BRAMAS Berenger's avatar
BRAMAS Berenger committed
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
        }

        // compute correct index in the array
        const MortonIndex treeLeafMask = ~(~0x00LL << (3 *  (inLevel + 1 - workingTree.tree->getSubOctreePosition()) ));
        return workingTree.tree->cellsAt(inLevel - workingTree.tree->getSubOctreePosition())[treeLeafMask & inIndex];
    }


    /** This function fill a array with the neighbors of a cell
     * it does not put the brothers in the array (brothers are cells
     * at the same level with the same parent) because they are of course
     * direct neighbors.
     * There is a maximum of 26 (3*3*3-1) direct neighbors
     *  // Take the neighbors != brothers
     *  CellClass* directNeighbors[26];
     *  const int nbDirectNeighbors = getNeighborsNoBrothers(directNeighbors,inIndex,inLevel);
     * @param inNeighbors the array to store the elements
     * @param inIndex the index of the element we want the neighbors
     * @param inLevel the level of the element
     * @return the number of neighbors
     */
    int getNeighborsNoBrothers(CellClass* inNeighbors[26], const MortonIndex inIndex, const int inLevel) const {
        FTreeCoordinate center;
        center.setPositionFromMorton(inIndex, inLevel);

        const int boxLimite = FMath::pow2(inLevel);

        int idxNeighbors = 0;

        // We test all cells around
        for(int idxX = -1 ; idxX <= 1 ; ++idxX){
            if(!FMath::Between(center.getX() + idxX,0,boxLimite)) continue;

            for(int idxY = -1 ; idxY <= 1 ; ++idxY){
                if(!FMath::Between(center.getY() + idxY,0,boxLimite)) continue;

                for(int idxZ = -1 ; idxZ <= 1 ; ++idxZ){
                    if(!FMath::Between(center.getZ() + idxZ,0,boxLimite)) continue;

                    // if we are not on the current cell
                    if( !(!idxX && !idxY && !idxZ) ){
                        const FTreeCoordinate other(center.getX() + idxX,center.getY() + idxY,center.getZ() + idxZ);
                        const MortonIndex mortonOther = other.getMortonIndex(inLevel);
                        // if not a brother
                        if( mortonOther>>3 != inIndex>>3 ){
                            // get cell
                            CellClass* const cell = getCell(mortonOther, inLevel);
                            // add to list if not null
                            if(cell) inNeighbors[idxNeighbors++] = cell;
                        }
                    }
                }
            }
        }

        return idxNeighbors;
    }


    /** This function return an adresse of cell array from a morton index and a level
     *
     * @param inIndex the index of the desired cell array has to contains
     * @param inLevel the level of the desired cell (cannot be infered from the index)
     * @return the cell if it exist or null (0)
     *
     */
    CellClass** getCellPt(const MortonIndex inIndex, const int inLevel) const{
        SubOctreeTypesConst workingTree;
        workingTree.tree = this->root;

        const MortonIndex treeMiddleMask = ~(~0x00LL << (3 *  workingTree.tree->getSubOctreeHeight() ));

        // Find the suboctree a the correct level
        while(inLevel >= workingTree.tree->getSubOctreeHeight() + workingTree.tree->getSubOctreePosition()) {
            // compute the leaf index
            const MortonIndex fullIndex = inIndex >> 3 * (inLevel + 1 - (workingTree.tree->getSubOctreeHeight() + workingTree.tree->getSubOctreePosition()) );
            // point to next suboctree
            workingTree.tree = workingTree.middleTree->leafs(int(treeMiddleMask & fullIndex));
788
            if(!workingTree.tree) return nullptr;
BRAMAS Berenger's avatar
BRAMAS Berenger committed
789 790 791 792 793
        }

        // Be sure there is a parent allocated
        const int levelInTree = inLevel - workingTree.tree->getSubOctreePosition();
        if( levelInTree && !workingTree.tree->cellsAt(levelInTree - 1)[~(~0x00LL << (3 * levelInTree )) & (inIndex>>3)]){
794
            return nullptr;
BRAMAS Berenger's avatar
BRAMAS Berenger committed
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
        }

        // compute correct index in the array and return the @ in array
        const MortonIndex treeLeafMask = ~(~0x00LL << (3 * (levelInTree + 1 ) ));
        return &workingTree.tree->cellsAt(levelInTree)[treeLeafMask & inIndex];
    }


    /** This function fill an array with the distant neighbors of a cell
     * @param inNeighbors the array to store the elements
     * @param inNeighborsIndex the array to store morton index of the neighbors
     * @param inIndex the index of the element we want the neighbors
     * @param inLevel the level of the element
     * @return the number of neighbors
     */
    int getInteractionNeighbors(const CellClass* inNeighbors[343],
811 812
                const FTreeCoordinate& workingCell,
                const int inLevel, const int neighSeparation = 1) const{
BRAMAS Berenger's avatar
BRAMAS Berenger committed
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
        // reset
        memset(inNeighbors, 0, sizeof(CellClass*) * 343);

        // Then take each child of the parent's neighbors if not in directNeighbors
        // Father coordinate
        const FTreeCoordinate parentCell(workingCell.getX()>>1,workingCell.getY()>>1,workingCell.getZ()>>1);

        // Limite at parent level number of box (split by 2 by level)
        const int boxLimite = FMath::pow2(inLevel-1);

        int idxNeighbors = 0;
        // We test all cells around
        for(int idxX = -1 ; idxX <= 1 ; ++idxX){
            if(!FMath::Between(parentCell.getX() + idxX,0,boxLimite)) continue;

            for(int idxY = -1 ; idxY <= 1 ; ++idxY){
                if(!FMath::Between(parentCell.getY() + idxY,0,boxLimite)) continue;

                for(int idxZ = -1 ; idxZ <= 1 ; ++idxZ){
                    if(!FMath::Between(parentCell.getZ() + idxZ,0,boxLimite)) continue;

                    // if we are not on the current cell
                    if( idxX || idxY || idxZ ){
                        const FTreeCoordinate otherParent(parentCell.getX() + idxX,parentCell.getY() + idxY,parentCell.getZ() + idxZ);
                        const MortonIndex mortonOtherParent = otherParent.getMortonIndex(inLevel-1) << 3;
                        // Get child
                        CellClass** const cells = getCellPt(mortonOtherParent, inLevel);

                        // If there is one or more child
                        if(cells){
                            // For each child
                            for(int idxCousin = 0 ; idxCousin < 8 ; ++idxCousin){
                                if(cells[idxCousin]){
                                    const int xdiff  = ((otherParent.getX()<<1) | ( (idxCousin>>2) & 1)) - workingCell.getX();
                                    const int ydiff  = ((otherParent.getY()<<1) | ( (idxCousin>>1) & 1)) - workingCell.getY();
                                    const int zdiff  = ((otherParent.getZ()<<1) | (idxCousin&1)) - workingCell.getZ();

                                    // Test if it is a direct neighbor
851
                                    if(FMath::Abs(xdiff) > neighSeparation || FMath::Abs(ydiff) > neighSeparation || FMath::Abs(zdiff) > neighSeparation){
BRAMAS Berenger's avatar
BRAMAS Berenger committed
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
                                        // add to neighbors
                                        inNeighbors[ (((xdiff+3) * 7) + (ydiff+3)) * 7 + zdiff + 3] = cells[idxCousin];
                                        ++idxNeighbors;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        return idxNeighbors;
    }

867 868 869 870 871 872 873 874 875 876 877
    /** This function fills an array with all the neighbors of a cell, 
     * i.e. childs of parent's neighbors, direct neighbors and cell itself.
     * This is called for instance when the nearfield also needs to be approximated
     * in that cas we only call this function at the leaf level.
     * @param inNeighbors the array to store the elements
     * @param inNeighborsIndex the array to store morton index of the neighbors
     * @param inIndex the index of the element we want the neighbors
     * @param inLevel the level of the element
     * @return the number of neighbors
     */
    int getFullNeighborhood(const CellClass* inNeighbors[343],
878 879
                const FTreeCoordinate& workingCell,
                const int inLevel) const{
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
        // reset
        memset(inNeighbors, 0, sizeof(CellClass*) * 343);

        // Then take each child of the parent's neighbors
        // Father coordinate
        const FTreeCoordinate parentCell(workingCell.getX()>>1,workingCell.getY()>>1,workingCell.getZ()>>1);

        // Limite at parent level number of box (split by 2 by level)
        const int boxLimite = FMath::pow2(inLevel-1);

        int idxNeighbors = 0;
        // We test all cells around
        for(int idxX = -1 ; idxX <= 1 ; ++idxX){
            if(!FMath::Between(parentCell.getX() + idxX,0,boxLimite)) continue;

            for(int idxY = -1 ; idxY <= 1 ; ++idxY){
                if(!FMath::Between(parentCell.getY() + idxY,0,boxLimite)) continue;

                for(int idxZ = -1 ; idxZ <= 1 ; ++idxZ){
                    if(!FMath::Between(parentCell.getZ() + idxZ,0,boxLimite)) continue;

                    const FTreeCoordinate otherParent(parentCell.getX() + idxX,parentCell.getY() + idxY,parentCell.getZ() + idxZ);
                    const MortonIndex mortonOtherParent = otherParent.getMortonIndex(inLevel-1) << 3;
                    // Get child
                    CellClass** const cells = getCellPt(mortonOtherParent, inLevel);

                    // If there is one or more child
                    if(cells){
                        // For each child
                        for(int idxCousin = 0 ; idxCousin < 8 ; ++idxCousin){
                            if(cells[idxCousin]){
                                const int xdiff  = ((otherParent.getX()<<1) | ( (idxCousin>>2) & 1)) - workingCell.getX();
                                const int ydiff  = ((otherParent.getY()<<1) | ( (idxCousin>>1) & 1)) - workingCell.getY();
                                const int zdiff  = ((otherParent.getZ()<<1) | (idxCousin&1)) - workingCell.getZ();

                                // add to neighbors
                                inNeighbors[ (((xdiff+3) * 7) + (ydiff+3)) * 7 + zdiff + 3] = cells[idxCousin];
                                ++idxNeighbors;
                            }
                        }
                    }
                }
            }
        }

        return idxNeighbors;
    }
BRAMAS Berenger's avatar
BRAMAS Berenger committed
927 928 929 930 931 932 933 934 935 936 937

    /** This function fill an array with the distant neighbors of a cell
     * it respects the periodic condition and will give the relative distance
     * between the working cell and the neighbors
     * @param inNeighbors the array to store the elements
     * @param inRelativePosition the array to store the relative position of the neighbors
     * @param workingCell the index of the element we want the neighbors
     * @param inLevel the level of the element
     * @return the number of neighbors
     */
    int getPeriodicInteractionNeighbors(const CellClass* inNeighbors[343],
938 939
                const FTreeCoordinate& workingCell,
                const int inLevel, const int inDirection, const int neighSeparation = 1) const{
BRAMAS Berenger's avatar
BRAMAS Berenger committed
940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963

        // Then take each child of the parent's neighbors if not in directNeighbors
        // Father coordinate
        const FTreeCoordinate parentCell(workingCell.getX()>>1,workingCell.getY()>>1,workingCell.getZ()>>1);

        // Limite at parent level number of box (split by 2 by level)
        const int boxLimite = FMath::pow2(inLevel-1);

        // This is not on a border we can use normal interaction list method
        if( !(parentCell.getX() == 0 || parentCell.getY() == 0 || parentCell.getZ() == 0 ||
              parentCell.getX() == boxLimite - 1 || parentCell.getY() == boxLimite - 1 || parentCell.getZ() == boxLimite - 1 ) ) {
            return getInteractionNeighbors( inNeighbors, workingCell, inLevel);
        }
        else{
            // reset

            memset(inNeighbors, 0, sizeof(CellClass*) * 343);

            const int startX =  (TestPeriodicCondition(inDirection, DirMinusX) || parentCell.getX() != 0 ?-1:0);
            const int endX =    (TestPeriodicCondition(inDirection, DirPlusX)  || parentCell.getX() != boxLimite - 1 ?1:0);
            const int startY =  (TestPeriodicCondition(inDirection, DirMinusY) || parentCell.getY() != 0 ?-1:0);
            const int endY =    (TestPeriodicCondition(inDirection, DirPlusY)  || parentCell.getY() != boxLimite - 1 ?1:0);
            const int startZ =  (TestPeriodicCondition(inDirection, DirMinusZ) || parentCell.getZ() != 0 ?-1:0);
            const int endZ =    (TestPeriodicCondition(inDirection, DirPlusZ)  || parentCell.getZ() != boxLimite - 1 ?1:0);
964

BRAMAS Berenger's avatar
BRAMAS Berenger committed
965 966 967 968 969 970
            int idxNeighbors = 0;
            // We test all cells around
            for(int idxX = startX ; idxX <= endX ; ++idxX){
                for(int idxY = startY ; idxY <= endY ; ++idxY){
                    for(int idxZ = startZ ; idxZ <= endZ ; ++idxZ){
                        // if we are not on the current cell
971
                        if(neighSeparation<1 || idxX || idxY || idxZ ){
BRAMAS Berenger's avatar
BRAMAS Berenger committed
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

                            const FTreeCoordinate otherParent(parentCell.getX() + idxX,parentCell.getY() + idxY,parentCell.getZ() + idxZ);
                            FTreeCoordinate otherParentInBox(otherParent);
                            // periodic
                            if( otherParentInBox.getX() < 0 ){
                                otherParentInBox.setX( otherParentInBox.getX() + boxLimite );
                            }
                            else if( boxLimite <= otherParentInBox.getX() ){
                                otherParentInBox.setX( otherParentInBox.getX() - boxLimite );
                            }

                            if( otherParentInBox.getY() < 0 ){
                                otherParentInBox.setY( otherParentInBox.getY() + boxLimite );
                            }
                            else if( boxLimite <= otherParentInBox.getY() ){
                                otherParentInBox.setY( otherParentInBox.getY() - boxLimite );
                            }

                            if( otherParentInBox.getZ() < 0 ){
                                otherParentInBox.setZ( otherParentInBox.getZ() + boxLimite );
                            }
                            else if( boxLimite <= otherParentInBox.getZ() ){
                                otherParentInBox.setZ( otherParentInBox.getZ() - boxLimite );
                            }


                            const MortonIndex mortonOtherParent = otherParentInBox.getMortonIndex(inLevel-1) << 3;
                            // Get child
                            CellClass** const cells = getCellPt(mortonOtherParent, inLevel);
1001
                            // TODO : REMOVE NEXT COMMENTS
BRAMAS Berenger's avatar
BRAMAS Berenger committed
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
                            //							std::cout << "     idx,idy,idz "<< idxX << " "<<  idxY  << " "<<   idxZ
                            //									  <<"  mortonOtherParent"<<  mortonOtherParent<< std::endl;

                            // If there is one or more child
                            if(cells){
                                // For each child
                                for(int idxCousin = 0 ; idxCousin < 8 ; ++idxCousin){
                                    if(cells[idxCousin]){
                                        const int xdiff  = ((otherParent.getX()<<1) | ( (idxCousin>>2) & 1)) - workingCell.getX();
                                        const int ydiff  = ((otherParent.getY()<<1) | ( (idxCousin>>1) & 1)) - workingCell.getY();
                                        const int zdiff  = ((otherParent.getZ()<<1) | (idxCousin&1))         - workingCell.getZ();

                                        // Test if it is a direct neighbor
1015
                                        if(FMath::Abs(xdiff) > neighSeparation || FMath::Abs(ydiff) > neighSeparation || FMath::Abs(zdiff) > neighSeparation){
BRAMAS Berenger's avatar
BRAMAS Berenger committed
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
                                            // add to neighbors
                                            inNeighbors[ (((xdiff+3) * 7) + (ydiff+3)) * 7 + zdiff + 3] = cells[idxCousin];
                                            ++idxNeighbors;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            //			std::cout << " End   in getPeriodicInteractionNeighbors"<<std::endl;

            return idxNeighbors;
        }
    }


    /** This function return a cell (if it exists) from a morton index and a level
     * @param inIndex the index of the desired cell
     * @param inLevel the level of the desired cell (cannot be infered from the index)
     * @return the cell if it exist or null (0)
     *
     */
    ContainerClass* getLeafSrc(const MortonIndex inIndex){
        SubOctreeTypes workingTree;
        workingTree.tree = this->root;
        const MortonIndex treeSubLeafMask = ~(~0x00LL << (3 *  workingTree.tree->getSubOctreeHeight() ));

        // Find the suboctree a the correct level
        while(leafIndex >= workingTree.tree->getSubOctreeHeight() + workingTree.tree->getSubOctreePosition()) {
            // compute the leaf index
            const MortonIndex fullIndex = inIndex >> (3 * (leafIndex + 1  - (workingTree.tree->getSubOctreeHeight() + workingTree.tree->getSubOctreePosition()) ) );
            // point to next suboctree
            workingTree.tree = workingTree.middleTree->leafs(int(treeSubLeafMask & fullIndex));
1051
            if(!workingTree.tree) return nullptr;
BRAMAS Berenger's avatar
BRAMAS Berenger committed
1052 1053 1054 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 1096 1097 1098
        }

        // compute correct index in the array
        const MortonIndex treeLeafMask = ~(~0x00LL << (3 *  (leafIndex + 1 - workingTree.tree->getSubOctreePosition()) ));
        return workingTree.leafTree->getLeafSrc(int(treeLeafMask & inIndex));
    }

    /** This function fill an array with the neighbors of a cell
     * @param inNeighbors the array to store the elements
     * @param inIndex the index of the element we want the neighbors
     * @param inLevel the level of the element
     * @return the number of neighbors
     */
    int getLeafsNeighbors(ContainerClass* inNeighbors[27], const FTreeCoordinate& center, const int inLevel){
        memset( inNeighbors, 0 , 27 * sizeof(ContainerClass*));
        const int boxLimite = FMath::pow2(inLevel);

        int idxNeighbors = 0;

        // We test all cells around
        for(int idxX = -1 ; idxX <= 1 ; ++idxX){
            if(!FMath::Between(center.getX() + idxX,0,boxLimite)) continue;

            for(int idxY = -1 ; idxY <= 1 ; ++idxY){
                if(!FMath::Between(center.getY() + idxY,0,boxLimite)) continue;

                for(int idxZ = -1 ; idxZ <= 1 ; ++idxZ){
                    if(!FMath::Between(center.getZ() + idxZ,0,boxLimite)) continue;

                    // if we are not on the current cell
                    if( idxX || idxY || idxZ ){
                        const FTreeCoordinate other(center.getX() + idxX,center.getY() + idxY,center.getZ() + idxZ);
                        const MortonIndex mortonOther = other.getMortonIndex(inLevel);
                        // get cell
                        ContainerClass* const leaf = getLeafSrc(mortonOther);
                        // add to list if not null
                        if(leaf){
                            inNeighbors[(((idxX + 1) * 3) + (idxY +1)) * 3 + idxZ + 1] = leaf;
                            ++idxNeighbors;
                        }
                    }
                }
            }
        }

        return idxNeighbors;
    }
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
    /** This function fill an array with the neighbors of a cell
     * @param inNeighbors the array to store the elements
     * @param inIndex the index of the element we want the neighbors
     * @param inLevel the level of the element
     * @return the number of neighbors
     */
    int getLeafsNeighbors(const CellClass*  inNeighbors[27], const FTreeCoordinate& center, const int inLevel){
        memset( inNeighbors, 0 , 27 * sizeof(CellClass*));
        const int boxLimite = FMath::pow2(inLevel);

        int idxNeighbors = 0;

        // We test all cells around
        for(int idxX = -1 ; idxX <= 1 ; ++idxX){
            if(!FMath::Between(center.getX() + idxX,0,boxLimite)) continue;

            for(int idxY = -1 ; idxY <= 1 ; ++idxY){
                if(!FMath::Between(center.getY() + idxY,0,boxLimite)) continue;

                for(int idxZ = -1 ; idxZ <= 1 ; ++idxZ){
                    if(!FMath::Between(center.getZ() + idxZ,0,boxLimite)) continue;

                    // if we are not on the current cell
                    if( idxX || idxY || idxZ ){
                        const FTreeCoordinate other(center.getX() + idxX,center.getY() + idxY,center.getZ() + idxZ);
                        const MortonIndex mortonOther = other.getMortonIndex(inLevel);
                        // get cell
//                        ContainerClass* const leaf = getLeafSrc(mortonOther);
                        CellClass** const leaf = getCellPt(mortonOther, inLevel);

                        // add to list if not null
                        if(leaf){
                            inNeighbors[(((idxX + 1) * 3) + (idxY +1)) * 3 + idxZ + 1] = leaf;
                            ++idxNeighbors;
                        }
                    }
                }
            }
        }

        return idxNeighbors;
    }
BRAMAS Berenger's avatar
BRAMAS Berenger committed
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152


    /** This function fill an array with the neighbors of a cell
     * @param inNeighbors the array to store the elements
     * @param inIndex the index of the element we want the neighbors
     * @param inLevel the level of the element
     * @return the number of neighbors
     */
    int getPeriodicLeafsNeighbors(ContainerClass* inNeighbors[27], FTreeCoordinate outOffsets[27], bool*const isPeriodic,
    const FTreeCoordinate& center, const int inLevel, const int inDirection){

        const int boxLimite = FMath::pow2(inLevel);
1153
        // TODO : REMOVE NEXT COMMENTS
BRAMAS Berenger's avatar
BRAMAS Berenger committed
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
        //		std::cout << " Begin in getPeriodicLeafsNeighbors"<<std::endl;

        if( center.getX() != 0 && center.getY() != 0 && center.getZ() != 0 &&
                center.getX() != boxLimite - 1 && center.getY() != boxLimite - 1 && center.getZ() != boxLimite - 1 ){
            (*isPeriodic) = false;
            return getLeafsNeighbors(inNeighbors, center, inLevel);
        }

        (*isPeriodic) = true;
        memset(inNeighbors , 0 , 27 * sizeof(ContainerClass*));
        int idxNeighbors = 0;

        const int startX = (TestPeriodicCondition(inDirection, DirMinusX) || center.getX() != 0 ?-1:0);
        const int endX = (TestPeriodicCondition(inDirection, DirPlusX) || center.getX() != boxLimite - 1 ?1:0);
        const int startY = (TestPeriodicCondition(inDirection, DirMinusY) || center.getY() != 0 ?-1:0);
        const int endY = (TestPeriodicCondition(inDirection, DirPlusY) || center.getY() != boxLimite - 1 ?1:0);
        const int startZ = (TestPeriodicCondition(inDirection, DirMinusZ) || center.getZ() != 0 ?-1:0);
        const int endZ = (TestPeriodicCondition(inDirection, DirPlusZ) || center.getZ() != boxLimite - 1 ?1:0);
1172
        // TODO : REMOVE NEXT COMMENTS
BRAMAS Berenger's avatar
BRAMAS Berenger committed
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
        //		std::cout << "  -- startX " << startX << " endX "<< endX<< std::endl ;
        //		std::cout << "  -- startY " << startY << " endX "<< endY<< std::endl ;
        //		std::cout << "  -- startZ " << startZ << " endX "<< endZ<< std::endl ;
        //		std::cout << "     boxLimite "<< boxLimite<<std::endl;
        int otherX,otherY,otherZ;
        FTreeCoordinate other;

        int xoffset = 0, yoffset = 0, zoffset = 0;
        // We test all cells around
        for(int idxX = startX ; idxX <= endX ; ++idxX){
            otherX = center.getX() + idxX ; xoffset = 0 ;
            if( otherX < 0 ){
                otherX += boxLimite ;
                xoffset = -1;
            }
            else if( boxLimite <= otherX ){
                otherX -= boxLimite ;
                xoffset = 1;
            }
            other.setX(otherX);
            for(int idxY = startY ; idxY <= endY ; ++idxY){
                otherY = center.getY() + idxY ;
                yoffset = 0 ;
                if( otherY < 0 ){
                    otherY += boxLimite ;
                    yoffset = -1;
                }
                else if( boxLimite <= otherY ){
                    otherY -= boxLimite ;
                    yoffset = 1;
                }
                other.setY(otherY);
                for(int idxZ = startZ ; idxZ <= endZ ; ++idxZ){
                    zoffset = 0 ;
                    // if we are not on the current cell
                    if( idxX || idxY || idxZ ){ //  !( idxX !=0  && idxY != 0  &&idxZ != 0  )
1209
                        // TODO : REMOVE NEXT COMMENTS
BRAMAS Berenger's avatar
BRAMAS Berenger committed
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
                        //						FTreeCoordinate other(center.getX() + idxX,center.getY() + idxY,center.getZ() + idxZ);
                        otherZ = center.getZ() + idxZ ;

                        if( otherZ < 0 ){
                            otherZ += boxLimite ;
                            zoffset = -1;
                        }
                        else if( boxLimite <= otherZ ){
                            otherZ -= boxLimite ;
                            zoffset = 1;
                        }
                        other.setZ(otherZ);
1222

1223
                        // TODO : REMOVE NEXT COMMENTS
BRAMAS Berenger's avatar
BRAMAS Berenger committed
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
                        //						if( other.getX() < 0 ){
                        //							other.setX( other.getX() + boxLimite );
                        //							xoffset = -1;
                        //						}
                        //						else if( boxLimite <= other.getX() ){
                        //							other.setX( other.getX() - boxLimite );
                        //							xoffset = 1;
                        //						}
                        //						if( other.getY() < 0 ){
                        //							other.setY( other.getY() + boxLimite );
                        //							yoffset = -1;
                        //						}
                        //						else if( boxLimite <= other.getY() ){
                        //							other.setY( other.getY() - boxLimite );
                        //							yoffset = 1;
                        //						}
                        //						if( other.getZ() < 0 ){
                        //							other.setZ( other.getZ() + boxLimite );
                        //							zoffset = -1;
                        //						}
                        //						else if( boxLimite <= other.getZ() ){
                        //							other.setZ( other.getZ() - boxLimite );
                        //							zoffset = 1;
                        //						}
1248 1249


1250 1251
                        const MortonIndex mortonOther = other.getMortonIndex(inLevel);
                        // TODO : REMOVE NEXT COMMENTS
BRAMAS Berenger's avatar
BRAMAS Berenger committed
1252 1253 1254 1255 1256 1257 1258 1259 1260
                        //						std::cout << "     idx,idy,idz "<< idxX << " "<<  idxY  << " "<<   idxZ
                        //								  <<"  mortonOther  "<<  mortonOther<<  "          other "<< other<< std::endl;
                        // get cell
                        ContainerClass* const leaf = getLeafSrc(mortonOther);
                        // add to list if not null
                        if(leaf){
                            const int index = (((idxX + 1) * 3) + (idxY +1)) * 3 + idxZ + 1;
                            inNeighbors[index] = leaf;
                            outOffsets[index].setPosition(xoffset,yoffset,zoffset);
1261
                            // TODO : REMOVE NEXT COMMENTS
BRAMAS Berenger's avatar
BRAMAS Berenger committed
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
                            //							std::cout << "        xoffset,yoffset,zoffset "<< xoffset << " "<<  yoffset  << " "<<   zoffset <<" mortonOther " << mortonOther << std::endl<< std::endl;

                            ++idxNeighbors;
                        }  // if(leaf)
                    } // if( idxX || idxY || idxZ )
                }
            }
        }
        // TODO : REMOVE NEXT COMMENTS
        //		std::cout << " End   in getPeriodicLeafsNeighbors " <<std::endl;

        return idxNeighbors;
    }



    /////////////////////////////////////////////////////////
    // Lambda function to apply to all member
    /////////////////////////////////////////////////////////

    /**
     * @brief forEachLeaf iterate on the leaf and apply the function
     * @param function
     */
    void forEachLeaf(std::function<void(LeafClass*)> function){
        Iterator octreeIterator(this);
        octreeIterator.gotoBottomLeft();

        do{
            function(octreeIterator.getCurrentLeaf());
        } while(octreeIterator.moveRight());
    }

    /**
     * @brief forEachLeaf iterate on the cell and apply the function
     * @param function
     */
    void forEachCell(std::function<void(CellClass*)> function){
        Iterator octreeIterator(this);
        octreeIterator.gotoBottomLeft();

        Iterator avoidGoLeft(octreeIterator);

        for(int idx = this->height-1 ; idx >= 1 ; --idx ){
            do{
                function(octreeIterator.getCurrentCell());
            } while(octreeIterator.moveRight());
            avoidGoLeft.moveUp();
            octreeIterator = avoidGoLeft;
        }
    }

    /**
     * @brief forEachLeaf iterate on the cell and apply the function
     * @param function
     */
    void forEachCellWithLevel(std::function<void(CellClass*,const int)> function){
        Iterator octreeIterator(this);
        octreeIterator.gotoBottomLeft();

        Iterator avoidGoLeft(octreeIterator);

        for(int idx = this->height-1 ; idx >= 1 ; --idx ){
            do{
                function(octreeIterator.getCurrentCell(),idx);
            } while(octreeIterator.moveRight());
            avoidGoLeft.moveUp();
            octreeIterator = avoidGoLeft;
        }
    }

    /**
     * @brief forEachLeaf iterate on the cell and apply the function
     * @param function
     */
    void forEachCellLeaf(std::function<void(CellClass*,LeafClass*)> function){
        Iterator octreeIterator(this);
        octreeIterator.gotoBottomLeft();

        do{
            function(octreeIterator.getCurrentCell(),octreeIterator.getCurrentLeaf());
        } while(octreeIterator.moveRight());
    }
1345 1346 1347
};

#endif //FOCTREE_HPP
1348