QList<QLineF> Snapper::findSnappingOffsetLines(const SnapLineMap &snappingOffsetMap, Qt::Orientation orientation, double snapLine, double lowerLimit, double upperLimit, QList<QRectF> *boundingRects) const { QList<QLineF> lineList; SnapLineMapIterator snappingOffsetIterator(snappingOffsetMap); while (snappingOffsetIterator.hasNext()) { snappingOffsetIterator.next(); const QRectF &formEditorItemRect(snappingOffsetIterator.value().first); double formEditorItemRectLowerLimit; double formEditorItemRectUpperLimit; if (orientation == Qt::Horizontal) { formEditorItemRectLowerLimit = formEditorItemRect.left(); formEditorItemRectUpperLimit = formEditorItemRect.right(); } else { formEditorItemRectLowerLimit = formEditorItemRect.top(); formEditorItemRectUpperLimit = formEditorItemRect.bottom(); } if (qFuzzyCompare(snapLine, snappingOffsetIterator.key()) && !(lowerLimit > formEditorItemRectUpperLimit || upperLimit < formEditorItemRectLowerLimit)) { lineList += createSnapLine(orientation, snapLine, lowerLimit, upperLimit, formEditorItemRect); if (boundingRects != 0) boundingRects->append(snappingOffsetIterator.value().first); } } return lineList; }
QPixmap loadPixmap(const QString &path) { qreal ratio = 1.0; QPixmap pixmap; const qreal devicePixelRatio = qApp->devicePixelRatio(); if (!qFuzzyCompare(ratio, devicePixelRatio)) { QImageReader reader; reader.setFileName(qt_findAtNxFile(path, devicePixelRatio, &ratio)); if (reader.canRead()) { reader.setScaledSize(reader.size() * (devicePixelRatio / ratio)); pixmap = QPixmap::fromImage(reader.read()); pixmap.setDevicePixelRatio(devicePixelRatio); } } else { pixmap.load(path); } return pixmap; }
QPixmap QScreen::grabWindow(WId window, int x, int y, int width, int height) { const QPlatformScreen *platformScreen = handle(); if (!platformScreen) { qWarning("invoked with handle==0"); return QPixmap(); } const qreal factor = QHighDpiScaling::factor(this); if (qFuzzyCompare(factor, 1)) return platformScreen->grabWindow(window, x, y, width, height); const QPoint nativePos = QHighDpi::toNative(QPoint(x, y), factor); QSize nativeSize(width, height); if (nativeSize.isValid()) nativeSize = QHighDpi::toNative(nativeSize, factor); QPixmap result = platformScreen->grabWindow(window, nativePos.x(), nativePos.y(), nativeSize.width(), nativeSize.height()); result.setDevicePixelRatio(factor); return result; }
void WGraphicsArrowItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) { const QLineF& line = m_line; if (qFuzzyCompare(line.length(), qreal(0.))) return; // Draw the line itself painter->setPen(m_pen); painter->drawLine(line); // Draw the arrows double angle = ::acos(line.dx() / line.length()); if (line.dy() >= 0) angle = TwoPi - angle; painter->setBrush(Qt::black); QPointF startPos = m_line.p1(); QPointF endPos = m_line.p2(); if (!m_uniDirectedArrow) { // QPointF startNodeArrowP1 = startPos + QPointF(sin(angle + Pi / 3) * m_arrowSize, // cos(angle + Pi / 3) * m_arrowSize); // QPointF startNodeArrowP2 = startPos + QPointF(sin(angle + Pi - Pi / 3) * m_arrowSize, // cos(angle + Pi - Pi / 3) * m_arrowSize); // painter->drawPolygon(QPolygonF() << line.p1() << startNodeArrowP1 << startNodeArrowP2); QLineF arrowPoints = Wf::getArrowPoints(endPos, startPos, m_arrowSize); painter->drawPolygon(QPolygonF() << line.p1() << arrowPoints.p1() << arrowPoints.p2()); } { // QPointF endNodeArrowP1 = endPos + QPointF(sin(angle - Pi / 3) * m_arrowSize, // cos(angle - Pi / 3) * m_arrowSize); // QPointF endNodeArrowP2 = endPos + QPointF(sin(angle - Pi + Pi / 3) * m_arrowSize, // cos(angle - Pi + Pi / 3) * m_arrowSize); // painter->drawPolygon(QPolygonF() << line.p2() << endNodeArrowP1 << endNodeArrowP2); QLineF arrowPoints = Wf::getArrowPoints(startPos, endPos, m_arrowSize); painter->drawPolygon(QPolygonF() << line.p2() << arrowPoints.p1() << arrowPoints.p2()); } }
/* * NewtonRaphsonRootFind : * Use Newton-Raphson iteration to find better root. */ static qreal NewtonRaphsonRootFind(QPointF *Q, QPointF P, qreal u) { qreal numerator, denominator; QPointF Q1[3], Q2[2]; /* Q' and Q'' */ QPointF Q_u, Q1_u, Q2_u; /*u evaluated at Q, Q', & Q'' */ qreal uPrime; /* Improved u */ int i; /* Compute Q(u) */ Q_u = BezierII(3, Q, u); /* Generate control vertices for Q' */ for (i = 0; i <= 2; ++i) { Q1[i].setX((Q[i+1].x() - Q[i].x()) * 3.0); Q1[i].setY((Q[i+1].y() - Q[i].y()) * 3.0); } /* Generate control vertices for Q'' */ for (i = 0; i <= 1; ++i) { Q2[i].setX((Q1[i+1].x() - Q1[i].x()) * 2.0); Q2[i].setY((Q1[i+1].y() - Q1[i].y()) * 2.0); } /* Compute Q'(u) and Q''(u) */ Q1_u = BezierII(2, Q1, u); Q2_u = BezierII(1, Q2, u); /* Compute f(u)/f'(u) */ numerator = (Q_u.x() - P.x()) * (Q1_u.x()) + (Q_u.y() - P.y()) * (Q1_u.y()); denominator = (Q1_u.x()) * (Q1_u.x()) + (Q1_u.y()) * (Q1_u.y()) + (Q_u.x() - P.x()) * (Q2_u.x()) + (Q_u.y() - P.y()) * (Q2_u.y()); if (qFuzzyCompare(denominator, qreal(0.0))) { denominator = Zero; } /* u = u - f(u)/f'(u) */ uPrime = u - (numerator / denominator); return (uPrime); }
QGradient* Gradient::platformGradient() { if (m_gradient) return m_gradient; if (m_radial) m_gradient = new QRadialGradient(m_p1.x(), m_p1.y(), m_r1, m_p0.x(), m_p0.y()); else m_gradient = new QLinearGradient(m_p0.x(), m_p0.y(), m_p1.x(), m_p1.y()); QColor stopColor; Vector<ColorStop>::iterator stopIterator = m_stops.begin(); qreal lastStop(0.0); const qreal lastStopDiff = 0.0000001; while (stopIterator != m_stops.end()) { stopColor.setRgbF(stopIterator->red, stopIterator->green, stopIterator->blue, stopIterator->alpha); if (qFuzzyCompare(lastStop, qreal(stopIterator->stop))) lastStop = stopIterator->stop + lastStopDiff; else lastStop = stopIterator->stop; if (m_radial && m_r0) lastStop = m_r0 / m_r1 + lastStop * (1.0f - m_r0 / m_r1); m_gradient->setColorAt(lastStop, stopColor); ++stopIterator; } switch(m_spreadMethod) { case SpreadMethodPad: m_gradient->setSpread(QGradient::PadSpread); break; case SpreadMethodReflect: m_gradient->setSpread(QGradient::ReflectSpread); break; case SpreadMethodRepeat: m_gradient->setSpread(QGradient::RepeatSpread); break; } return m_gradient; }
bool glc::lineIntersectPlane(const GLC_Line3d& line, const GLC_Plane& plane, GLC_Point3d* pPoint) { const GLC_Vector3d n= plane.normal(); const GLC_Point3d p= line.startingPoint(); const GLC_Vector3d d= line.direction(); const double denominator= d * n; if (qFuzzyCompare(fabs(denominator), 0.0)) { qDebug() << " glc::lineIntersectPlane : Line parallel to the plane"; // The line is parallel to the plane return false; } else { // The line intersect the plane by one point const double t= -((n * p) + plane.coefD()) / denominator; (*pPoint)= p + (t * d); return true; } }
VoiceAnalyzer::VoiceAnalyzer(const QAudioFormat &format, QObject *parent): QIODevice(parent), m_format(format), m_frequency(0), m_position(0), m_fftHelper(new FastFourierTransformer(this)) { Q_ASSERT(qFuzzyCompare(M_SAMPLE_COUNT_MULTIPLIER, float(2)/(M_TWELTH_ROOT_OF_2 -1.0))); m_totalSampleCount = qRound(qreal(PrecisionPerNote) *TargetFrequencyParameter *M_SAMPLE_COUNT_MULTIPLIER); m_samples.reserve(m_totalSampleCount); int i = 2; int j = 1; for (; i < TargetFrequencyParameter; i *= 2) { j++; } m_maximumVoiceDifference = j*12; setCutOffPercentage(CutOffScaler); }
void CSceneWidget::onHideBoxsTriggerd(bool triggerd) { QListIterator<QGraphicsItem*> it(scene()->items()); while(it.hasNext()) { CGraphicsItem *gi = qgraphicsitem_cast<CGraphicsItem*>(it.next()); if(!qFuzzyCompare(gi->zValue(), qreal(0.0))) { gi->setEditMode(!triggerd); gi->setVisible(!triggerd); } } if(QAction *action = qobject_cast<QAction*>(sender())) { if(triggerd) action->setText(tr("Show boxs")); else action->setText(tr("Hide boxs")); } update(); }
/*! * \brief Draw an hightlight rectangle arround an item * * \param painter painter where the item is highlighted * \param rect The rectangular area to be drawn * \param pw Pen width of highlight rectangle drawn. * \param option The style option which contains palette and other information. */ void drawHighlightRect(QPainter *painter, QRectF rect, qreal pw, const QStyleOptionGraphicsItem *option) { const QRectF murect = painter->transform().mapRect(QRectF(0, 0, 1, 1)); if(qFuzzyCompare(qMax(murect.width(), murect.height()), qreal(0.0))) { return; } const QPen savePen = painter->pen(); const QBrush saveBrush = painter->brush(); const QRectF mbrect = painter->transform().mapRect(rect); if(qMin(mbrect.width(), mbrect.height()) < qreal(1.0)) { return; } qreal itemStrokeWidth = pw; const qreal pad = itemStrokeWidth / 2; const qreal strokeWidth = 0; // cosmetic pen const QColor fgcolor = option->palette.windowText().color(); const QColor bgcolor( // ensure good contrast against fgcolor fgcolor.red() > 127 ? 0 : 255, fgcolor.green() > 127 ? 0 : 255, fgcolor.blue() > 127 ? 0 : 255); rect.adjust(pad, pad, -pad, -pad); painter->setPen(QPen(bgcolor, strokeWidth, Qt::SolidLine)); painter->setBrush(Qt::NoBrush); painter->drawRect(rect); painter->setPen(QPen(option->palette.windowText(), 0, Qt::DashLine)); painter->setBrush(Qt::NoBrush); painter->drawRect(rect); painter->setPen(savePen); painter->setBrush(saveBrush); }
void GraphicsUtils::qt_graphicsItem_highlightSelected(QPainter *painter, const QStyleOptionGraphicsItem *option, const QRectF & boundingRect, const QPainterPath & path) { const QRectF murect = painter->transform().mapRect(QRectF(0, 0, 1, 1)); if (qFuzzyCompare(qMax(murect.width(), murect.height()) + 1, 1)) return; const QRectF mbrect = painter->transform().mapRect(boundingRect); if (qMin(mbrect.width(), mbrect.height()) < double(1.0)) return; double itemPenWidth = 1.0; const double pad = itemPenWidth / 2; const double penWidth = 0; // cosmetic pen const QColor fgcolor = option->palette.windowText().color(); const QColor bgcolor( // ensure good contrast against fgcolor fgcolor.red() > 127 ? 0 : 255, fgcolor.green() > 127 ? 0 : 255, fgcolor.blue() > 127 ? 0 : 255); painter->setPen(QPen(bgcolor, penWidth, Qt::SolidLine)); painter->setBrush(Qt::NoBrush); if (path.isEmpty()) { painter->drawRect(boundingRect.adjusted(pad, pad, -pad, -pad)); } else { painter->drawPath(path); } painter->setPen(QPen(option->palette.windowText(), 0, Qt::DashLine)); painter->setBrush(Qt::NoBrush); if (path.isEmpty()) { painter->drawRect(boundingRect.adjusted(pad, pad, -pad, -pad)); } else { painter->drawPath(path); } }
void TestQgsDistanceArea::basic() { QgsPoint p1( 1.0, 3.0 ), p2( -2.0, -1.0 ); QgsDistanceArea daA; double resultA, resultB, resultC; daA.setEllipsoid( GEO_NONE ); resultA = daA.measureLine( p1, p2 ); QCOMPARE( resultA, 5.0 ); // Now, on an ellipsoid. Always less? daA.setSourceCrs( 3006 ); daA.setEllipsoid( "WGS84" ); daA.setEllipsoidalMode( true ); resultA = daA.measureLine( p1, p2 ); QVERIFY( resultA < 5.0 ); // Test copy constructor QgsDistanceArea daB( daA ); resultB = daB.measureLine( p1, p2 ); QCOMPARE( resultA, resultB ); // Different Ellipsoid daB.setEllipsoid( "WGS72" ); resultB = daB.measureLine( p1, p2 ); QVERIFY( ! qFuzzyCompare( resultA, resultB ) ); // Test assignment QSharedPointer<QgsDistanceArea> daC( new QgsDistanceArea ); *daC = daB; resultC = daC->measureLine( p1, p2 ); QCOMPARE( resultB, resultC ); // Use parameter setting of ellipsoid radii (from WGS72 ) daA.setEllipsoid( 6378135.0, 6378135.0 - ( 6378135.0 / 298.26 ) ); resultA = daA.measureLine( p1, p2 ); QCOMPARE( resultA, resultB ); }
// Initialized the mover void GLC_SetTargetMover::init(const GLC_UserInput& userInput) { // Z Buffer component of selected point between 0 and 1 GLfloat Depth; // read selected point glReadPixels(userInput.x(), m_pViewport->viewVSize() - userInput.y() , 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &Depth); // Test if there is geometry under picking point if (!qFuzzyCompare(Depth, 1.0f)) { // Geometry find -> Update camera's target position const GLC_Point3d target(m_pViewport->unProject(userInput.x(), userInput.y())); m_pViewport->cameraHandle()->setTargetCam(target); } else { // Geometry not find -> panning const GLC_Point3d curPos(m_pViewport->mapPosMouse(userInput.x(), userInput.y())); const GLC_Point3d prevPos(m_pViewport->mapPosMouse(m_pViewport->viewHSize() / 2, m_pViewport->viewVSize() / 2)); const GLC_Vector3d VectPan(curPos - prevPos); // panning vector // pan camera m_pViewport->cameraHandle()->pan(VectPan); } }
bool VariableDesc::goodGainOffsetTest(const VariableDesc& var) { DEBUG_FUNC_NAME const QString conversionType = var.conversionType(); qreal aValue = var.aValue(); qreal bValue = var.bValue(); // zero-full scale if (conversionType == getVARIABLE_CONVERSION_TYPE_STRING_0()) { return !qFuzzyCompare(aValue, bValue); } // gain-offset else if (conversionType == getVARIABLE_CONVERSION_TYPE_STRING_1()) { return (aValue != 0.0); } else { return true; } }
void StretchHeaderView::NormaliseWidths(const QList<int>& sections) { if (!stretch_enabled_) return; const ColumnWidthType total_sum = std::accumulate(column_widths_.begin(), column_widths_.end(), 0.0); ColumnWidthType selected_sum = total_sum; if (!sections.isEmpty()) { selected_sum = 0.0; for (int i=0 ; i<count() ; ++i) if (sections.contains(i)) selected_sum += column_widths_[i]; } if (total_sum != 0.0 && !qFuzzyCompare(total_sum, 1.0)) { const ColumnWidthType mult = (selected_sum + (1.0 - total_sum)) / selected_sum; for (int i=0 ; i<column_widths_.count() ; ++i) { if (sections.isEmpty() || sections.contains(i)) column_widths_[i] *= mult; } } }
bool OsmAnd::CoreResourcesEmbeddedBundle_P::containsResource(const QString& name, const float displayDensityFactor) const { const auto citResourceEntry = _resources.constFind(name); if (citResourceEntry == _resources.cend()) return false; const auto& resourceEntry = *citResourceEntry; auto itByDisplayDensityFactor = iteratorOf(constOf(resourceEntry.variantsByDisplayDensityFactor)); while (itByDisplayDensityFactor.hasNext()) { const auto byDisplayDensityFactorEntry = itByDisplayDensityFactor.next(); const auto& testDisplayDensityFactor = byDisplayDensityFactorEntry.key(); if (qFuzzyCompare(displayDensityFactor, testDisplayDensityFactor) || testDisplayDensityFactor >= displayDensityFactor || !itByDisplayDensityFactor.hasNext()) { return true; } } return false; }
QStringList CSceneWidget::apply() { QStringList list; QListIterator<QGraphicsItem*> it(scene()->items()); while(it.hasNext()) { CGraphicsItem *gi = qgraphicsitem_cast<CGraphicsItem*>(it.next()); if(!qFuzzyCompare(gi->zValue(), qreal(0.0))) // ignore first item, first item is background { gi->setEditMode(false); list.push_back(QString("x=%1%,y=%2%,w=%3%,h=%4%"). arg(gi->pos().x()/scene()->sceneRect().width()*100). arg(gi->pos().y()/scene()->sceneRect().height()*100). arg(gi->imageSize().width()/scene()->sceneRect().width()*100). arg(gi->imageSize().height()/scene()->sceneRect().height()*100)); } } onHideBoxsTriggerd(true); return list; }
void tst_QRawFont::advances() { QFETCH(QFont::HintingPreference, hintingPreference); QRawFont font(QLatin1String(SRCDIR "testfont.ttf"), 10, hintingPreference); QVERIFY(font.isValid()); QRawFontPrivate *font_d = QRawFontPrivate::get(font); QVERIFY(font_d->fontEngine != 0); QVector<quint32> glyphIndices; glyphIndices << 44 << 83 << 83 << 70 << 69 << 86; // "Foobar" bool supportsSubPixelPositions = font_d->fontEngine->supportsSubPixelPositions(); QVector<QPointF> advances = font.advancesForGlyphIndexes(glyphIndices); for (int i=0; i<glyphIndices.size(); ++i) { QVERIFY(qFuzzyCompare(qRound(advances.at(i).x()), 8.0)); if (supportsSubPixelPositions) QVERIFY(advances.at(i).x() > 8.0); QVERIFY(qFuzzyIsNull(advances.at(i).y())); } }
QImage UCScalingImageProvider::requestImage(const QString &id, QSize *size, const QSize &requestedSize) { Q_UNUSED(requestedSize); int separatorPosition = id.indexOf("/"); float scaleFactor = id.left(separatorPosition).toFloat(); QString path = id.mid(separatorPosition+1); QFile file(path); if (file.open(QIODevice::ReadOnly)) { QImage image; QImageReader imageReader(&file); if (!qFuzzyCompare(scaleFactor, (float)1.0)) { QSize realSize = imageReader.size(); imageReader.setScaledSize(realSize * scaleFactor); } imageReader.read(&image); *size = image.size(); return image; } else { return QImage(); } }
bool TemplateEngine::evaluateBooleanJavaScriptExpression(QJSEngine &engine, const QString &expression, bool *result, QString *errorMessage) { if (errorMessage) errorMessage->clear(); if (result) *result = false; const QJSValue value = engine.evaluate(expression); if (value.isError()) { if (errorMessage) *errorMessage = QString::fromLatin1("Error in \"%1\": %2") .arg(expression, value.toString()); return false; } // Try to convert to bool, be that an int or whatever. if (value.isBool()) { if (result) *result = value.toBool(); return true; } if (value.isNumber()) { if (result) *result = !qFuzzyCompare(value.toNumber(), 0); return true; } if (value.isString()) { if (result) *result = !value.toString().isEmpty(); return true; } if (errorMessage) *errorMessage = QString::fromLatin1("Cannot convert result of \"%1\" (\"%2\"to bool.") .arg(expression, value.toString()); return false; }
void XFloatWidget::setValue( qreal in ) { if( !_settingValue ) { if( in > maximum() ) { in = maximum(); } if( in < minimum() ) { in = minimum(); } _settingValue = true; if( !qFuzzyCompare( in, _spinner->value() ) ) { _spinner->setValue( in ); } setSliderFromValue( in ); emit valueChanged( this ); emit valueChanged( _spinner->value() ); _settingValue = false; } }
void VolumeEffectFilter::treatOneSamplePerChannel(BYTE **buffer, int sampleSize, int channelCount, int frequency) { float volume = m_volumeEffect->volume(); if (m_volumeEffect->m_fading) { const qreal lastSample = m_volumeEffect->m_fadeDuration * frequency / 1000; const qreal completed = qreal(m_volumeEffect->m_fadeSamplePosition++) / lastSample; if (qFuzzyCompare(completed, qreal(1.))) { m_volumeEffect->setVolume(m_volumeEffect->m_targetVolume); m_volumeEffect->m_fading = false; //we end the fading effect } else { volume = m_volumeEffect->m_fadeCurveFn(m_volumeEffect->m_initialVolume, m_volumeEffect->m_targetVolume - m_volumeEffect->m_initialVolume, completed); } } for(int c = 0; c < channelCount; ++c) { switch (sampleSize) { case 2: { short *shortBuffer = reinterpret_cast<short*>(*buffer); *shortBuffer *= qRound(volume); } break; case 1: **buffer *= qRound(volume); break; default: break; } *buffer += sampleSize; } }
void ShapeVisitor_RestrictedPositionGetter::visit( Shape_Plane& shape ) { float t; float m = - shape.getD() - shape.getNormalVector().x() * mOriginalPosition.x() - shape.getNormalVector().y() * mOriginalPosition.y() - shape.getNormalVector().z() * mOriginalPosition.z(); double shapeX= static_cast<double>( shape.getNormalVector().x() ); double shapeY= static_cast<double>( shape.getNormalVector().y() ); double shapeZ= static_cast<double>( shape.getNormalVector().z() ); double n = pow( shapeX, 2.0 ) + pow( shapeY, 2.0 ) + pow( shapeZ, 2.0 ); if ( !qFuzzyCompare( n,0.0 ) ) //if (n != 0.0) { t = m / static_cast<float>( n ); } else { t = 0.f; } mRestrictedPosition = osg::Vec3f( mOriginalPosition.x() + t * shape.getNormalVector().x(), mOriginalPosition.y() + t * shape.getNormalVector().y(), mOriginalPosition.z() + t * shape.getNormalVector().z() ); }
/* * ChordLengthParameterize : * Assign parameter values to digitized points * using relative distances between points. */ static qreal *ChordLengthParameterize(const QList<QPointF> &points, int first, int last) { int i; qreal *u; /* Parameterization */ u = new qreal[(last-first+1)]; u[0] = 0.0; for (i = first + 1; i <= last; ++i) { u[i-first] = u[i-first-1] + distance(points.at(i), points.at(i - 1)); } qreal denominator = u[last-first]; if (qFuzzyCompare(denominator, qreal(0.0))) { denominator = Zero; } for (i = first + 1; i <= last; ++i) { u[i-first] = u[i-first] / denominator; } return(u); }
void GraphicEdge::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) { if (!source || !dest) return; QLineF line(sourcePoint, destPoint); if (qFuzzyCompare(line.length(), qreal(0.))) return; painter->setPen(QPen(Qt::black, 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); painter->drawLine(line); double angle = ::acos(line.dx() / line.length()); if (line.dy() >= 0) angle = TwoPi - angle; QPointF destArrowP1 = destPoint + QPointF(sin(angle - Pi / 3) * arrowSize, cos(angle - Pi / 3) * arrowSize); QPointF destArrowP2 = destPoint + QPointF(sin(angle - Pi + Pi / 3) * arrowSize, cos(angle - Pi + Pi / 3) * arrowSize); painter->setBrush(Qt::black); painter->drawPolygon(QPolygonF() << line.p2() << destArrowP1 << destArrowP2); }
void Geometry::appendSmooth( const QVector3D &a, const QVector3D &n, int from ) { // Smooth normals are acheived by averaging the normals for faces meeting // at a point. First find the point in geometry already generated // (working backwards, since most often the points shared are between faces // recently added). int v = vertices.count() - 1; for (; v >= from; --v) if (qFuzzyCompare( vertices[v], a )) break; if (v < from) { // The vert was not found so add it as a new one, and initialize // its corresponding normal v = vertices.count(); vertices.append( a ); normals.append( n ); } else { // Vert found, accumulate normals into corresponding normal slot. // Must call finalize once finished accumulating normals normals[v] += n; } // In both cases (found or not) reference the vert via its index faces.append( v ); }
QByteArray OsmAnd::CoreResourcesEmbeddedBundle_P::getResource(const QString& name, const float displayDensityFactor, bool* ok /*= nullptr*/) const { const auto citResourceEntry = _resources.constFind(name); if (citResourceEntry == _resources.cend()) { if (ok) *ok = false; return QByteArray(); } const auto& resourceEntry = *citResourceEntry; auto itByDisplayDensityFactor = iteratorOf(constOf(resourceEntry.variantsByDisplayDensityFactor)); while (itByDisplayDensityFactor.hasNext()) { const auto byDisplayDensityFactorEntry = itByDisplayDensityFactor.next(); const auto& testDisplayDensityFactor = byDisplayDensityFactorEntry.key(); const auto& resourceData = byDisplayDensityFactorEntry.value(); if (qFuzzyCompare(displayDensityFactor, testDisplayDensityFactor) || testDisplayDensityFactor >= displayDensityFactor || !itByDisplayDensityFactor.hasNext()) { if (ok) *ok = true; if (!name.endsWith(QString(".png"))) return qUncompress(resourceData.data, resourceData.size); else { return QByteArray(reinterpret_cast<const char*>(resourceData.data) + 4, resourceData.size - 4); } } } if (ok) *ok = false; return QByteArray(); }
void MCObjectTest::testRotate() { MCObject object("TestObject"); QVERIFY(qFuzzyCompare(object.angle(), MCFloat(0.0))); object.rotate(90); QVERIFY(qFuzzyCompare(object.angle(), MCFloat(90))); MCWorld world; MCShapePtr shape(new MCRectShape(nullptr, 10, 10)); object.setShape(shape); object.rotate(45); QVERIFY(qFuzzyCompare(object.angle(), MCFloat(45))); QVERIFY(qFuzzyCompare(shape->angle(), MCFloat(45))); object.addToWorld(); object.rotate(22); QVERIFY(qFuzzyCompare(object.angle(), MCFloat(22))); QVERIFY(qFuzzyCompare(shape->angle(), MCFloat(22))); }
void QGstreamerPlayerSession::busMessage(const QGstreamerMessage &message) { GstMessage* gm = message.rawMessage(); if (gm == 0) { // Null message, query current position quint32 newPos = position(); if (newPos/1000 != m_lastPosition) { m_lastPosition = newPos/1000; emit positionChanged(newPos); } double volume = 1.0; g_object_get(G_OBJECT(m_playbin), "volume", &volume, NULL); if (m_volume != int(volume*100)) { m_volume = int(volume*100); emit volumeChanged(m_volume); } } else { //tag message comes from elements inside playbin, not from playbin itself if (GST_MESSAGE_TYPE(gm) == GST_MESSAGE_TAG) { //qDebug() << "tag message"; GstTagList *tag_list; gst_message_parse_tag(gm, &tag_list); gst_tag_list_foreach(tag_list, addTagToMap, &m_tags); //qDebug() << m_tags; emit tagsChanged(); } if (GST_MESSAGE_SRC(gm) == GST_OBJECT_CAST(m_playbin)) { switch (GST_MESSAGE_TYPE(gm)) { case GST_MESSAGE_STATE_CHANGED: { GstState oldState; GstState newState; GstState pending; gst_message_parse_state_changed(gm, &oldState, &newState, &pending); #ifdef DEBUG_PLAYBIN QStringList states; states << "GST_STATE_VOID_PENDING" << "GST_STATE_NULL" << "GST_STATE_READY" << "GST_STATE_PAUSED" << "GST_STATE_PLAYING"; qDebug() << QString("state changed: old: %1 new: %2 pending: %3") \ .arg(states[oldState]) \ .arg(states[newState]) \ .arg(states[pending]); #endif switch (newState) { case GST_STATE_VOID_PENDING: case GST_STATE_NULL: setSeekable(false); finishVideoOutputChange(); if (m_state != QMediaPlayer::StoppedState) emit stateChanged(m_state = QMediaPlayer::StoppedState); break; case GST_STATE_READY: setSeekable(false); if (m_state != QMediaPlayer::StoppedState) emit stateChanged(m_state = QMediaPlayer::StoppedState); break; case GST_STATE_PAUSED: { QMediaPlayer::State prevState = m_state; m_state = QMediaPlayer::PausedState; //check for seekable if (oldState == GST_STATE_READY) { getStreamsInfo(); updateVideoResolutionTag(); /* //gst_element_seek_simple doesn't work reliably here, have to find a better solution GstFormat format = GST_FORMAT_TIME; gint64 position = 0; bool seekable = false; if (gst_element_query_position(m_playbin, &format, &position)) { seekable = gst_element_seek_simple(m_playbin, format, GST_SEEK_FLAG_NONE, position); } setSeekable(seekable); */ setSeekable(true); if (!qFuzzyCompare(m_playbackRate, qreal(1.0))) { qreal rate = m_playbackRate; m_playbackRate = 1.0; setPlaybackRate(rate); } } if (m_state != prevState) emit stateChanged(m_state); break; } case GST_STATE_PLAYING: if (m_state != QMediaPlayer::PlayingState) emit stateChanged(m_state = QMediaPlayer::PlayingState); break; } } break; case GST_MESSAGE_EOS: emit playbackFinished(); break; case GST_MESSAGE_TAG: case GST_MESSAGE_STREAM_STATUS: case GST_MESSAGE_UNKNOWN: break; case GST_MESSAGE_ERROR: { GError *err; gchar *debug; gst_message_parse_error (gm, &err, &debug); emit error(int(QMediaPlayer::ResourceError), QString::fromUtf8(err->message)); qWarning() << "Error:" << QString::fromUtf8(err->message); g_error_free (err); g_free (debug); } break; case GST_MESSAGE_WARNING: { GError *err; gchar *debug; gst_message_parse_warning (gm, &err, &debug); qWarning() << "Warning:" << QString::fromUtf8(err->message); g_error_free (err); g_free (debug); } break; case GST_MESSAGE_INFO: #ifdef DEBUG_PLAYBIN { GError *err; gchar *debug; gst_message_parse_info (gm, &err, &debug); qDebug() << "Info:" << QString::fromUtf8(err->message); g_error_free (err); g_free (debug); } #endif break; case GST_MESSAGE_BUFFERING: { int progress = 0; gst_message_parse_buffering(gm, &progress); emit bufferingProgressChanged(progress); } break; case GST_MESSAGE_STATE_DIRTY: case GST_MESSAGE_STEP_DONE: case GST_MESSAGE_CLOCK_PROVIDE: case GST_MESSAGE_CLOCK_LOST: case GST_MESSAGE_NEW_CLOCK: case GST_MESSAGE_STRUCTURE_CHANGE: case GST_MESSAGE_APPLICATION: case GST_MESSAGE_ELEMENT: break; case GST_MESSAGE_SEGMENT_START: { const GstStructure *structure = gst_message_get_structure(gm); qint64 position = g_value_get_int64(gst_structure_get_value(structure, "position")); position /= 1000000; m_lastPosition = position; emit positionChanged(position); } break; case GST_MESSAGE_SEGMENT_DONE: break; case GST_MESSAGE_DURATION: { GstFormat format = GST_FORMAT_TIME; gint64 duration = 0; if (gst_element_query_duration(m_playbin, &format, &duration)) { int newDuration = duration / 1000000; if (m_duration != newDuration) { m_duration = newDuration; emit durationChanged(m_duration); } } } break; case GST_MESSAGE_LATENCY: #if (GST_VERSION_MAJOR >= 0) && (GST_VERSION_MINOR >= 10) && (GST_VERSION_MICRO >= 13) case GST_MESSAGE_ASYNC_START: case GST_MESSAGE_ASYNC_DONE: #if GST_VERSION_MICRO >= 23 case GST_MESSAGE_REQUEST_STATE: #endif #endif case GST_MESSAGE_ANY: break; default: break; } } else if (m_videoSink && m_renderer && GST_MESSAGE_SRC(gm) == GST_OBJECT_CAST(m_videoSink) && GST_MESSAGE_TYPE(gm) == GST_MESSAGE_STATE_CHANGED) { GstState oldState; GstState newState; gst_message_parse_state_changed(gm, &oldState, &newState, 0); if (oldState == GST_STATE_READY && newState == GST_STATE_PAUSED) m_renderer->precessNewStream(); } } }
bool UIDisplayBase::CanHandleVideoRate(double Rate, int &ModeIndex) { // can handle anything if (m_variableRefreshRate) return true; // avoid repeated checks if (qFuzzyCompare(Rate + 1.0f, m_lastRateChecked + 1.0f)) return false; m_lastRateChecked = Rate; // TODO try and find a better rate when the current rate is below the video frame rate // Pick the most suitable rate from those available // 1. higher is better // 2. exact multiple is better // 3. progressive is better than interlaced (we can't guarantee tv interlacing will work) // 4. something in the range 50-60Hz is optimal for UI LOG(VB_GENERAL, LOG_INFO, QString("Trying to find best match for frame rate %1").arg(Rate)); int best = 0; int index = -1; QList<int> scores; for (int i = 0; i < m_modes.size(); ++i) { int score = 0; double rate = m_modes[i].m_rate; // optimum range if (rate > 49.0f && rate < 61.0f) score += 5; // less desirable if (m_modes[i].m_interlaced) score -= 3; // exact match if (qFuzzyCompare(Rate + 1.0f, rate + 1.0f)) { score += 15; } // multiple else if (qFuzzyCompare((double)1.0f, fmod(rate, Rate) + 1.0f)) { score += 15; } // try to account for 29.97/30.00 and 23.97/24.00 differences else if (abs(rate - Rate) < 0.05f) { score += 10; } else if (fmod(rate, Rate) < 0.01f) { score += 10; } // avoid dropping frames if (rate < (Rate - 0.05f)) score -= 10; if (score > best) { best = score; index = i; } LOG(VB_GUI, LOG_INFO, QString("Rate: %1Hz%2 Score %3 Index %4") .arg(m_modes[i].m_rate).arg(m_modes[i].m_interlaced ? QString(" Interlaced") : "") .arg(score).arg(m_modes[i].m_index)); } if (best < 1) { LOG(VB_GENERAL, LOG_INFO, "Failed to find suitable rate"); return false; } LOG(VB_GENERAL, LOG_INFO, QString("Best mode %1Hz%2 (Index %3)") .arg(m_modes[index].m_rate).arg(m_modes[index].m_interlaced ? QString(" Interlaced") : "") .arg(m_modes[index].m_index)); ModeIndex = index; return true; }