void BTreeBuilder::buildUnbalanced( ByteInputStream &sortedInputStream, RecordNum nEntriesTotal, double fillFactor) { // TODO: common fcn // calculate amount of space to reserve on each leaf from fillfactor uint cbReserved = getSegment()->getUsablePageSize() - sizeof(BTreeNode); cbReserved = uint(cbReserved*(1-fillFactor)); // start with just a leaf level growTree(); BTreeBuildLevel &level = getLevel(0); level.cbReserved = cbReserved; level.nEntriesTotal = nEntriesTotal; level.processInput(sortedInputStream); // NOTE: It's important to realize that growTree() could be called inside // this loop, so it's necessary to recompute levels.size() after each // iteration. for (uint i = 0; i < levels.size(); ++i) { BTreeBuildLevel &level = getLevel(i); level.indexLastKey(true); } swapRoot(); }
void HeapPriorityQueue::enqueue(string value) { //Create new node with the value as the word. string* newWord = new string(value); /* * Insert node into tree. */ //If there's no other elements, this element becomes the root if(isEmpty()){ root = newWord; } //For all other cases: else{ //Find next empty spot and insert: elements[size() + 1] = newWord; //Swap with parent nodes as needed until tree is valid again. bubbleUp(elements[size() + 1], size() + 1, elements); } //Increment the total. total ++; //If necessary, grow the tree. if(total == length){ growTree(elements); } }
//Função recurssiva que constroi árvore e cria novas threads, de forma a calcular o resultado void * NewSpawnTree (void * l) { leaf L = (leaf) l; // Faz casting //Confere se pode e/ou nescessita crescimento da árvore if( ( L->posVet < L->T->sizeVetCalories) && ( L->prevSum < L->T->idealDist ) && ( L->T->FLAG == TRUE ) ) { growTree(L); // Aloca novas posições int flag = 0; //Inicio seção crítica pthread_mutex_lock(&L->T->numThreadsLock); // Tranca mutex if(L->T->numThreads < L->T->maxNumThreads) { L->T->numThreads ++; flag = 1; } pthread_mutex_unlock(&L->T->numThreadsLock); // Libera mutex if(flag)// Confere possibilidade de criar nova thread { pthread_t NAO; (void) pthread_create(&NAO, NULL, NewSpawnTree, (void *) L->nao); (*NewSpawnTree)((void *) L->sim); // Utilizando o ponteiro da função HAHA pthread_join(NAO, NULL); } else // Caso Nova thread não possa ser criada, faz de maneira funcional mesmo { NewSpawnTree(L->sim); NewSpawnTree(L->nao); } //Seção crítica pthread_mutex_lock(&L->T->numThreadsLock); // Tranca Mutex L->T->numThreads -= (1+flag); pthread_mutex_unlock(&L->T->numThreadsLock); // Libera Mutex } else if( L->prevSum == L->T->idealDist ) // Confere se resultado já foi encontrado { //Seção crítica pthread_mutex_lock(&L->T->flagLock);// Tranca Mutex L->T->FLAG = 0; pthread_mutex_unlock(&L->T->flagLock); // Libera Mutex } return 0; }
//void AssociationTree::solve(std::vector<std::pair<unsigned int, unsigned int> > & _pairs, std::vector<unsigned int> & _unassoc) void AssociationTree::solve(std::vector<std::pair<unsigned int, unsigned int> > & _pairs, std::vector<bool> & _associated_mask) { std::list<AssociationNode*>::iterator best_node; bool rootReached = false; AssociationNode *anPtr; //grows tree exploring all likely hypothesis growTree(); //computes tree probs computeTree(); //normalizes tree probs normalizeTree(); //if terminus_node_list_ is empty exit withou pairing if ( terminus_node_list_.empty() ) return; //choose best node based on best tree probability chooseBestTerminus(best_node); //resize _associated_mask and resets it to false _associated_mask.resize(nd_,false); //set pairs anPtr = *best_node; //init pointer int ii=0; while( ! anPtr->isRoot() ) //set pairs { // if ( anPtr->getTargetIndex() == nt_) //detection with void target -> unassociated detection // { // _unassoc.push_back(anPtr->getDetectionIndex()); // } // else // { // _pairs.push_back( std::pair<unsigned int, unsigned int>(anPtr->getDetectionIndex(), anPtr->getTargetIndex()) ); // } if ( anPtr->getTargetIndex() < nt_ ) //association pair { _associated_mask.at(anPtr->getDetectionIndex()) = true; _pairs.push_back( std::pair<unsigned int, unsigned int>(anPtr->getDetectionIndex(), anPtr->getTargetIndex()) ); } anPtr = anPtr->upNodePtr(); } }
// Função seta todos os parametros iniciais de uma nova árvore, incluindo os mutex e o máximo de threads tree initTree(int idealDist, int * Vet, int sizeVet, int maxNumThreads) { tree T = malloc( sizeof (*T) ); // Aloca espaço da árvore T->vetCalories = malloc(sizeVet * sizeof(int)); // Aloca Espaço das folhas da árvore //Seta parametros T->sizeVetCalories = sizeVet; T->idealDist = idealDist; T->FLAG = TRUE; T->numThreads = 0; T->maxNumThreads = maxNumThreads; //Inicializa os Mutex pthread_mutex_init(&T->flagLock, NULL); pthread_mutex_init(&T->numThreadsLock, NULL); //Seta valores do vetor de calorias int cont; for(cont=0; cont<sizeVet; cont++) { T->vetCalories[cont] = Vet[cont]; } //Aloca e seta parametros no topo da árvore T->topo = malloc(sizeof(struct node)); T->topo->prevSum = 0; T->topo->val = 0; T->topo->posVet = -1; T->topo->sim = NULL; T->topo->nao = NULL; T->topo->T = T; //Aloca 2 novas folhas (Sim e Não) para crescimento da árvore growTree(T->topo); return T; // retorna essa árvore }
ompl::base::PlannerStatus ompl::geometric::RRTConnect::solve(const base::PlannerTerminationCondition &ptc) { checkValidity(); base::GoalSampleableRegion *goal = dynamic_cast<base::GoalSampleableRegion*>(pdef_->getGoal().get()); if (!goal) { logError("Unknown type of goal (or goal undefined)"); return base::PlannerStatus::UNRECOGNIZED_GOAL_TYPE; } while (const base::State *st = pis_.nextStart()) { Motion *motion = new Motion(si_); si_->copyState(motion->state, st); motion->root = motion->state; tStart_->add(motion); } if (tStart_->size() == 0) { logError("Motion planning start tree could not be initialized!"); return base::PlannerStatus::INVALID_START; } if (!goal->couldSample()) { logError("Insufficient states in sampleable goal region"); return base::PlannerStatus::INVALID_GOAL; } if (!sampler_) sampler_ = si_->allocStateSampler(); logInform("Starting with %d states", (int)(tStart_->size() + tGoal_->size())); TreeGrowingInfo tgi; tgi.xstate = si_->allocState(); Motion *rmotion = new Motion(si_); base::State *rstate = rmotion->state; bool startTree = true; bool solved = false; while (ptc() == false) { TreeData &tree = startTree ? tStart_ : tGoal_; tgi.start = startTree; startTree = !startTree; TreeData &otherTree = startTree ? tStart_ : tGoal_; if (tGoal_->size() == 0 || pis_.getSampledGoalsCount() < tGoal_->size() / 2) { const base::State *st = tGoal_->size() == 0 ? pis_.nextGoal(ptc) : pis_.nextGoal(); if (st) { Motion* motion = new Motion(si_); si_->copyState(motion->state, st); motion->root = motion->state; tGoal_->add(motion); } if (tGoal_->size() == 0) { logError("Unable to sample any valid states for goal tree"); break; } } /* sample random state */ sampler_->sampleUniform(rstate); GrowState gs = growTree(tree, tgi, rmotion); if (gs != TRAPPED) { /* remember which motion was just added */ Motion *addedMotion = tgi.xmotion; /* attempt to connect trees */ /* if reached, it means we used rstate directly, no need top copy again */ if (gs != REACHED) si_->copyState(rstate, tgi.xstate); GrowState gsc = ADVANCED; tgi.start = startTree; while (gsc == ADVANCED) gsc = growTree(otherTree, tgi, rmotion); Motion *startMotion = startTree ? tgi.xmotion : addedMotion; Motion *goalMotion = startTree ? addedMotion : tgi.xmotion; /* if we connected the trees in a valid way (start and goal pair is valid)*/ if (gsc == REACHED && goal->isStartGoalPairValid(startMotion->root, goalMotion->root)) { // it must be the case that either the start tree or the goal tree has made some progress // so one of the parents is not NULL. We go one step 'back' to avoid having a duplicate state // on the solution path if (startMotion->parent) startMotion = startMotion->parent; else goalMotion = goalMotion->parent; connectionPoint_ = std::make_pair<base::State*, base::State*>(startMotion->state, goalMotion->state); /* construct the solution path */ Motion *solution = startMotion; std::vector<Motion*> mpath1; while (solution != NULL) { mpath1.push_back(solution); solution = solution->parent; } solution = goalMotion; std::vector<Motion*> mpath2; while (solution != NULL) { mpath2.push_back(solution); solution = solution->parent; } PathGeometric *path = new PathGeometric(si_); path->getStates().reserve(mpath1.size() + mpath2.size()); for (int i = mpath1.size() - 1 ; i >= 0 ; --i) path->append(mpath1[i]->state); for (unsigned int i = 0 ; i < mpath2.size() ; ++i) path->append(mpath2[i]->state); pdef_->addSolutionPath(base::PathPtr(path), false, 0.0); solved = true; break; } } } si_->freeState(tgi.xstate); si_->freeState(rstate); delete rmotion; logInform("Created %u states (%u start + %u goal)", tStart_->size() + tGoal_->size(), tStart_->size(), tGoal_->size()); return solved ? base::PlannerStatus::EXACT_SOLUTION : base::PlannerStatus::TIMEOUT; }
int World::loadColumn(WorldColumn &wc, int xIndex, int zIndex, const int *heightMap, bool doOutCroppings) { int worldX = xIndex * WORLD_CHUNK_SIDE; int worldZ = zIndex * WORLD_CHUNK_SIDE; wc.mWorldIndex.x = xIndex; wc.mWorldIndex.z = zIndex; wc.mWorldPosition.x = worldX; wc.mWorldPosition.z = worldZ; block_t block; block.faceVisibility = 0; block.uniqueLighting = LIGHT_LEVEL_NOT_SET; int floorBlockType = BLOCK_TYPE_DIRT; v3di_t worldPosition; worldPosition.z = worldZ; v3di_t relativePosition; for (relativePosition.z = 0; relativePosition.z < WORLD_CHUNK_SIDE; relativePosition.z++, worldPosition.z++) { worldPosition.x = worldX; for (relativePosition.x = 0; relativePosition.x < WORLD_CHUNK_SIDE; relativePosition.x++, worldPosition.x++) { // calculate the index for the heightmap: heightmap is an int[] which contains the height info // for the entire chunk 'floor'. It is apparently (WORLD_CHUNK_SIDE + 2)^2 in size. It has to be // because even the edges need to know their neighbors height to avoid gaps int terrainIndex = (relativePosition.x + 1) + ((relativePosition.z + 1) * (WORLD_CHUNK_SIDE + 2)); int terrainHeight = heightMap[terrainIndex]; if (terrainHeight > 5000 || terrainHeight < -5000) { // this isn't really necessary...just kind of a warning printf ("World::loadColumn() - whoa boy\n"); } int worldY = terrainHeight; // check neighbors to see if we need more blocks underneath int lowestNeighborHeight = 1000000; bool treePossible = true; int neighborHeight; // left int neighborIndex = terrainIndex - 1; neighborHeight = heightMap[neighborIndex]; if (neighborHeight != worldY) treePossible = false; lowestNeighborHeight = min (lowestNeighborHeight, neighborHeight); // right neighborIndex = terrainIndex + 1; neighborHeight = heightMap[neighborIndex]; if (neighborHeight != worldY) treePossible = false; lowestNeighborHeight = min (lowestNeighborHeight, neighborHeight); // backward neighborIndex = terrainIndex - (WORLD_CHUNK_SIDE + 2); neighborHeight = heightMap[neighborIndex]; if (neighborHeight != worldY) treePossible = false; lowestNeighborHeight = min (lowestNeighborHeight, neighborHeight); // forward neighborIndex = terrainIndex + (WORLD_CHUNK_SIDE + 2); neighborHeight = heightMap[neighborIndex]; if (neighborHeight != worldY) treePossible = false; lowestNeighborHeight = min (lowestNeighborHeight, neighborHeight); // now for the rest // this starts at 1 to include the ground floor int positiveNoiseHeight = 1; if (doOutCroppings) { positiveNoiseHeight += (int)floor(25.0 * mPeriodics.mRandomMap.getValueBilerp((double)worldPosition.x * 0.00321, (double)worldPosition.z * 0.00321)); } if (worldY < WATER_LEVEL) { // deal with the water // if (worldY < -20) worldY = -20; for (worldPosition.y = worldY; worldPosition.y < WATER_LEVEL; worldPosition.y++) { // this is where the actual block is figured out // this will generate the ground block and all the water above block.type = mPeriodics.generateBlockAtWorldPosition(worldPosition); if (block.type > BLOCK_TYPE_AIR) { wc.setBlockAtWorldPosition(worldPosition, block); if (gBlockData.get(block.type)->solidityType == BLOCK_SOLIDITY_TYPE_LIQUID) { wc.mNumUnderWater++; } } } } else { // finally, generate the stack of blocks for this x, z for (worldPosition.y = worldY; worldPosition.y < (worldY + positiveNoiseHeight); worldPosition.y++) { if (doOutCroppings) { block.type = mPeriodics.generateBlockAtWorldPosition(worldPosition); } else { block.type = mPeriodics.generateBlockAtWorldPosition(worldPosition, terrainHeight); } if (worldPosition.y == worldY) { floorBlockType = block.type; } if (block.type > BLOCK_TYPE_AIR) { wc.setBlockAtWorldPosition(worldPosition, block); } } if (doOutCroppings) { // this is the wrong place for this!!!! if (treePossible && r_numi(0, 10) >= 5) { // reset this to the ground level worldPosition.y = worldY; growTree(worldPosition, floorBlockType, wc.mNumUnderWater); } else { worldPosition.y = worldY; growGroundCover(worldPosition); } } } } } int lowest = wc.getLowestBlockHeight(); // fill in the underground /* for (relativePosition.z = 0; relativePosition.z < DEFAULT_REGION_SIDE; relativePosition.z++) { for (relativePosition.x = 0; relativePosition.x < DEFAULT_REGION_SIDE; relativePosition.x++) { v3di_t worldPosition; worldPosition.x = worldX + relativePosition.x; worldPosition.z = worldZ + relativePosition.z; int terrainHeight = static_cast<int>(floor (mPeriodics.getTerrainHeight (worldPosition.x, worldPosition.z))); for (worldPosition.y = lowest; worldPosition.y < terrainHeight; worldPosition.y++) { block_t block = mPeriodics.generateBlockAtWorldPosition (worldPosition); wc.setBlockAtWorldPosition (worldPosition, block, mPeriodics); } } }*/ // #pragma omp parallel for for (int rz = 0; rz < WORLD_CHUNK_SIDE; rz++) { for (int rx = 0; rx < WORLD_CHUNK_SIDE; rx++) { v3di_t worldPosition; worldPosition.x = worldX + rx; worldPosition.z = worldZ + rz; int terrainIndex = (rx + 1) + ((rz + 1) * (WORLD_CHUNK_SIDE + 2)); int terrainHeight = heightMap[terrainIndex]; for (worldPosition.y = lowest; worldPosition.y < terrainHeight; worldPosition.y++) { if (doOutCroppings) { block.type = mPeriodics.generateBlockAtWorldPosition(worldPosition); } else { block.type = mPeriodics.generateBlockAtWorldPosition(worldPosition, terrainHeight); } wc.setBlockAtWorldPosition(worldPosition, block); } } } applyOverdrawBlocks(wc); return 1; }