Automaton build(int lo, int hi) { int firstClose = -1; int level = 0; for (int i = lo; i <= hi; ++i) { if (isOpen(i)) ++level; if (isClose(i)) --level; if (isClose(i) && firstClose == -1 && level == 0) firstClose = i; if (isOr(i) && level == 0) return autoOr(build(lo, i - 1), build(i + 1, hi)); } int mid = lo+1; if (isOpen(lo)) mid = firstClose + 1; bool star = false; if (mid <= hi && isStar(mid)) { ++mid; star = true; } Automaton A = isOpen(lo) ? build(lo + 1, firstClose - 1) : autoChar(regex[lo]); if (star) A = autoStar(A); if (mid > hi) return A; return autoSeq(A, build(mid, hi)); }
/*! Draw lines from the pole \param painter Painter \param canvasRect Contents rect of the canvas in painter coordinates \param pole Position of the pole in painter coordinates \param radius Length of the lines in painter coordinates \param azimuthMap Maps azimuth values to values related to 0.0, M_2PI \param values Azimuth values, indicating the direction of the lines */ void QwtPolarGrid::drawRays( QPainter *painter, const QwtDoubleRect &canvasRect, const QwtDoublePoint &pole, double radius, const QwtScaleMap &azimuthMap, const QwtValueList &values ) const { for ( int i = 0; i < int( values.size() ); i++ ) { double azimuth = azimuthMap.xTransform( values[i] ); azimuth = ::fmod( azimuth, 2 * M_PI ); bool skipLine = false; if ( testDisplayFlag( SmartScaleDraw ) ) { const QwtAbstractScaleDraw::ScaleComponent bone = QwtAbstractScaleDraw::Backbone; if ( isClose( azimuth, 0.0 ) ) { const AxisData &axis = d_data->axisData[QwtPolar::AxisRight]; if ( axis.isVisible && axis.scaleDraw->hasComponent( bone ) ) skipLine = true; } else if ( isClose( azimuth, M_PI / 2 ) ) { const AxisData &axis = d_data->axisData[QwtPolar::AxisTop]; if ( axis.isVisible && axis.scaleDraw->hasComponent( bone ) ) skipLine = true; } else if ( isClose( azimuth, M_PI ) ) { const AxisData &axis = d_data->axisData[QwtPolar::AxisLeft]; if ( axis.isVisible && axis.scaleDraw->hasComponent( bone ) ) skipLine = true; } else if ( isClose( azimuth, 3 * M_PI / 2.0 ) ) { const AxisData &axis = d_data->axisData[QwtPolar::AxisBottom]; if ( axis.isVisible && axis.scaleDraw->hasComponent( bone ) ) skipLine = true; } } if ( !skipLine ) { const QwtDoublePoint pos = qwtPolar2Pos( pole, radius, azimuth ); /* Qt4 is horrible slow, when painting primitives, with coordinates far outside the visible area. */ QwtPolygon pa( 2 ); pa.setPoint( 0, pole.toPoint() ); pa.setPoint( 1, pos.toPoint() ); if ( testDisplayFlag( ClipGridLines ) ) pa = QwtClipper::clipPolygon( canvasRect.toRect(), pa ); QwtPainter::drawPolyline( painter, pa ); } } }
bool isConfigValid( double rangeResolution, double angleIncrement, int baudrate ) { if ( (!isClose(rangeResolution, 0.001)) && (!isClose(rangeResolution, 0.01)) ) { cout<<"bad range resolution." << endl; return false; } if ( !isClose(angleIncrement,DEG2RAD(0.5)) && !isClose(angleIncrement,DEG2RAD(1.0)) ) { cout<<"bad angle." << endl; return false; } switch (baudrate) { case 9600: break; case 19200: break; case 38400: break; case 500000: break; default: cout<<"bad baudrate." << endl; return false; } return true; }
double rangeResolution2MaxRange( double rangeResolution ) { if ( isClose( rangeResolution, 0.001 ) ) return 8.0; else if ( isClose( rangeResolution, 0.01 ) ) return 80.0; else { assert( false && "Didn't expect this range resolution." ); return 0.0; } }
int angleIncrement2NumberOfSamples( double angleIncrement ) { if ( isClose( angleIncrement, 1.0 ) ) return 181; else if ( isClose( angleIncrement, 0.5 ) ) return 361; else { assert( false && "Didn't expect this angle increment." ); return 0; } }
double maxRange2RangeResolution( double maxRange ) { if ( isClose( maxRange, 8.0 ) ) return 0.001; else if ( isClose( maxRange, 80.0 ) ) return 0.01; else { assert( false && "Didn't expect this max range." ); return 0.0; } }
//END::PAGE::Absolute Value //BEGIN::PAGE::gotoItem // makes SPHERE go to specified item void gotoItem(int n) { api.getMyZRState(sphere); game.getItemLocation(n, itemLoc); api.setPositionTarget(itemLoc); if(isClose(itemLoc) && isStopSpin() && isStopMove()) { if(startTurnX == n) { if(startX > 0) { torques[0] = -sphere[7]; torques[1] = sphere[6]; } else if(startX < 0) { torques[0] = sphere[7]; torques[1] = -sphere[6]; } api.setAttitudeTarget(torques); startTurnX = startTurnX + 1; } } else { if(startTurnX == n && abs(sphere[11]) > minAngularSpeed) { rotation[2] = resetRotationTorque; //rotation needed to stop before next item api.setTorques(rotation); } } }
extern real read_numeric_multi(bool f_optional, int *p_n_readings) { size_t n_readings = 0; real tot = (real)0.0; skipblanks(); if (!isOpen(ch)) { real r = read_number(f_optional); if (p_n_readings) *p_n_readings = (r == HUGE_REAL ? 0 : 1); return r; } nextch(); skipblanks(); do { tot += read_number(fFalse); ++n_readings; skipblanks(); } while (!isClose(ch)); nextch(); if (p_n_readings) *p_n_readings = n_readings; /* FIXME: special averaging for bearings ... */ /* And for percentage gradient */ return tot / n_readings; }
int calcDistance(int xPos1, int yPos1, int xPos2, int yPos2, World* world) { char** tempBoard = copyBoard(world->gameBoard); int distanceToDest = UNREACHABLE_DISTANCE; // unreachable int isNodeValid = 0; // set the cheese square as a wall in the temp board, because the cat can't move through cheese tempBoard[world->cheeseYPos][world->cheeseXPos] = WALL_SQUARE; Node* node = NULL; Node* node1 = (Node*)malloc(sizeof(Node)); if (node1 == NULL) { perror("ERROR: malloc failed\n"); exit(1); } node1->xPos = xPos1; node1->yPos = yPos1; node1->distance = 0; int isFoundDest = 0; ListRef queue = newList(node1); ListRef queueHead = queue; while (queue != NULL && !isEmpty(queue) && !isFoundDest) { node = (Node*)headData(queue); tempBoard[node->yPos][node->xPos] = WALL_SQUARE; Direction direction; for (direction = 0; direction < NUM_DIRECTIONS; direction++) { Node* movedNode = (Node*)malloc(sizeof(Node)); if (movedNode == NULL) { perror("ERROR: malloc failed\n"); exit(1); } movedNode->xPos = node->xPos; movedNode->yPos = node->yPos; movedNode->distance = node->distance; isNodeValid = moveNode(node->xPos, node->yPos, tempBoard, direction, movedNode); if (isNodeValid == 1) { if (isClose(movedNode->xPos,movedNode->yPos, xPos2, yPos2)) { distanceToDest = movedNode->distance; isFoundDest = 1; free(movedNode); break; } tempBoard[movedNode->yPos][movedNode->xPos] = WALL_SQUARE; append(queue, movedNode); } } queue = tail(queue); } freeBoard(tempBoard); destroyList(queueHead, free); return distanceToDest; }
bool socketer::canAccept() { if(!isClose() && socket_can_read(m_sockfd)) { return true; } return false; }
//============================================================================== bool hasClosePoint(const std::vector<Contact>& _contacts, const Eigen::Vector3d& _point) { for (const auto& contact : _contacts) { if (isClose(contact.point, _point)) return true; } return false; }
void AlertBox::touchEnded(Touch* touch, Event* event) { if(_dead)return; if(!isScroll(touch)) { click(touch); isClose(touch); } _offsetPoint = touch->getLocation(); _moved = false; }
void changeFixedState(){ for(int i = 0;i < 6;i++){ if(equal(0.0,cmd_vel[i]) && !fixed[i] && isClose(vel[i],0.0)){ pid[i].resetPID(); pid[i].setK(fixPointK[i][0],fixPointK[i][1],fixPointK[i][2]); fixed[i] = true; fixedPosition[i] = position[i]; }else if(!equal(0.0,cmd_vel[i]) && fixed[i]){ pid[i].resetPID(); pid[i].setK(cmdVelK[i][0],cmdVelK[i][1],cmdVelK[i][2]); fixed[i] = false; } } }
void Any::readUntilCommaOrClose(TextInput& ti, Token& token) { while (!(((token.type() == Token::SYMBOL) && (isClose(token.string()[0]))) || isSeparator(token.string()[0]))) { switch (token.type()) { case Token::NEWLINE: case Token::COMMENT: // Consume token = ti.read(); break; default: throw ParseError(ti.filename(), token.line(), token.character(), "Expected a comma or close paren"); } } }
//------------------------------------------------------------------------------ std::string WebSocketFrame::toString() const { std::stringstream ss; ss << "Flags:"; ss << " CONT=" << (isContinuation() ? "Y" : "N"); ss << ", TXT=" << (isText() ? "Y" : "N"); ss << ", BIN=" << (isBinary() ? "Y" : "N"); ss << ", CLOSE=" << (isClose() ? "Y" : "N"); ss << ", PING=" << (isPing() ? "Y" : "N"); ss << ", PONG=" << (isPong() ? "Y" : "N"); ss << ", FINAL=" << (isFinal() ? "Y" : "N"); ss << ", RSV1=" << (isRSV1() ? "Y" : "N"); ss << ", RSV2=" << (isRSV2() ? "Y" : "N"); ss << ", RSV3=" << (isRSV3() ? "Y" : "N"); ss << ", nBytes=" << size(); ss << ", bytes=" << getText(); return ss.str(); }
QString Key8Manager::filterKey(QString const &path) { if (path.isEmpty()) return ""; QString result = ""; result += path[0]; for (int i = 1; i < path.length() - 1; ++i) { if (path[i - 1] == path[i + 1] && isClose(path[i - 1], path[i])) i += 2; else result += path[i]; } if (path.length() > 1) result += path.right(1); return result; }
/* In order to collect an item, the following conditions must be true: 1. You must be < 0.05 meters away 2. You must have an angular velocity of < 2.3 degrees/second 3. You must have a linear velocity of < 0.01 meters per second 4. You must turn 90 degrees in any direction once 1,2,3 are true to collect an item. The function is able to accept ints 0, 1, and 2, which correspond to items in the game. 1,2,3 are accounted for in their own various functions, isClose, isStopSpin, isStopMove 4 is accounted for with the rotation below with the function setAttitudeTarget */ void gotoItem(int n) { api.getMyZRState(sphere); game.getItemLocation(n, itemLoc); api.setPositionTarget(itemLoc); if(isClose(itemLoc) && isStopSpin() && isStopMove()) { //the purpose of startTurnX is to make sure you only turn once per item, save fuel if(startTurnX == n) { /* changes attitude vector from current position to either 90 degrees clockwise 90 degrees counterclockwise */ if(startX > 0) { torques[0] = -sphere[7]; torques[1] = sphere[6]; } else if(startX < 0) { torques[0] = sphere[7]; torques[1] = -sphere[6]; } api.setAttitudeTarget(torques); startTurnX = startTurnX + 1; } } else { //stops the robot by applying torque if(startTurnX == n && abs(sphere[11]) > minAngularSpeed) { rotation[2] = resetRotationTorque; //rotation needed to stop before next item api.setTorques(rotation); } } }
int main(){ long xa(0), ya(0), xb(0), yb(0); scanf("%ld %ld %ld %ld", &xa, &ya, &xb, &yb); long xmin(0), xmax(0), ymin(0), ymax(0); if(xa < xb){xmin = xa; xmax = xb;} else{xmin = xb; xmax = xa;} if(ya < yb){ymin = ya; ymax = yb;} else{ymin = yb; ymax = ya;} std::set<std::pair<long,long>> coldGenerals; std::set<std::pair<long,long>>::iterator myIter; for(long k = ymin; k <= ymax; k++){coldGenerals.insert(std::pair<long,long>(xmin,k));} for(long k = ymin; k <= ymax; k++){coldGenerals.insert(std::pair<long,long>(xmax,k));} for(long k = xmin; k <= xmax; k++){coldGenerals.insert(std::pair<long,long>(k,ymin));} for(long k = xmin; k <= xmax; k++){coldGenerals.insert(std::pair<long,long>(k,ymax));} std::vector<std::pair<long,long>> radiators; std::vector<long> radii; long numRadiators(0); scanf("%ld", &numRadiators); for(long k = 0; k < numRadiators; k++){ long xtemp(0), ytemp(0), tempRadius(0); scanf("%ld %ld %ld", &xtemp, &ytemp, &tempRadius); radiators.push_back(std::pair<long,long>(xtemp,ytemp)); radii.push_back(tempRadius); } for(long k = 0; k < numRadiators; k++){ myIter = coldGenerals.begin(); while(myIter != coldGenerals.end()){ if(isClose(myIter->first, myIter->second,radiators[k].first,radiators[k].second,radii[k])){coldGenerals.erase(myIter); myIter = coldGenerals.begin();} else{myIter++;} } } printf("%ld\n", coldGenerals.size()); return 0; }
socketer *socketer::accept() { int e; if(isClose()) return NULL; e = socket_can_read(m_sockfd); if( 1 == e ) { struct sockaddr_in client_addr; socketer *temp; net_socket new_sock = accept(m_sockfd, (struct sockaddr *)&client_addr, *size); if(new_sock == NET_INVALID_SOCKET) return NULL; temp = new socketer; if(!temp) { socket_close(&new_sock); return NULL; } return temp; } else { if(e == -1) { debuglog("select socket error!\n"); return NULL; } else if(e == 0) { debuglog("select socket overtime...error:%ld\n",GetLastError()); } } debuglog("end so return null...\n"); return NULL; }
int main(int argc, const char * argv[]) { setup_log(); double destination[3] = {0, 5, 3} ; double vitesse[3] = {0} ; double position[3] = {0} ; double propulsion_verticale = 0, propulsion_horizontale = 0 ; int i = 1; do { double delta_t = get_delta_t(); ; double acceleration[3]; double deplacement[3] = { 0 }; acquerir_acceleration(acceleration); double v0[3]; matrix_col_copy(vitesse, v0); // vitesse = acceleration * ∆t + v0 matrix_k(acceleration, delta_t, acceleration); matrix_col_sum(acceleration, v0, vitesse); // vitesse = 1/2 . acceleration * ∆t^2 + v0 . ∆t matrix_k(acceleration, delta_t, acceleration); matrix_k(acceleration, 0.5, acceleration); matrix_k(v0, delta_t, v0); matrix_col_sum(deplacement, acceleration, deplacement); matrix_col_sum(deplacement, v0, deplacement); //On calcul la nouvelle position du dirigeable double θ = acquerir_angle_nord() / (2 * PI) ; //conversion degré/radians double matrice_passage[3][3] = { { cos(θ), sin(θ), 0 }, { -sin(θ), cos(θ), 0 }, { 0 , 0 , 1 } }; matrix_product(deplacement, matrice_passage, deplacement); //on calcul les coordonées de d dans (i,j) matrix_col_sum(deplacement, position, position); // on ajoute le déplacement à la position du dirigeable // et on agit en fonction //on inverse la matrice de passage afin d'aller de (i, j) vers (k, l) matrice_passage[0][1] *= -1 ; matrice_passage[1][0] *= -1 ; //les coordonées de la destination, dans le référentiel du ballon double dest[3] ; matrix_col_copy(destination, dest) ; matrix_col_diff(dest, position, dest); matrix_product(dest, matrice_passage, dest); char tourner = 0 ; double angle_destination = atan(dest[0]/dest[1]); double distance_destination = sqrt(pow(dest[0], 2) + pow(dest[1], 2)); // Dans le plan (x, y) if(distance_destination > 0.1){ if(dest[1] > 0 && isClose(angle_destination, 0, PI/16)){ if(vitesse[1] > .1 && acceleration[1] > 0){ propulsion_horizontale -= .1 ; } if(vitesse[1] < .1){ propulsion_horizontale += .1 ; } } else { propulsion_horizontale = .2 ; if(dest[0] < 0){ tourner = -1 ; } else if(dest[0] > 0){ tourner = 1 ; } } } else { if (vitesse[1] > 0.01) { //on ralenti à l'approche de l'objectif propulsion_horizontale = -7 ; } else { propulsion_horizontale = 0 ; } } // on adapte la propulsion verticale if(vitesse[2] > 0.1){ propulsion_verticale-- ; if(vitesse[2] > 1){ propulsion_verticale -= 10; } } else if(vitesse[2] < - 0.1){ propulsion_verticale++ ; if(vitesse[2] < -1){ propulsion_verticale += 10; } } else if(position[2] < destination[2]){ propulsion_verticale++; } else if (position[2] > destination[2]){ propulsion_verticale-- ; } //On réajuste ensuite les demandes moteur if(propulsion_verticale > 100){ propulsion_verticale = 100 ; } else if(propulsion_verticale < 1){ propulsion_verticale = 1 ; } if(propulsion_horizontale > 100){ propulsion_horizontale = 100 ; } else if(propulsion_horizontale < -100){ propulsion_horizontale = -100 ; } double norme = sqrt(pow(propulsion_verticale,2) + pow(propulsion_horizontale,2)) ; // si on demande une trop forte poussée aux moteurs, on réajuste la demande // en donnant la priorité à la poussée verticale if(norme > 100){ norme = 100 ; int signe = propulsion_horizontale < 0 ? -1 : 1 ; propulsion_horizontale = signe * sqrt(pow(norme, 2) - pow(propulsion_verticale,2)) ; } double angle_moteur_gauche = atan(propulsion_horizontale / propulsion_verticale) ; double angle_moteur_droit = angle_moteur_gauche ; if(tourner != 0){ angle_moteur_gauche *= tourner ; angle_moteur_droit *= -tourner ; } adapter_propulsion(norme, angle_moteur_gauche, angle_moteur_droit); if(i % 5 == 0){ //On complète le log toutes les 5 périodes add_log(acceleration, vitesse, position, dest, propulsion_verticale, propulsion_horizontale, angle_moteur_gauche, angle_moteur_droit, θ); } } while(i++ < 1200) ; matrix_col_print(position); close_log(); return 0; }
void AudioResamplerDyn<TC, TI, TO>::setSampleRate(int32_t inSampleRate) { if (mInSampleRate == inSampleRate) { return; } int32_t oldSampleRate = mInSampleRate; int32_t oldHalfNumCoefs = mConstants.mHalfNumCoefs; uint32_t oldPhaseWrapLimit = mConstants.mL << mConstants.mShift; bool useS32 = false; mInSampleRate = inSampleRate; // TODO: Add precalculated Equiripple filters if (mFilterQuality != getQuality() || !isClose(inSampleRate, oldSampleRate, mFilterSampleRate, mSampleRate)) { mFilterSampleRate = inSampleRate; mFilterQuality = getQuality(); // Begin Kaiser Filter computation // // The quantization floor for S16 is about 96db - 10*log_10(#length) + 3dB. // Keep the stop band attenuation no greater than 84-85dB for 32 length S16 filters // // For s32 we keep the stop band attenuation at the same as 16b resolution, about // 96-98dB // double stopBandAtten; double tbwCheat = 1.; // how much we "cheat" into aliasing int halfLength; if (mFilterQuality == DYN_HIGH_QUALITY) { // 32b coefficients, 64 length useS32 = true; stopBandAtten = 98.; if (inSampleRate >= mSampleRate * 4) { halfLength = 48; } else if (inSampleRate >= mSampleRate * 2) { halfLength = 40; } else { halfLength = 32; } } else if (mFilterQuality == DYN_LOW_QUALITY) { // 16b coefficients, 16-32 length useS32 = false; stopBandAtten = 80.; if (inSampleRate >= mSampleRate * 4) { halfLength = 24; } else if (inSampleRate >= mSampleRate * 2) { halfLength = 16; } else { halfLength = 8; } if (inSampleRate <= mSampleRate) { tbwCheat = 1.05; } else { tbwCheat = 1.03; } } else { // DYN_MED_QUALITY // 16b coefficients, 32-64 length // note: > 64 length filters with 16b coefs can have quantization noise problems useS32 = false; stopBandAtten = 84.; if (inSampleRate >= mSampleRate * 4) { halfLength = 32; } else if (inSampleRate >= mSampleRate * 2) { halfLength = 24; } else { halfLength = 16; } if (inSampleRate <= mSampleRate) { tbwCheat = 1.03; } else { tbwCheat = 1.01; } } // determine the number of polyphases in the filterbank. // for 16b, it is desirable to have 2^(16/2) = 256 phases. // https://ccrma.stanford.edu/~jos/resample/Relation_Interpolation_Error_Quantization.html // // We are a bit more lax on this. int phases = mSampleRate / gcd(mSampleRate, inSampleRate); // TODO: Once dynamic sample rate change is an option, the code below // should be modified to execute only when dynamic sample rate change is enabled. // // as above, #phases less than 63 is too few phases for accurate linear interpolation. // we increase the phases to compensate, but more phases means more memory per // filter and more time to compute the filter. // // if we know that the filter will be used for dynamic sample rate changes, // that would allow us skip this part for fixed sample rate resamplers. // while (phases<63) { phases *= 2; // this code only needed to support dynamic rate changes } if (phases>=256) { // too many phases, always interpolate phases = 127; } // create the filter mConstants.set(phases, halfLength, inSampleRate, mSampleRate); createKaiserFir(mConstants, stopBandAtten, inSampleRate, mSampleRate, tbwCheat); } // End Kaiser filter // update phase and state based on the new filter. const Constants& c(mConstants); mInBuffer.resize(mChannelCount, c.mHalfNumCoefs); const uint32_t phaseWrapLimit = c.mL << c.mShift; // try to preserve as much of the phase fraction as possible for on-the-fly changes mPhaseFraction = static_cast<unsigned long long>(mPhaseFraction) * phaseWrapLimit / oldPhaseWrapLimit; mPhaseFraction %= phaseWrapLimit; // should not do anything, but just in case. mPhaseIncrement = static_cast<uint32_t>(static_cast<uint64_t>(phaseWrapLimit) * inSampleRate / mSampleRate); // determine which resampler to use // check if locked phase (works only if mPhaseIncrement has no "fractional phase bits") int locked = (mPhaseIncrement << (sizeof(mPhaseIncrement)*8 - c.mShift)) == 0; if (locked) { mPhaseFraction = mPhaseFraction >> c.mShift << c.mShift; // remove fractional phase } // stride is the minimum number of filter coefficients processed per loop iteration. // We currently only allow a stride of 16 to match with SIMD processing. // This means that the filter length must be a multiple of 16, // or half the filter length (mHalfNumCoefs) must be a multiple of 8. // // Note: A stride of 2 is achieved with non-SIMD processing. int stride = ((c.mHalfNumCoefs & 7) == 0) ? 16 : 2; LOG_ALWAYS_FATAL_IF(stride < 16, "Resampler stride must be 16 or more"); LOG_ALWAYS_FATAL_IF(mChannelCount < 1 || mChannelCount > 8, "Resampler channels(%d) must be between 1 to 8", mChannelCount); // stride 16 (falls back to stride 2 for machines that do not support NEON) if (locked) { switch (mChannelCount) { case 1: mResampleFunc = &AudioResamplerDyn<TC, TI, TO>::resample<1, true, 16>; break; case 2: mResampleFunc = &AudioResamplerDyn<TC, TI, TO>::resample<2, true, 16>; break; case 3: mResampleFunc = &AudioResamplerDyn<TC, TI, TO>::resample<3, true, 16>; break; case 4: mResampleFunc = &AudioResamplerDyn<TC, TI, TO>::resample<4, true, 16>; break; case 5: mResampleFunc = &AudioResamplerDyn<TC, TI, TO>::resample<5, true, 16>; break; case 6: mResampleFunc = &AudioResamplerDyn<TC, TI, TO>::resample<6, true, 16>; break; case 7: mResampleFunc = &AudioResamplerDyn<TC, TI, TO>::resample<7, true, 16>; break; case 8: mResampleFunc = &AudioResamplerDyn<TC, TI, TO>::resample<8, true, 16>; break; } } else { switch (mChannelCount) { case 1: mResampleFunc = &AudioResamplerDyn<TC, TI, TO>::resample<1, false, 16>; break; case 2: mResampleFunc = &AudioResamplerDyn<TC, TI, TO>::resample<2, false, 16>; break; case 3: mResampleFunc = &AudioResamplerDyn<TC, TI, TO>::resample<3, false, 16>; break; case 4: mResampleFunc = &AudioResamplerDyn<TC, TI, TO>::resample<4, false, 16>; break; case 5: mResampleFunc = &AudioResamplerDyn<TC, TI, TO>::resample<5, false, 16>; break; case 6: mResampleFunc = &AudioResamplerDyn<TC, TI, TO>::resample<6, false, 16>; break; case 7: mResampleFunc = &AudioResamplerDyn<TC, TI, TO>::resample<7, false, 16>; break; case 8: mResampleFunc = &AudioResamplerDyn<TC, TI, TO>::resample<8, false, 16>; break; } } #ifdef DEBUG_RESAMPLER printf("channels:%d %s stride:%d %s coef:%d shift:%d\n", mChannelCount, locked ? "locked" : "interpolated", stride, useS32 ? "S32" : "S16", 2*c.mHalfNumCoefs, c.mShift); #endif }
void VertexSnapper::snap() { qDebug("VertexSnapper::snap: ENTERING SNAP"); for ( unsigned int i = 0; i < subGeometry.size(); i++ ) { // find close features from the reference layer // vectors of coordinates of close Geometries std::vector<double> closeCoordX; std::vector<double> closeCoordY; qDebug("VertexSnapper::snap: Vectors with coordinates created"); for ( unsigned int j = 0; j < refGeometry.size(); j++) { bool close = isClose( subGeometry[i].getGEOSGeom(), refGeometry[j].getGEOSGeom() ); qDebug("VertexSnapper::snap: isClose checked."); if (close) { // add close coordinates //closeCoord->add( refGeometry[j].getGEOSGeom()->getCoordinates(), false, true );//(*ref_it).getGEOSGeom()->getCoordinates(), false, true ); // get points from geometry //GEOSGeometry* points = GEOSGeom_extractUniquePoints( refGeometry[j].getGEOSGeom() ); const GEOSCoordSequence *coords = GEOSGeom_getCoordSeq( refGeometry[j].getGEOSGeom() ); // NOTE: Only linestring or points is possible //GEOSCoordSequence *coords = GEOSCoordSeq_clone( s ); qDebug("VertexSnapper::snap: GEOSCoordSequence cloned from refGeometry"); // get number of points unsigned int cSize; GEOSCoordSeq_getSize( coords, &cSize ); // add x and y coordinates to the vectors for ( unsigned int k = 0; k < cSize; k++ ) { double x, y; GEOSCoordSeq_getX( coords, k, &x ); GEOSCoordSeq_getY( coords, k, &y ); closeCoordX.push_back(x); closeCoordY.push_back(y); qDebug("VertexSnapper::snap: Close coordinates x, y added to vector"); } //GEOSCoordSeq_destroy(coords); } } // create sequence with close points int dim = GEOSGeom_getDimensions( refGeometry[0].getGEOSGeom() ); GEOSCoordSequence *closeCoord = GEOSCoordSeq_create( closeCoordX.size(), dim ); qDebug("VertexSnapper::snap: GEOSCoordSequence closeCoord created"); for( unsigned int l = 0; l < closeCoordX.size(); l++) { GEOSCoordSeq_setX(closeCoord, l, closeCoordX[l]); GEOSCoordSeq_setY(closeCoord, l, closeCoordY[l]); } // snap vertex snapVertices( &subGeometry[i], closeCoord); newGeometry.push_back( subGeometry[i] ); GEOSCoordSeq_destroy(closeCoord); } } // void VertexSnapper::snap()
//Takes an expression in a string and evalutates in, boolean or arithmentic double evaluate_expression(string& input) { SyntaxChecker check; //Here's our checker object double rhs, lhs, result; //Some doubles we will need syntax_status oper; //this is for passing into the function process stack<double> operands; //Operand stack stack<syntax_status> operators; //Operator stack list<exprToken> expression; //Here's the list we need to pass into syntax_check //Here we pass in the expression to see if it passes the test if (check.syntax_check(input, expression) != 0) //this also populates the list of tokens { return numeric_limits<double>::quiet_NaN(); //if the input is invalid, return NaN } if (expression.size() == 0) { return numeric_limits<double>::quiet_NaN(); } //Iterate through the list of tokens for (list<exprToken>::iterator itr = expression.begin(); itr != expression.end(); ++itr) { //If it's a number push it on the operand stack if (itr->isANumber) { operands.push(itr->number); //If there is a negative or not on top of the stack, process it now while (!operators.empty() && isUnary(operators.top())) { if (isNot(operators.top())) result = !operands.top(); else if (isNegative(operators.top())) result = -operands.top(); operands.pop(); operators.pop(); operands.push(result); } } //If it's an operator else if (isOperator(itr->token)) { //if there are none, push it onto the stack if (operators.empty()) { operators.push(itr->token); } //if it's precedence is lower or equal to what's on top, process the last one else if (precedence(itr->token) <= precedence(operators.top())) { rhs = operands.top(); operands.pop(); lhs = operands.top(); operands.pop(); oper = operators.top(); operators.pop(); result = process(lhs, rhs, oper); operands.push(result); operators.push(itr->token); } //if it's of higher precedence, push it on to be processed later else if (precedence(itr->token) > precedence(operators.top())) { operators.push(itr->token); } } //it's an opening parenthesis, put it in operator stack else if (isOpen(itr->token)) { operators.push(itr->token); } //It's a closing parenthesis, process until the last opening parenthesis else if (isClose(itr->token)) { while (!isOpen(operators.top())) { rhs = operands.top(); operands.pop(); lhs = operands.top(); operands.pop(); oper = operators.top(); operators.pop(); operands.push(process(lhs, rhs, oper)); } operators.pop(); //dump the last opening parenthesis, we're done with it //Now if there is a ! or - on top of the operator stack we need to evaluate it //for the expression that was inside the parenthesis while (!operators.empty() && isUnary(operators.top())) { if (isNot(operators.top())) result = !operands.top(); else if (isNegative(operators.top())) result = -operands.top(); operands.pop(); operators.pop(); operands.push(result); } } //If we have a - or ! we need to put it in the operand stack regardless of any precedence else if (isUnary(itr->token)) { operators.push(itr->token); } } //After we finish going through the list, we need to evaluate any remaining operators while (!operators.empty()) { rhs = operands.top(); operands.pop(); lhs = operands.top(); operands.pop(); oper = operators.top(); operators.pop(); operands.push(process(lhs, rhs, oper)); } //The top of the operand stack is the solution return operands.top(); }
int vrpn_Tracker_DeadReckoning_Rotation::test(void) { // Construct a loopback connection to be used by all of our objects. vrpn_Connection *c = vrpn_create_server_connection("loopback:"); // Create a tracker server to be the initator and a dead-reckoning // rotation tracker to use it as a base; have it predict 1 second // into the future. vrpn_Tracker_Server *t0 = new vrpn_Tracker_Server("Tracker0", c, 2); vrpn_Tracker_DeadReckoning_Rotation *t1 = new vrpn_Tracker_DeadReckoning_Rotation("Tracker1", c, "*Tracker0", 2, 1); // Create a remote tracker to listen to t1 and set up its callbacks for // position and velocity reports. They will fill in the static structures // listed above with whatever values they receive. vrpn_Tracker_Remote *tr = new vrpn_Tracker_Remote("Tracker1", c); tr->register_change_handler(&poseResponse, handle_test_tracker_report); tr->register_change_handler(&velResponse, handle_test_tracker_velocity_report); // Set up the values in the pose and velocity responses with incorrect values // so that things will fail if the class does not perform as expected. q_vec_set(poseResponse.pos, 1, 1, 1); q_make(poseResponse.quat, 0, 0, 1, 0); poseResponse.time.tv_sec = 0; poseResponse.time.tv_usec = 0; poseResponse.sensor = -1; // Send a pose report from sensors 0 and 1 on the original tracker that places // them at (1,1,1) and with the identity rotation. We should get a response for // each of them so we should end up with the sensor-1 response matching what we // sent, with no change in position or orientation. q_vec_type pos = { 1, 1, 1 }; q_type quat = { 0, 0, 0, 1 }; struct timeval firstSent; vrpn_gettimeofday(&firstSent, NULL); t0->report_pose(0, firstSent, pos, quat); t0->report_pose(1, firstSent, pos, quat); t0->mainloop(); t1->mainloop(); c->mainloop(); tr->mainloop(); if ( (poseResponse.time.tv_sec != firstSent.tv_sec + 1) || (poseResponse.sensor != 1) || (q_vec_distance(poseResponse.pos, pos) > 1e-10) || (poseResponse.quat[Q_W] != 1) ) { std::cerr << "vrpn_Tracker_DeadReckoning_Rotation::test(): Got unexpected" << " initial response: pos (" << poseResponse.pos[Q_X] << ", " << poseResponse.pos[Q_Y] << ", " << poseResponse.pos[Q_Z] << "), quat (" << poseResponse.quat[Q_X] << ", " << poseResponse.quat[Q_Y] << ", " << poseResponse.quat[Q_Z] << ", " << poseResponse.quat[Q_W] << ")" << " from sensor " << poseResponse.sensor << " at time " << poseResponse.time.tv_sec << ":" << poseResponse.time.tv_usec << std::endl; delete tr; delete t1; delete t0; c->removeReference(); return 1; } // Send a second tracker report for sensor 0 coming 0.4 seconds later that has // translated to position (2,1,1) and rotated by 0.4 * 90 degrees around Z. // This should cause a prediction for one second later than this new pose // message that has rotated by very close to 1.4 * 90 degrees. q_vec_type pos2 = { 2, 1, 1 }; q_type quat2; double angle2 = 0.4 * 90 * M_PI / 180.0; q_from_axis_angle(quat2, 0, 0, 1, angle2); struct timeval p4Second = { 0, 400000 }; struct timeval firstPlusP4 = vrpn_TimevalSum(firstSent, p4Second); t0->report_pose(0, firstPlusP4, pos2, quat2); t0->mainloop(); t1->mainloop(); c->mainloop(); tr->mainloop(); double x, y, z, angle; q_to_axis_angle(&x, &y, &z, &angle, poseResponse.quat); if ((poseResponse.time.tv_sec != firstPlusP4.tv_sec + 1) || (poseResponse.sensor != 0) || (q_vec_distance(poseResponse.pos, pos2) > 1e-10) || !isClose(x, 0) || !isClose(y, 0) || !isClose(z, 1) || !isClose(angle, 1.4 * 90 * M_PI / 180.0) ) { std::cerr << "vrpn_Tracker_DeadReckoning_Rotation::test(): Got unexpected" << " predicted pose response: pos (" << poseResponse.pos[Q_X] << ", " << poseResponse.pos[Q_Y] << ", " << poseResponse.pos[Q_Z] << "), quat (" << poseResponse.quat[Q_X] << ", " << poseResponse.quat[Q_Y] << ", " << poseResponse.quat[Q_Z] << ", " << poseResponse.quat[Q_W] << ")" << " from sensor " << poseResponse.sensor << std::endl; delete tr; delete t1; delete t0; c->removeReference(); return 2; } // Send a velocity report for sensor 1 that has has translation by (1,0,0) // and rotating by 0.4 * 90 degrees per 0.4 of a second around Z. // This should cause a prediction for one second later than the first // report that has rotated by very close to 90 degrees. The translation // should be ignored, so the position should be the original position. q_vec_type vel = { 0, 0, 0 }; t0->report_pose_velocity(1, firstPlusP4, vel, quat2, 0.4); t0->mainloop(); t1->mainloop(); c->mainloop(); tr->mainloop(); q_to_axis_angle(&x, &y, &z, &angle, poseResponse.quat); if ((poseResponse.time.tv_sec != firstSent.tv_sec + 1) || (poseResponse.sensor != 1) || (q_vec_distance(poseResponse.pos, pos) > 1e-10) || !isClose(x, 0) || !isClose(y, 0) || !isClose(z, 1) || !isClose(angle, 90 * M_PI / 180.0) ) { std::cerr << "vrpn_Tracker_DeadReckoning_Rotation::test(): Got unexpected" << " predicted velocity response: pos (" << poseResponse.pos[Q_X] << ", " << poseResponse.pos[Q_Y] << ", " << poseResponse.pos[Q_Z] << "), quat (" << poseResponse.quat[Q_X] << ", " << poseResponse.quat[Q_Y] << ", " << poseResponse.quat[Q_Z] << ", " << poseResponse.quat[Q_W] << ")" << " from sensor " << poseResponse.sensor << std::endl; delete tr; delete t1; delete t0; c->removeReference(); return 3; } // To test the behavior of the prediction code when we're moving around more // than one axis, and when we're starting from a non-identity orientation, // set sensor 1 to be rotated 180 degrees around X. Then send a velocity // report that will produce a rotation of 180 degrees around Z. The result // should match a prediction of 180 degrees around Y (plus or minus 180, plus // or minus Y axis are all equivalent). struct timeval oneSecond = { 1, 0 }; struct timeval firstPlusOne = vrpn_TimevalSum(firstSent, oneSecond); q_type quat3; q_from_axis_angle(quat3, 1, 0, 0, M_PI); t0->report_pose(1, firstPlusOne, pos, quat3); q_type quat4; q_from_axis_angle(quat4, 0, 0, 1, M_PI); t0->report_pose_velocity(1, firstPlusOne, vel, quat4, 1.0); t0->mainloop(); t1->mainloop(); c->mainloop(); tr->mainloop(); q_to_axis_angle(&x, &y, &z, &angle, poseResponse.quat); if ((poseResponse.time.tv_sec != firstPlusOne.tv_sec + 1) || (poseResponse.sensor != 1) || (q_vec_distance(poseResponse.pos, pos) > 1e-10) || !isClose(x, 0) || !isClose(fabs(y), 1) || !isClose(z, 0) || !isClose(fabs(angle), M_PI) ) { std::cerr << "vrpn_Tracker_DeadReckoning_Rotation::test(): Got unexpected" << " predicted pose + velocity response: pos (" << poseResponse.pos[Q_X] << ", " << poseResponse.pos[Q_Y] << ", " << poseResponse.pos[Q_Z] << "), quat (" << poseResponse.quat[Q_X] << ", " << poseResponse.quat[Q_Y] << ", " << poseResponse.quat[Q_Z] << ", " << poseResponse.quat[Q_W] << ")" << " from sensor " << poseResponse.sensor << std::endl; delete tr; delete t1; delete t0; c->removeReference(); return 4; } // To test the behavior of the prediction code when we're moving around more // than one axis, and when we're starting from a non-identity orientation, // set sensor 0 to start out at identity. Then in one second it will be // rotated 180 degrees around X. Then in another second it will be rotated // additionally by 90 degrees around Z; the prediction should be another // 90 degrees around Z, which should turn out to compose to +/-180 degrees // around +/- Y, as in the velocity case above. // To make this work, we send a sequence of three poses, one second apart, // starting at the original time. We do this on sensor 0, which has never // had a velocity report, so that it will be using the pose-only prediction. struct timeval firstPlusTwo = vrpn_TimevalSum(firstPlusOne, oneSecond); q_from_axis_angle(quat3, 1, 0, 0, M_PI); t0->report_pose(0, firstSent, pos, quat); t0->report_pose(0, firstPlusOne, pos, quat3); q_from_axis_angle(quat4, 0, 0, 1, M_PI / 2); q_type quat5; q_mult(quat5, quat4, quat3); t0->report_pose(0, firstPlusTwo, pos, quat5); t0->mainloop(); t1->mainloop(); c->mainloop(); tr->mainloop(); q_to_axis_angle(&x, &y, &z, &angle, poseResponse.quat); if ((poseResponse.time.tv_sec != firstPlusTwo.tv_sec + 1) || (poseResponse.sensor != 0) || (q_vec_distance(poseResponse.pos, pos) > 1e-10) || !isClose(x, 0) || !isClose(fabs(y), 1.0) || !isClose(z, 0) || !isClose(fabs(angle), M_PI) ) { std::cerr << "vrpn_Tracker_DeadReckoning_Rotation::test(): Got unexpected" << " predicted pose + pose response: pos (" << poseResponse.pos[Q_X] << ", " << poseResponse.pos[Q_Y] << ", " << poseResponse.pos[Q_Z] << "), quat (" << poseResponse.quat[Q_X] << ", " << poseResponse.quat[Q_Y] << ", " << poseResponse.quat[Q_Z] << ", " << poseResponse.quat[Q_W] << ")" << " from sensor " << poseResponse.sensor << "; axis = (" << x << ", " << y << ", " << z << "), angle = " << angle << std::endl; delete tr; delete t1; delete t0; c->removeReference(); return 5; } // Done; delete our objects and return 0 to indicate that // everything worked. delete tr; delete t1; delete t0; c->removeReference(); return 0; }
/*! Draw circles \param painter Painter \param canvasRect Contents rect of the canvas in painter coordinates \param pole Position of the pole in painter coordinates \param radialMap Maps radius values into painter coordinates. \param values Radial values, indicating the distances from the pole */ void QwtPolarGrid::drawCircles( QPainter *painter, const QwtDoubleRect &canvasRect, const QwtDoublePoint &pole, const QwtScaleMap &radialMap, const QwtValueList &values ) const { for ( int i = 0; i < int( values.size() ); i++ ) { const double val = values[i]; const GridData &gridData = d_data->gridData[QwtPolar::Radius]; bool skipLine = false; if ( testDisplayFlag( SmartScaleDraw ) ) { const AxisData &axis = d_data->axisData[QwtPolar::AxisAzimuth]; if ( axis.isVisible && axis.scaleDraw->hasComponent( QwtAbstractScaleDraw::Backbone ) ) { #if QWT_VERSION < 0x050200 if ( isClose( val, gridData.scaleDiv.hBound() ) ) #else if ( isClose( val, gridData.scaleDiv.upperBound() ) ) #endif skipLine = true; } } #if QWT_VERSION < 0x050200 if ( isClose( val, gridData.scaleDiv.lBound() ) ) #else if ( isClose( val, gridData.scaleDiv.lowerBound() ) ) #endif skipLine = true; if ( !skipLine ) { const double radius = radialMap.transform( val ); QwtDoubleRect outerRect( 0, 0, 2 * radius, 2 * radius ); outerRect.moveCenter( pole ); #if QT_VERSION < 0x040000 QwtPainter::drawEllipse( painter, outerRect.toRect() ); #else if ( testDisplayFlag( ClipGridLines ) ) { /* Qt4 is horrible slow, when painting primitives, with coordinates far outside the visible area. We need to clip. */ const QwtArray<QwtDoubleInterval> angles = QwtClipper::clipCircle( canvasRect, pole, radius ); for ( int i = 0; i < angles.size(); i++ ) { const QwtDoubleInterval intv = angles[i]; if ( intv.minValue() == 0 && intv.maxValue() == 2 * M_PI ) QwtPainter::drawEllipse( painter, outerRect.toRect() ); else { const double from = intv.minValue() / M_PI * 180; const double to = intv.maxValue() / M_PI * 180; double span = to - from; if ( span < 0.0 ) span += 360.0; const QwtMetricsMap &mm = QwtPainter::metricsMap(); const QRect r = outerRect.toRect(); painter->drawArc( mm.layoutToDevice( r, painter ), qRound( from * 16 ), qRound( span * 16 ) ); } } } else { QwtPainter::drawEllipse( painter, outerRect.toRect() ); } #endif } } }
/*! Draw circles \param painter Painter \param canvasRect Contents rect of the canvas in painter coordinates \param pole Position of the pole in painter coordinates \param radialMap Maps radius values into painter coordinates. \param values Radial values, indicating the distances from the pole */ void QwtPolarGrid::drawCircles( QPainter *painter, const QRectF &canvasRect, const QPointF &pole, const QwtScaleMap &radialMap, const QList<double> &values ) const { for ( int i = 0; i < int( values.size() ); i++ ) { const double val = values[i]; const GridData &gridData = d_data->gridData[QwtPolar::Radius]; bool skipLine = false; if ( testDisplayFlag( SmartScaleDraw ) ) { const AxisData &axis = d_data->axisData[QwtPolar::AxisAzimuth]; if ( axis.isVisible && axis.scaleDraw->hasComponent( QwtAbstractScaleDraw::Backbone ) ) { if ( isClose( val, gridData.scaleDiv.upperBound() ) ) skipLine = true; } } if ( isClose( val, gridData.scaleDiv.lowerBound() ) ) skipLine = true; if ( !skipLine ) { const double radius = radialMap.transform( val ); QRectF outerRect( 0, 0, 2 * radius, 2 * radius ); outerRect.moveCenter( pole ); if ( testDisplayFlag( ClipGridLines ) ) { /* Qt4 is horrible slow, when painting primitives, with coordinates far outside the visible area. We need to clip. */ const QVector<QwtInterval> angles = QwtClipper::clipCircle( canvasRect, pole, radius ); for ( int i = 0; i < angles.size(); i++ ) { const QwtInterval intv = angles[i]; if ( intv.minValue() == 0 && intv.maxValue() == 2 * M_PI ) QwtPainter::drawEllipse( painter, outerRect ); else { const double from = intv.minValue() / M_PI * 180; const double to = intv.maxValue() / M_PI * 180; double span = to - from; if ( span < 0.0 ) span += 360.0; painter->drawArc( outerRect, qRound( from * 16 ), qRound( span * 16 ) ); } } } else { QwtPainter::drawEllipse( painter, outerRect ); } } } }
bool DockableWidgetLayout::insertLocation( QRect& rect, int& index, DockSide& side, const QSizePolicy& sizePol) { // best insertion data // Distance is a number that represents the how far // the insertion rectangle is from the final location. unsigned bestDistance = 0xFFFFFFFF; int bestIndex = 0; DockSide bestSide; QRect bestRect; // loop over all widgets and find appropriate matching sides for (int i = 0; i < dockedWidgets.size(); ++i) { DockInfo* d = dockedWidgets[i]; /***************************************************** * Check for placement against the top of the widget * *****************************************************/ if (i == 0 || d->dockSide != BOTTOM) { if (!(rect.left() > d->right() - SNAP_DISTANCE || rect.right() < d->left + SNAP_DISTANCE) && isClose(rect.bottom(), d->top)) { // rectangle is close to the edge unsigned dist = 8 * abs(rect.bottom() - d->top); // now find all points on this side // (use set as a sorted unique list) QSet<int> sidePoints; for (int j = 0; j <= i; ++j) { DockInfo* d2 = dockedWidgets[j]; if (d->top == d2->top) { sidePoints.insert(d2->left); sidePoints.insert(d2->right()); // check if any other widget rest against this side for (int k = i + 1; k < dockedWidgets.size(); ++k) { DockInfo* d3 = dockedWidgets[k]; if (d3->bottom() == d2->top) { sidePoints.insert(d3->left); sidePoints.insert(d3->right()); } } } } // widget placement can occur at all points, find the closest QSet<int>::iterator it = sidePoints.begin(); for (int j = 0; j < sidePoints.size() - 1; ++j) { // check after point unsigned newDist1 = dist + abs(*it - rect.left()); if (newDist1 < bestDistance && isClose(*it, rect.left())) { QRect r(QPoint(*it, d->top - rect.height()), rect.size()); if (!overlaysWithFirstNWidgets(r, i)) { bestDistance = newDist1; bestIndex = i + 1; bestSide = TOP; bestRect = r; } } ++it; // check before point unsigned newDist2 = dist + abs(*it - rect.right()); if (newDist2 < bestDistance && isClose(*it, rect.right())) { QRect r(QPoint(*it - rect.width(), d->top - rect.height()), rect.size()); if (!overlaysWithFirstNWidgets(r, i)) { bestDistance = newDist2; bestIndex = i + 1; bestSide = TOP; bestRect = r; } } } // check for resized placement options if (sizePol.horizontalPolicy() != QSizePolicy::Fixed) { int mid = rect.left() + rect.width() / 2; for (QSet<int>::iterator ita = sidePoints.begin() + 1; ita != sidePoints.end(); ++ita) { for (QSet<int>::iterator itb = sidePoints.begin(); ita != itb; ++itb) { int sp_mid = (*ita + *itb) / 2; int sp_diff = *ita - *itb; if (isClose(sp_mid, mid)) { QRect r(*itb, d->top - rect.height(), sp_diff, rect.height()); if (!overlaysWithFirstNWidgets(r, i)) { bestDistance = dist + abs(sp_mid - mid); bestIndex = i + 1; bestSide = TOP; bestRect = r; } } } } } } } /******************************************************** * Check for placement against the bottom of the widget * ********************************************************/ if (i == 0 || d->dockSide != TOP) { if (!(rect.left() > d->right() - SNAP_DISTANCE || rect.right() < d->left + SNAP_DISTANCE) && isClose(rect.top(), d->bottom())) { // rectangle is close to the edge unsigned dist = 8 * abs(rect.top() - d->bottom()); // now find all points on this side // (use set as a sorted unique list) QSet<int> sidePoints; for (int j = 0; j <= i; ++j) { DockInfo* d2 = dockedWidgets[j]; if (d->bottom() == d2->bottom()) { sidePoints.insert(d2->left); sidePoints.insert(d2->right()); // check if any other widget rest against this side for (int k = i + 1; k < dockedWidgets.size(); ++k) { DockInfo* d3 = dockedWidgets[k]; if (d3->top == d2->bottom()) { sidePoints.insert(d3->left); sidePoints.insert(d3->right()); } } } } // widget placement can occur at all points, find the closest QSet<int>::iterator it = sidePoints.begin(); for (int j = 0; j < sidePoints.size() - 1; ++j) { // check after point unsigned newDist1 = dist + abs(*it - rect.left()); if (newDist1 < bestDistance && isClose(*it, rect.left())) { QRect r(QPoint(*it, d->bottom()), rect.size()); if (!overlaysWithFirstNWidgets(r, i)) { bestDistance = newDist1; bestIndex = i + 1; bestSide = BOTTOM; bestRect = r; } } ++it; // check before point unsigned newDist2 = dist + abs(*it - rect.right()); if (newDist2 < bestDistance && isClose(*it, rect.right())) { QRect r(QPoint(*it - rect.width(), d->bottom()), rect.size()); if (!overlaysWithFirstNWidgets(r, i)) { bestDistance = newDist2; bestIndex = i + 1; bestSide = BOTTOM; bestRect = r; } } } // check for resized placement options if (sizePol.horizontalPolicy() != QSizePolicy::Fixed) { int mid = rect.left() + rect.width() / 2; for (QSet<int>::iterator ita = sidePoints.begin() + 1; ita != sidePoints.end(); ++ita) { for (QSet<int>::iterator itb = sidePoints.begin(); ita != itb; ++itb) { int sp_mid = (*ita + *itb) / 2; int sp_diff = *ita - *itb; if (isClose(sp_mid, mid)) { QRect r(*itb, d->bottom(), sp_diff, rect.height()); if (!overlaysWithFirstNWidgets(r, i)) { bestDistance = dist + abs(sp_mid - mid); bestIndex = i + 1; bestSide = BOTTOM; bestRect = r; } } } } } } } /****************************************************** * Check for placement against the left of the widget * ******************************************************/ if (i == 0 || d->dockSide != RIGHT) { if (!(rect.top() > d->bottom() - SNAP_DISTANCE || rect.bottom() < d->top + SNAP_DISTANCE) && isClose(rect.right(), d->left)) { // rectangle is close to the edge unsigned dist = 8 * abs(rect.right() - d->left); // now find all points on this side // (use set as a sorted unique list) QSet<int> sidePoints; for (int j = 0; j <= i; ++j) { DockInfo* d2 = dockedWidgets[j]; if (d->left == d2->left) { sidePoints.insert(d2->top); sidePoints.insert(d2->bottom()); // check if any other widget rest against this side for (int k = i + 1; k < dockedWidgets.size(); ++k) { DockInfo* d3 = dockedWidgets[k]; if (d3->right() == d2->left) { sidePoints.insert(d3->top); sidePoints.insert(d3->bottom()); } } } } // widget placement can occur at all points, find the closest QSet<int>::iterator it = sidePoints.begin(); for (int j = 0; j < sidePoints.size() - 1; ++j) { // check after point unsigned newDist1 = dist + abs(*it - rect.top()); if (newDist1 < bestDistance && isClose(*it, rect.top())) { QRect r(QPoint(d->left - rect.width(), *it), rect.size()); if (!overlaysWithFirstNWidgets(r, i)) { bestDistance = newDist1; bestIndex = i + 1; bestSide = LEFT; bestRect = r; } } ++it; // check before point unsigned newDist2 = dist + abs(*it - rect.bottom()); if (newDist2 < bestDistance && isClose(*it, rect.bottom())) { QRect r(QPoint(d->left - rect.width(), *it - rect.height()), rect.size()); if (!overlaysWithFirstNWidgets(r, i)) { bestDistance = newDist2; bestIndex = i + 1; bestSide = LEFT; bestRect = r; } } } // check for resized placement options if (sizePol.verticalPolicy() != QSizePolicy::Fixed) { int mid = rect.top() + rect.height() / 2; for (QSet<int>::iterator ita = sidePoints.begin() + 1; ita != sidePoints.end(); ++ita) { for (QSet<int>::iterator itb = sidePoints.begin(); ita != itb; ++itb) { int sp_mid = (*ita + *itb) / 2; int sp_diff = *ita - *itb; if (isClose(sp_mid, mid)) { QRect r(d->left - rect.width(), *itb, rect.width(), sp_diff); if (!overlaysWithFirstNWidgets(r, i)) { bestDistance = dist + abs(sp_mid - mid); bestIndex = i + 1; bestSide = LEFT; bestRect = r; } } } } } } } /******************************************************* * Check for placement against the right of the widget * *******************************************************/ if (i == 0 || d->dockSide != LEFT) { if (!(rect.top() > d->bottom() - SNAP_DISTANCE || rect.bottom() < d->top + SNAP_DISTANCE) && isClose(rect.left(), d->right())) { // rectangle is close to the edge unsigned dist = 8 * abs(rect.left() - d->right()); // now find all points on this side // (use set as a sorted unique list) QSet<int> sidePoints; for (int j = 0; j <= i; ++j) { DockInfo* d2 = dockedWidgets[j]; if (d->right() == d2->right()) { sidePoints.insert(d2->top); sidePoints.insert(d2->bottom()); // check if any other widget rest against this side for (int k = i + 1; k < dockedWidgets.size(); ++k) { DockInfo* d3 = dockedWidgets[k]; if (d3->left == d2->right()) { sidePoints.insert(d3->top); sidePoints.insert(d3->bottom()); } } } } // widget placement can occur at all points, find the closest QSet<int>::iterator it = sidePoints.begin(); for (int j = 0; j < sidePoints.size() - 1; ++j) { // check after point unsigned newDist1 = dist + abs(*it - rect.top()); if (newDist1 < bestDistance && isClose(*it, rect.top())) { QRect r(QPoint(d->left + d->width, *it), rect.size()); if (!overlaysWithFirstNWidgets(r, i)) { bestDistance = newDist1; bestIndex = i + 1; bestSide = RIGHT; bestRect = r; } } ++it; // check before point unsigned newDist2 = dist + abs(*it - rect.bottom()); if (newDist2 < bestDistance && isClose(*it, rect.bottom())) { QRect r(QPoint(d->right(), *it - rect.height()), rect.size()); if (!overlaysWithFirstNWidgets(r, i)) { bestDistance = newDist2; bestIndex = i + 1; bestSide = RIGHT; bestRect = r; } } } // check for resized placement options if (sizePol.verticalPolicy() != QSizePolicy::Fixed) { int mid = rect.top() + rect.height() / 2; for (QSet<int>::iterator ita = sidePoints.begin() + 1; ita != sidePoints.end(); ++ita) { for (QSet<int>::iterator itb = sidePoints.begin(); ita != itb; ++itb) { int sp_mid = (*ita + *itb) / 2; int sp_diff = *ita - *itb; if (isClose(sp_mid, mid)) { QRect r(d->right(), *itb, rect.width(), sp_diff); if (!overlaysWithFirstNWidgets(r, i)) { bestDistance = dist + abs(sp_mid - mid); bestIndex = i + 1; bestSide = RIGHT; bestRect = r; } } } } } } } } if (bestIndex) { rect = bestRect; index = bestIndex; side = bestSide; return true; } else { return false; } }