コード例 #1
0
ファイル: cylinder.cpp プロジェクト: snake10/sickle
QVector<GLfloat> calcCylinderVertices() {
	QVector<GLfloat> vertices;
	vertices.reserve(sides* 4 * 3);

	qreal theta = 0;
	for (int j = 0; j < sides; j++) {
		for(int i = 0; i < 2; i++) {
			vertices.append(qCos(theta));
			vertices.append(1.0f);
			vertices.append(qSin(theta));

			vertices.append(qCos(theta));
			vertices.append(-1.0f);
			vertices.append(qSin(theta));
		}

		theta += (2 * M_PI) / sides;
	}

	return vertices;
}
コード例 #2
0
ファイル: store.cpp プロジェクト: KDE/akonadi
bool Store::deleteFlags(const PimItem::List &items, const QSet<QByteArray> &flags, bool &flagsChanged)
{
    DataStore *store = connection()->storageBackend();

    QVector<Flag> flagList;
    flagList.reserve(flags.size());
    for (auto iter = flags.cbegin(), end = flags.cend(); iter != end; ++iter) {
        Flag flag = Flag::retrieveByName(QString::fromUtf8(*iter));
        if (!flag.isValid()) {
            continue;
        }

        flagList.append(flag);
    }

    if (!store->removeItemsFlags(items, flagList, &flagsChanged)) {
        qCDebug(AKONADISERVER_LOG) << "Store::deleteFlags: Unable to remove item flags";
        return false;
    }
    return true;
}
コード例 #3
0
QVector<QString> CDisplaySettingsPage::bookNameAbbreviationsTryVector() {
    QVector<QString> atv;
    atv.reserve(4);
    {
        QString settingsLanguage = btConfig().value<QString>("GUI/booknameLanguage");
        if (!settingsLanguage.isEmpty())
            atv.append(settingsLanguage);
    }
    {
        const QString localeLanguageAndCountry = QLocale::system().name();
        if (!localeLanguageAndCountry.isEmpty()) {
            atv.append(localeLanguageAndCountry);
            int i = localeLanguageAndCountry.indexOf('_');
            if (i > 0)
                atv.append(localeLanguageAndCountry.left(i));
        }
    }
    BT_ASSERT(CLanguageMgr::instance()->languageForAbbrev("en_US"));
    atv.append("en_US");
    return atv;
}
コード例 #4
0
    void ArtworksRepository::cleanupEmptyDirectories() {
        LOG_DEBUG << "#";
        int count = m_DirectoriesList.length();
        QVector<int> indicesToRemove;
        indicesToRemove.reserve(count);

        for (int i = 0; i < count; ++i) {
            const QString &directory = m_DirectoriesList[i];
            if (m_DirectoriesHash[directory] == 0) {
                indicesToRemove.append(i);
            }
        }

        if (!indicesToRemove.isEmpty()) {
            LOG_INFO << indicesToRemove.length() << "empty directory(ies)...";

            QVector<QPair<int, int> > rangesToRemove;
            Helpers::indicesToRanges(indicesToRemove, rangesToRemove);
            removeItemsAtIndices(rangesToRemove);
        }
    }
コード例 #5
0
ファイル: tabwidget.cpp プロジェクト: RavenB/CopyQ
void TabWidget::onTabsMoved(const QString &oldPrefix, const QString &newPrefix, const QList<int> &indexes)
{
    const int newCurrentIndex = indexes.indexOf(currentIndex());
    Q_ASSERT(newCurrentIndex != -1);

    m_stackedWidget->hide();

    QVector<QWidget*> widgets;
    widgets.reserve(m_stackedWidget->count());

    while ( m_stackedWidget->count() > 0 ) {
        QWidget *w = m_stackedWidget->widget(0);
        widgets.append(w);
        m_stackedWidget->removeWidget(w);
    }

    foreach (int index, indexes) {
        Q_ASSERT(index >= 0);
        Q_ASSERT(index < widgets.count());
        m_stackedWidget->insertWidget(-1, widgets[index]);
    }
コード例 #6
0
ファイル: qgsogrdataitems.cpp プロジェクト: rhurlin/QGIS
QVector<QgsDataItem*> QgsOgrDataCollectionItem::createChildren()
{
  QVector<QgsDataItem*> children;

  OGRSFDriverH hDriver;
  OGRDataSourceH hDataSource = OGROpen( TO8F( mPath ), false, &hDriver );
  if ( !hDataSource )
    return children;
  int numLayers = OGR_DS_GetLayerCount( hDataSource );

  children.reserve( numLayers );
  for ( int i = 0; i < numLayers; ++i )
  {
    QgsOgrLayerItem* item = dataItemForLayer( this, QString(), mPath, hDataSource, i );
    children.append( item );
  }

  OGR_DS_Destroy( hDataSource );

  return children;
}
コード例 #7
0
QVector<ShaderAttribute> QGraphicsHelperGL4::programAttributesAndLocations(GLuint programId)
{
    QVector<ShaderAttribute> attributes;
    GLint nbrActiveAttributes = 0;
    m_funcs->glGetProgramiv(programId, GL_ACTIVE_ATTRIBUTES, &nbrActiveAttributes);
    attributes.reserve(nbrActiveAttributes);
    char attributeName[256];
    for (GLint i = 0; i < nbrActiveAttributes; i++) {
        ShaderAttribute attribute;
        GLsizei attributeNameLength = 0;
        // Size is 1 for scalar and more for struct or arrays
        // Type is the GL Type
        m_funcs->glGetActiveAttrib(programId, i, sizeof(attributeName) - 1, &attributeNameLength,
                                   &attribute.m_size, &attribute.m_type, attributeName);
        attributeName[sizeof(attributeName) - 1] = '\0';
        attribute.m_location = m_funcs->glGetAttribLocation(programId, attributeName);
        attribute.m_name = QString::fromUtf8(attributeName, attributeNameLength);
        attributes.append(attribute);
    }
    return attributes;
}
コード例 #8
0
ファイル: vconfigmanager.cpp プロジェクト: liunianbanbo/vnote
QVector<QString> VConfigManager::getNoteTemplates(DocType p_type) const
{
    QVector<QString> res;
    QDir dir(getTemplateConfigFolder());
    if (!dir.exists()) {
        dir.mkpath(getTemplateConfigFolder());
        return res;
    }

    dir.setFilter(QDir::Files | QDir::NoSymLinks);
    QStringList files = dir.entryList();
    res.reserve(files.size());
    for (auto const &item : files) {
        if (p_type == DocType::Unknown
            || p_type == VUtils::docTypeFromName(item)) {
            res.push_back(item);
        }
    }

    return res;
}
コード例 #9
0
    void SpellCheckerService::submitItems(const QVector<ISpellCheckable *> &itemsToCheck) {
        if (!m_WorkerIsAlive) { return; }

        if (m_SpellCheckWorker != NULL && !m_SpellCheckWorker->isCancelled()) {
            QVector<SpellCheckItemBase *> items;
            int length = itemsToCheck.length();

            items.reserve(length);

            for (int i = 0; i < length; ++i) {
                SpellCheck::ISpellCheckable *itemToCheck = itemsToCheck.at(i);
                SpellCheckItem *item = new SpellCheckItem(itemToCheck, Common::SpellCheckAll);
                itemToCheck->connectSignals(item);
                items.append(item);
            }

            qInfo() << "SpellCheck service: about to submit" << length << "items";

            m_SpellCheckWorker->submitItems(items);
            m_SpellCheckWorker->submitItem(new SpellCheckSeparatorItem());
        }
    }
コード例 #10
0
void StateMachineViewerServer::stateSelectionChanged()
{
    const QModelIndexList &selection = m_stateSelectionModel->selectedRows();
    qDebug() << selection;
    QVector<State> filter;
    filter.reserve(selection.size());
    foreach (const QModelIndex &index, selection) {
        State state = index.data(StateModel::StateValueRole).value<State>();
        bool addState = true;
        /// only pick the top-level items of the selection
        // NOTE: this might be slow for large selections, if someone wants to come up with a better
        // algorithm, please - go for it!
        foreach (State potentialParent, filter) {
            if (selectedStateMachine()->isDescendantOf(potentialParent, state)) {
                addState = false;
                break;
            }
        }

        if (addState)
            filter << state;
    }
コード例 #11
0
ファイル: cylinder.cpp プロジェクト: snake10/sickle
QVector<GLfloat> calcCylinderUVs() {
	QVector<GLfloat> UVs;
	UVs.reserve(sides * 4 * 2);

	qreal theta = 0;
	for (int j = 0; j < sides; j++) {
		for(int i = 0; i < 2; i++) {
			UVs.append(i);
			UVs.append(static_cast<float>(j) / sides);
		}

		UVs.append(qCos(theta));
		UVs.append(qSin(theta));

		UVs.append(qCos(theta));
		UVs.append(qSin(theta));

		theta += (2 * M_PI) / sides;
	}

	return UVs;
}
コード例 #12
0
ファイル: handlerhelper.cpp プロジェクト: KDE/akonadi
Protocol::FetchCollectionsResponse HandlerHelper::fetchCollectionsResponse(const Collection &col,
                                                                           const CollectionAttribute::List &attrs,
                                                                           bool includeStatistics,
                                                                           int ancestorDepth,
                                                                           const QStack<Collection> &ancestors,
                                                                           const QStack<CollectionAttribute::List> &ancestorAttributes,
                                                                           bool isReferenced,
                                                                           const QStringList &mimeTypes)
{
    Protocol::FetchCollectionsResponse response(col.id());
    response.setParentId(col.parentId());
    response.setName(col.name());
    response.setMimeTypes(mimeTypes);
    response.setRemoteId(col.remoteId());
    response.setRemoteRevision(col.remoteRevision());
    response.setResource(col.resource().name());
    response.setIsVirtual(col.isVirtual());

    if (includeStatistics) {
        const CollectionStatistics::Statistics stats = CollectionStatistics::self()->statistics(col);
        if (stats.count > -1) {
            Protocol::FetchCollectionStatsResponse statsResponse(stats.count,
                                                                 stats.count - stats.read,
                                                                 stats.size);
            response.setStatistics(statsResponse);
        }
    }

    if (!col.queryString().isEmpty()) {
        response.setSearchQuery(col.queryString());
        QVector<qint64> searchCols;
        const QStringList searchColIds = col.queryCollections().split(QLatin1Char(' '));
        searchCols.reserve(searchColIds.size());
        Q_FOREACH (const QString &searchColId, searchColIds) {
            searchCols << searchColId.toLongLong();
        }
        response.setSearchCollections(searchCols);
    }
コード例 #13
0
ファイル: connection.cpp プロジェクト: PZSAS/serv
void Connection::handleWithSamples()
{
    QVector<quint8> newSamples;
    int i, count, size;
    int freq = FREQ;
    qint64 sum;

    if(channel == MIC) freq = MIC_FREQ; // mikrofon

    sum = 0;
    size = rawSamples.size();
    newSamples.reserve(INTERVAL);
    count = qRound(SAMPLES_PER_SEC/freq); // po ile uśredniać

    for(i=0;i<size;i++)
    {
        sum += rawSamples[i];
        if((i % count) == (count-1))
        {
            newSamples.append(qRound((float)sum / (float)count));
            sum = 0;
        }
    }
    if((i%count) > count/2)
    {
        newSamples.append(qRound((float)sum / (float)(i%count)));
    }

    samples << newSamples;

    size = newSamples.size();
    for(i=0;i<size;i++)
    {
        ++ln;
        ln = ln & Nmask;
        lastSamples[ln] = newSamples[i];
    }
}
コード例 #14
0
void BackgroundFinder::addFrame(const QImage &img)
{
    if (_rolling.isEmpty())
    {
        for (int i = 0; i < img.width() * img.height(); i++)
        {
            _rolling.append(RollingMedianCalculator());
        }
    }


    QVector<QFuture<QRgb> > futures;
    futures.reserve(img.width() * img.height());
    for (int y = 0; y < img.height(); y++)
    {
        for (int x = 0; x < img.width(); x++)
        {
            const int index = y * img.width() + x;
            QFuture<QRgb> future = QtConcurrent::run(&_rolling[index],
                                                     &RollingMedianCalculator::next,
                                                     img.pixel(x,y));
            futures.append(future);
        }
    }

    QImage newBG(img.size(), img.format());
    for (int y = 0; y < img.height(); y++)
    {
        for (int x = 0; x < img.width(); x++)
        {
            const int index = y * img.width() + x;
            futures[index].waitForFinished();
            newBG.setPixel(x,y, futures.at(index).result());
        }
    }

    _bg = newBG;
}
コード例 #15
0
ファイル: qgsgeometryfactory.cpp プロジェクト: alexbruy/QGIS
std::unique_ptr<QgsPolygon> QgsGeometryFactory::fromPolygonXY( const QgsPolygonXY &polygon )
{
  std::unique_ptr< QgsPolygon > poly = qgis::make_unique< QgsPolygon >();

  QVector<QgsCurve *> holes;
  holes.reserve( polygon.size() );
  for ( int i = 0; i < polygon.size(); ++i )
  {
    std::unique_ptr< QgsLineString > l = linestringFromPolyline( polygon.at( i ) );
    l->close();

    if ( i == 0 )
    {
      poly->setExteriorRing( l.release() );
    }
    else
    {
      holes.push_back( l.release() );
    }
  }
  poly->setInteriorRings( holes );
  return poly;
}
コード例 #16
0
ファイル: RTSender.cpp プロジェクト: ilpropheta/anvedi
void RTSender::SendData(int count)
{
	map<QString, QVector<qreal>> sliceToSend;
	for (const auto& elem : dataToSend)
	{
		QVector<qreal> data; data.reserve(count);
		for (auto i = 0; i < count && (currentSampleIdx + i < elem.second.size()); ++i)
		{
			data.push_back(elem.second.at(currentSampleIdx + i));
		}
		sliceToSend.emplace(elem.first, std::move(data));
	}
	currentSampleIdx += count;
	if (!sliceToSend.begin()->second.empty())
	{
		receiver.addValues(sliceToSend);
		emit DataSent();
	}
	else
	{
		emit NoMoreData();
	}
}
コード例 #17
0
    bool BasicKeywordsModel::removeKeywordsUnsafe(const QSet<QString> &keywordsToRemove, bool caseSensitive) {
        int size = m_KeywordsList.size();

        QVector<int> indicesToRemove;
        indicesToRemove.reserve(size/2);

        for (int i = 0; i < size; ++i) {
            QString keyword = m_KeywordsList.at(i);

            if (!caseSensitive) {
                keyword = keyword.toLower();
            }

            if (keywordsToRemove.contains(keyword)) {
                indicesToRemove.append(i);
            }
        }

        bool anythingRemoved = !indicesToRemove.empty();
        removeKeywordsAtIndicesUnsafe(indicesToRemove);

        return anythingRemoved;
    }
コード例 #18
0
ファイル: qgslabelsearchtree.cpp プロジェクト: exlimit/QGIS
bool QgsLabelSearchTree::insertLabel( pal::LabelPosition *labelPos, int featureId, const QString &layerName, const QString &labeltext, const QFont &labelfont, bool diagram, bool pinned, const QString &providerId )
{
  if ( !labelPos )
  {
    return false;
  }

  double c_min[2];
  double c_max[2];
  labelPos->getBoundingBox( c_min, c_max );

  QVector<QgsPointXY> cornerPoints;
  cornerPoints.reserve( 4 );
  for ( int i = 0; i < 4; ++i )
  {
    cornerPoints.push_back( QgsPointXY( labelPos->getX( i ), labelPos->getY( i ) ) );
  }
  QgsLabelPosition *newEntry = new QgsLabelPosition( featureId, labelPos->getAlpha(), cornerPoints, QgsRectangle( c_min[0], c_min[1], c_max[0], c_max[1] ),
      labelPos->getWidth(), labelPos->getHeight(), layerName, labeltext, labelfont, labelPos->getUpsideDown(), diagram, pinned, providerId );
  mSpatialIndex.Insert( c_min, c_max, newEntry );
  mOwnedPositions << newEntry;
  return true;
}
コード例 #19
0
ファイル: meshcomplex.cpp プロジェクト: putanowr/MeshComplex
void MeshComplex::addGraphicsCell_(moab::EntityHandle handle) {
  double coords[3];
  moab::Range vertices;
  myMeshDB_->get_connectivity (&handle,1, vertices);
  auto nv = vertices.size();
  std::vector<double> x(nv);
  std::vector<double> y(nv);
  myMeshDB_->get_coords(vertices, &(x[0]), &(y[0]), nullptr);
  QVector<QPointF> points;
  points.reserve(2*nv);
  for (auto && tup : zip(x,y)) {
    double px,py;
    boost::tie(px,py) = tup;
    points.push_back(QPointF(px,py));
  }
  points.push_back(QPointF(x[0], y[0]));
  GraphicsCell *c = new GraphicsCell(points);
  myGraphics_->addToGroup(c);
  //void *data[] = {n};
  //auto retval = myMeshDB_->tag_set_data(myGraphicsNodesTag_, &handle, 1, data);
  //checkDB_(retval);
  qDebug() << "Drawing cell";
}
コード例 #20
0
void Core::Internal::runSearch(QFutureInterface<Core::LocatorFilterEntry> &future,
                               const QList<ILocatorFilter *> &filters, const QString &searchText)
{
    QSet<LocatorFilterEntry> alreadyAdded;
    const bool checkDuplicates = (filters.size() > 1);
    foreach (ILocatorFilter *filter, filters) {
        if (future.isCanceled())
            break;

        QList<LocatorFilterEntry> filterResults = filter->matchesFor(future, searchText);
        QVector<LocatorFilterEntry> uniqueFilterResults;
        uniqueFilterResults.reserve(filterResults.size());
        foreach (const LocatorFilterEntry &entry, filterResults) {
            if (checkDuplicates && alreadyAdded.contains(entry))
                continue;
            uniqueFilterResults.append(entry);
            if (checkDuplicates)
                alreadyAdded.insert(entry);
        }
        if (!uniqueFilterResults.isEmpty())
            future.reportResults(uniqueFilterResults);
    }
}
コード例 #21
0
ファイル: benchsuite.cpp プロジェクト: bschuste/GammaRay
void BenchSuite::connectionModel_connectionRemoved()
{
  Probe::createProbe(false);

  ConnectionModel model;
  static const int NUM_OBJECTS = 1000;
  QVector<QObject*> objects;
  objects.reserve(NUM_OBJECTS + 1);
  // fill it
  objects << new QObject;
  for(int i = 1; i <= NUM_OBJECTS; ++i) {
    QObject *obj = new QObject;
    objects << obj;
    Probe::objectAdded(obj);
    model.connectionAdded(obj, SIGNAL(destroyed()), objects.at(i-1), SLOT(deleteLater()), Qt::AutoConnection);
    model.connectionAdded(objects.at(i-1), SIGNAL(destroyed()), obj, SLOT(deleteLater()), Qt::AutoConnection);
    model.connectionAdded(obj, SIGNAL(destroyed()), objects.at(i-1), SLOT(deleteLater()), Qt::AutoConnection);
    model.connectionAdded(objects.at(i-1), SIGNAL(destroyed()), obj, SLOT(deleteLater()), Qt::AutoConnection);
    model.connectionAdded(obj, SIGNAL(invalid()), objects.at(i-1), SLOT(deleteLater()), Qt::AutoConnection);
    model.connectionAdded(objects.at(i-1), SIGNAL(destroyed()), obj, SLOT(invalid()), Qt::AutoConnection);
    // non-normalized
    model.connectionAdded(obj, SIGNAL( destroyed(  ) ), objects.at(i-1), SLOT(deleteLater()), Qt::AutoConnection);
    model.connectionAdded(objects.at(i-1), SIGNAL(destroyed()), obj, SLOT( deleteLater(  ) ), Qt::AutoConnection);
  }

  QBENCHMARK_ONCE {
    for(int i = 1; i <= NUM_OBJECTS; ++i) {
      model.connectionRemoved(objects.at(i), SIGNAL(destroyed()), objects.at(i-1), SLOT(deleteLater()));
      model.connectionRemoved(objects.at(i-1), SIGNAL(destroyed()), objects.at(i), SLOT(deleteLater()));
      model.connectionRemoved(objects.at(i), SIGNAL(destroyed()), objects.at(i-1), SLOT(invalid()));
      model.connectionRemoved(objects.at(i-1), SIGNAL(invalid()), objects.at(i), SLOT(deleteLater()));
    }
  }

  qDeleteAll(objects);
  delete Probe::instance();
}
コード例 #22
0
ファイル: Skin.cpp プロジェクト: OSSIA/Score
QVector<QPair<QColor, QString>> Skin::getColors() const
{
  QVector<QPair<QColor, QString>> vec;
  vec.reserve(27);

  SCORE_MAKE_PAIR_COLOR(Dark);
  SCORE_MAKE_PAIR_COLOR(HalfDark);
  SCORE_MAKE_PAIR_COLOR(Gray);
  SCORE_MAKE_PAIR_COLOR(HalfLight);
  SCORE_MAKE_PAIR_COLOR(Light);
  SCORE_MAKE_PAIR_COLOR(Emphasis1);
  SCORE_MAKE_PAIR_COLOR(Emphasis2);
  SCORE_MAKE_PAIR_COLOR(Emphasis3);
  SCORE_MAKE_PAIR_COLOR(Emphasis4);
  SCORE_MAKE_PAIR_COLOR(Base1);
  SCORE_MAKE_PAIR_COLOR(Base2);
  SCORE_MAKE_PAIR_COLOR(Base3);
  SCORE_MAKE_PAIR_COLOR(Base4);
  SCORE_MAKE_PAIR_COLOR(Base5);
  SCORE_MAKE_PAIR_COLOR(Warn1);
  SCORE_MAKE_PAIR_COLOR(Warn2);
  SCORE_MAKE_PAIR_COLOR(Warn3);
  SCORE_MAKE_PAIR_COLOR(Background1);
  SCORE_MAKE_PAIR_COLOR(Transparent1);
  SCORE_MAKE_PAIR_COLOR(Transparent2);
  SCORE_MAKE_PAIR_COLOR(Transparent3);
  SCORE_MAKE_PAIR_COLOR(Smooth1);
  SCORE_MAKE_PAIR_COLOR(Smooth2);
  SCORE_MAKE_PAIR_COLOR(Smooth3);
  SCORE_MAKE_PAIR_COLOR(Tender1);
  SCORE_MAKE_PAIR_COLOR(Tender2);
  SCORE_MAKE_PAIR_COLOR(Tender3);
  SCORE_MAKE_PAIR_COLOR(Pulse1);
  SCORE_MAKE_PAIR_COLOR(Pulse2);

  return vec;
}
コード例 #23
0
void QxSqlQuery::fetchSqlResult(QSqlQuery & query)
{
   bool bCheckRecord = true;
   m_pSqlResult.reset(new QxSqlResult());
   if (query.size() > 0) { m_pSqlResult->values.reserve(query.size()); }
   while (query.next())
   {
      if (bCheckRecord)
      {
         bCheckRecord = false;
         QSqlRecord record = query.record();
         m_pSqlResult->positionByKey.reserve(record.count());
         for (int i = 0; i < record.count(); i++)
         { m_pSqlResult->positionByKey.insert(record.fieldName(i), i); }
         qAssert(record.count() == m_pSqlResult->positionByKey.count());
      }
      QVector<QVariant> lst;
      lst.reserve(m_pSqlResult->positionByKey.count());
      for (long j = 0; j < m_pSqlResult->positionByKey.count(); j++)
      { lst.append(query.value(j)); }
      qAssert(lst.count() == m_pSqlResult->positionByKey.count());
      m_pSqlResult->values.append(lst);
   }
}
コード例 #24
0
ファイル: qgscompoundcurve.cpp プロジェクト: alexbruy/QGIS
QByteArray QgsCompoundCurve::asWkb() const
{
  int binarySize = sizeof( char ) + sizeof( quint32 ) + sizeof( quint32 );
  QVector<QByteArray> wkbForCurves;
  wkbForCurves.reserve( mCurves.size() );
  for ( const QgsCurve *curve : mCurves )
  {
    QByteArray wkbForCurve = curve->asWkb();
    binarySize += wkbForCurve.length();
    wkbForCurves << wkbForCurve;
  }

  QByteArray wkbArray;
  wkbArray.resize( binarySize );
  QgsWkbPtr wkb( wkbArray );
  wkb << static_cast<char>( QgsApplication::endian() );
  wkb << static_cast<quint32>( wkbType() );
  wkb << static_cast<quint32>( mCurves.size() );
  for ( const QByteArray &wkbForCurve : qgis::as_const( wkbForCurves ) )
  {
    wkb << wkbForCurve;
  }
  return wkbArray;
}
コード例 #25
0
ファイル: tst_skeleton.cpp プロジェクト: RSATom/Qt
    void checkJointTransforms_data()
    {
        QTest::addColumn<Skeleton*>("skeleton");
        QTest::addColumn<QVector<Sqt>>("jointTransforms");

        const int count = 5;
        auto skeleton = new Skeleton;
        skeleton->setJointCount(count);
        QVector<Sqt> jointTransforms;
        jointTransforms.reserve(count);
        for (int i = 0; i < count; ++i) {
            const float f = float(i);
            Sqt transform;
            transform.scale = QVector3D(f, f, f);
            transform.rotation = QQuaternion(f, 1.0f, 0.0f, 0.0f).normalized();
            transform.translation = QVector3D(1.0 * f, 2.0 * f, 3.0 * f);
            skeleton->setJointScale(i, transform.scale);
            skeleton->setJointRotation(i, transform.rotation);
            skeleton->setJointTranslation(i, transform.translation);
            jointTransforms.push_back(transform);
        }

        QTest::newRow("5 joints") << skeleton << jointTransforms;
    }
コード例 #26
0
ファイル: chatlog.cpp プロジェクト: BiTOk/qTox
void ChatLog::insertChatlineOnTop(const QList<ChatLine::Ptr>& newLines)
{
    if (newLines.isEmpty())
        return;

    QGraphicsScene::ItemIndexMethod oldIndexMeth = scene->itemIndexMethod();
    scene->setItemIndexMethod(QGraphicsScene::NoIndex);

    // alloc space for old and new lines
    QVector<ChatLine::Ptr> combLines;
    combLines.reserve(newLines.size() + lines.size());

    // add the new lines
    int i = 0;
    for (ChatLine::Ptr l : newLines)
    {
        l->addToScene(scene);
        l->visibilityChanged(false);
        l->setRow(i++);
        combLines.push_back(l);
    }

    // add the old lines
    for (ChatLine::Ptr l : lines)
    {
        l->setRow(i++);
        combLines.push_back(l);
    }

    lines = combLines;

    scene->setItemIndexMethod(oldIndexMeth);

    // redo layout
    startResizeWorker();
}
コード例 #27
0
ファイル: xyzdataprovider.cpp プロジェクト: ojschumann/clip
DataProvider* XYZDataProvider::Factory::getProvider(QString filename, ImageDataStore *store, QObject* _parent) {
  QFile imgFile(filename);

  if (!imgFile.open(QFile::ReadOnly)) return nullptr;

  QDataStream in(&imgFile);
  in.setByteOrder(QDataStream::LittleEndian);

  short unsigned int tmp;

  in >> tmp;
  int width = tmp;
  in >> tmp;
  int height = tmp;

  if ((2*width*height+4)!=imgFile.size()) return nullptr;
  QVector<float> pixelData;
  pixelData.reserve(width*height);


  for (int i=0; i<width*height; i++) {
    in >> tmp;
    pixelData << static_cast<float>(tmp);
  }

  store->setData(ImageDataStore::PixelSize, QSizeF(width, height));

  XYZDataProvider* provider = new XYZDataProvider(_parent);
  provider->pixelData = pixelData;
  provider->imgWidth = width;
  provider->imgHeight = height;
  provider->insertFileInformation(filename);
  provider->providerInformation.insert(Info_ImageSize, QString("%1x%2 pixels").arg(width).arg(height));

  return provider;
}
コード例 #28
0
	RowStore RowStoreModel::cacheFromLiveNodes(LiveNodes const &livenodes)
	{
		if(LiveNodeModel *model = livenodes.model())
		{
			if(RowStoreModel *modeldata = dynamic_cast<RowStoreModel *>(model))
				return modeldata->row_store;
			QVector<QStringList> ret;
			int columns = model->columnCount();
			for(int r = 0, rend = model->rowCount(); r < rend; ++r)
			{
				ret.push_back(QStringList());
				QStringList &b = ret.back();
				for(int c = 0; c < columns; ++c)
					b.push_back(model->data(model->index(r, c), Qt::DisplayRole).toString());
			}
			return RowStore(ret);
		}
		QVector<QStringList> ret;
		QList<LiveNode> const &nodes = livenodes.nodes();
		ret.reserve(nodes.size());
		for(QList<LiveNode>::const_iterator ni = nodes.begin(), niend = nodes.end(); ni != niend; ++ni)
			ret.push_back(QStringList(ni->toString()));
		return RowStore(ret);
	}
コード例 #29
0
void ConstellationMgr::loadLinesAndArt(const QString &fileName, const QString &artfileName, const QString& cultureName)
{
	QFile in(fileName);
	if (!in.open(QIODevice::ReadOnly | QIODevice::Text))
	{
		qWarning() << "Can't open constellation data file" << fileName  << "for culture" << cultureName;
		Q_ASSERT(0);
	}

	int totalRecords=0;
	QString record;
	QRegExp commentRx("^(\\s*#.*|\\s*)$");
	while (!in.atEnd())
	{
		record = QString::fromUtf8(in.readLine());
		if (!commentRx.exactMatch(record))
			totalRecords++;
	}
	in.seek(0);

	// delete existing data, if any
	vector < Constellation * >::iterator iter;
	for (iter = asterisms.begin(); iter != asterisms.end(); ++iter)
		delete(*iter);

	asterisms.clear();
	Constellation *cons = NULL;

	// read the file, adding a record per non-comment line
	int currentLineNumber = 0;	// line in file
	int readOk = 0;			// count of records processed OK
	while (!in.atEnd())
	{
		record = QString::fromUtf8(in.readLine());
		currentLineNumber++;
		if (commentRx.exactMatch(record))
			continue;

		cons = new Constellation;
		if(cons->read(record, hipStarMgr))
		{
			cons->artFader.setMaxValue(artIntensity);
			cons->setFlagArt(artDisplayed);
			cons->setFlagBoundaries(boundariesDisplayed);
			cons->setFlagLines(linesDisplayed);
			cons->setFlagLabels(namesDisplayed);
			asterisms.push_back(cons);
			++readOk;
		}
		else
		{
			qWarning() << "ERROR reading constellation rec at line " << currentLineNumber << "for culture" << cultureName;
			delete cons;
		}
	}
	in.close();
	qDebug() << "Loaded" << readOk << "/" << totalRecords << "constellation records successfully for culture" << cultureName;

	// Set current states
	setFlagArt(artDisplayed);
	setFlagLines(linesDisplayed);
	setFlagLabels(namesDisplayed);
	setFlagBoundaries(boundariesDisplayed);

	// It's possible to have no art - just constellations
	if (artfileName.isNull() || artfileName.isEmpty())
		return;
	QFile fic(artfileName);
	if (!fic.open(QIODevice::ReadOnly | QIODevice::Text))
	{
		qWarning() << "Can't open constellation art file" << fileName  << "for culture" << cultureName;
		return;
	}

	totalRecords=0;
	while (!fic.atEnd())
	{
		record = QString::fromUtf8(fic.readLine());
		if (!commentRx.exactMatch(record))
			totalRecords++;
	}
	fic.seek(0);

	// Read the constellation art file with the following format :
	// ShortName texture_file x1 y1 hp1 x2 y2 hp2
	// Where :
	// shortname is the international short name (i.e "Lep" for Lepus)
	// texture_file is the graphic file of the art texture
	// x1 y1 are the x and y texture coordinates in pixels of the star of hipparcos number hp1
	// x2 y2 are the x and y texture coordinates in pixels of the star of hipparcos number hp2
	// The coordinate are taken with (0,0) at the top left corner of the image file
	QString shortname;
	QString texfile;
	unsigned int x1, y1, x2, y2, x3, y3, hp1, hp2, hp3;
	QString tmpstr;

	currentLineNumber = 0;	// line in file
	readOk = 0;		// count of records processed OK

	while (!fic.atEnd())
	{
		++currentLineNumber;
		record = QString::fromUtf8(fic.readLine());
		if (commentRx.exactMatch(record))
			continue;

		// prevent leaving zeros on numbers from being interpretted as octal numbers
		record.replace(" 0", " ");
		QTextStream rStr(&record);
		rStr >> shortname >> texfile >> x1 >> y1 >> hp1 >> x2 >> y2 >> hp2 >> x3 >> y3 >> hp3;
		if (rStr.status()!=QTextStream::Ok)
		{
			qWarning() << "ERROR parsing constellation art record at line" << currentLineNumber << "of art file for culture" << cultureName;
			continue;
		}

		// Draw loading bar
// 		lb.SetMessage(q_("Loading Constellation Art: %1/%2").arg(currentLineNumber).arg(totalRecords));
// 		lb.Draw((float)(currentLineNumber)/totalRecords);

		cons = NULL;
		cons = findFromAbbreviation(shortname);
		if (!cons)
		{
			qWarning() << "ERROR in constellation art file at line" << currentLineNumber << "for culture" << cultureName
					   << "constellation" << shortname << "unknown";
		}
		else
		{
			QString texturePath(texfile);
			try
			{
				texturePath = StelFileMgr::findFile("skycultures/"+cultureName+"/"+texfile);
			}
			catch (std::runtime_error& e)
			{
				// if the texture isn't found in the skycultures/[culture] directory,
				// try the central textures diectory.
				qWarning() << "WARNING, could not locate texture file " << texfile
					 << " in the skycultures/" << cultureName
					 << " directory...  looking in general textures/ directory...";
				try
				{
					texturePath = StelFileMgr::findFile(QString("textures/")+texfile);
				}
				catch(exception& e2)
				{
					qWarning() << "ERROR: could not find texture, " << texfile << ": " << e2.what();
				}
			}

			cons->artTexture = StelApp::getInstance().getTextureManager().createTextureThread(texturePath);

			int texSizeX, texSizeY;
			if (cons->artTexture==NULL || !cons->artTexture->getDimensions(texSizeX, texSizeY))
			{
				qWarning() << "Texture dimension not available";
			}

			StelCore* core = StelApp::getInstance().getCore();
			Vec3d s1 = hipStarMgr->searchHP(hp1)->getJ2000EquatorialPos(core);
			Vec3d s2 = hipStarMgr->searchHP(hp2)->getJ2000EquatorialPos(core);
			Vec3d s3 = hipStarMgr->searchHP(hp3)->getJ2000EquatorialPos(core);

			// To transform from texture coordinate to 2d coordinate we need to find X with XA = B
			// A formed of 4 points in texture coordinate, B formed with 4 points in 3d coordinate
			// We need 3 stars and the 4th point is deduced from the other to get an normal base
			// X = B inv(A)
			Vec3d s4 = s1 + ((s2 - s1) ^ (s3 - s1));
			Mat4d B(s1[0], s1[1], s1[2], 1, s2[0], s2[1], s2[2], 1, s3[0], s3[1], s3[2], 1, s4[0], s4[1], s4[2], 1);
			Mat4d A(x1, texSizeY - y1, 0.f, 1.f, x2, texSizeY - y2, 0.f, 1.f, x3, texSizeY - y3, 0.f, 1.f, x1, texSizeY - y1, texSizeX, 1.f);
			Mat4d X = B * A.inverse();

			// Tesselate on the plan assuming a tangential projection for the image
			static const int nbPoints=5;
			QVector<Vec2f> texCoords;
			texCoords.reserve(nbPoints*nbPoints*6);
			for (int j=0;j<nbPoints;++j)
			{
				for (int i=0;i<nbPoints;++i)
				{
					texCoords << Vec2f(((float)i)/nbPoints, ((float)j)/nbPoints);
					texCoords << Vec2f(((float)i+1.f)/nbPoints, ((float)j)/nbPoints);
					texCoords << Vec2f(((float)i)/nbPoints, ((float)j+1.f)/nbPoints);
					texCoords << Vec2f(((float)i+1.f)/nbPoints, ((float)j)/nbPoints);
					texCoords << Vec2f(((float)i+1.f)/nbPoints, ((float)j+1.f)/nbPoints);
					texCoords << Vec2f(((float)i)/nbPoints, ((float)j+1.f)/nbPoints);
				}
			}

			QVector<Vec3d> contour;
			contour.reserve(texCoords.size());
			foreach (const Vec2f& v, texCoords)
				contour << X * Vec3d(v[0]*texSizeX, v[1]*texSizeY, 0.);

			cons->artPolygon.vertex=contour;
			cons->artPolygon.texCoords=texCoords;
			cons->artPolygon.primitiveType=StelVertexArray::Triangles;

			Vec3d tmp(X * Vec3d(0.5*texSizeX, 0.5*texSizeY, 0.));
			tmp.normalize();
			Vec3d tmp2(X * Vec3d(0., 0., 0.));
			tmp2.normalize();
			cons->boundingCap.n=tmp;
			cons->boundingCap.d=tmp*tmp2;
			++readOk;
		}
	}

	qDebug() << "Loaded" << readOk << "/" << totalRecords << "constellation art records successfully for culture" << cultureName;
	fic.close();
}
コード例 #30
0
KeyboardProfile KeyboardProfileDialog::getProfile() const
{
	KeyboardProfile profile(m_profile);
	profile.setTitle(m_ui->titleLineEditWidget->text());
	profile.setDescription(m_ui->descriptionLineEditWidget->text());
	profile.setVersion(m_ui->versionLineEditWidget->text());
	profile.setAuthor(m_ui->authorLineEditWidget->text());

	QMap<int, QVector<QPair<QVariantMap, QVector<QKeySequence> > > > actions;

	for (int i = 0; i < m_ui->actionsViewWidget->getRowCount(); ++i)
	{
		if (static_cast<ShortcutStatus>(m_ui->actionsViewWidget->getIndex(i, 0).data(StatusRole).toInt()) == ErrorStatus)
		{
			continue;
		}

		const QKeySequence shortcut(m_ui->actionsViewWidget->getIndex(i, 3).data(Qt::DisplayRole).toString());
		const int action(m_ui->actionsViewWidget->getIndex(i, 1).data(IdentifierRole).toInt());

		if (action >= 0 && !shortcut.isEmpty())
		{
			const QVariantMap parameters(m_ui->actionsViewWidget->getIndex(i, 1).data(ParametersRole).toMap());
			bool hasFound(false);

			if (actions.contains(action))
			{
				QVector<QPair<QVariantMap, QVector<QKeySequence> > > actionVariants(actions[action]);

				for (int j = 0; j < actionVariants.count(); ++j)
				{
					if (actionVariants.at(j).first == parameters)
					{
						actionVariants[j].second.append(shortcut);

						actions[action] = actionVariants;

						hasFound = true;

						break;
					}
				}
			}

			if (!hasFound)
			{
				actions[action] = {{parameters, {shortcut}}};
			}
		}
	}

	QMap<int, QVector<QPair<QVariantMap, QVector<QKeySequence> > > >::iterator iterator;
	QVector<KeyboardProfile::Action> definitions;
	definitions.reserve(actions.count());

	for (iterator = actions.begin(); iterator != actions.end(); ++iterator)
	{
		const QVector<QPair<QVariantMap, QVector<QKeySequence> > > actionVariants(iterator.value());

		for (int j = 0; j < actionVariants.count(); ++j)
		{
			KeyboardProfile::Action definition;
			definition.parameters = actionVariants[j].first;
			definition.shortcuts = actionVariants[j].second;
			definition.action = iterator.key();

			definitions.append(definition);
		}
	}

	profile.setDefinitions({{ActionsManager::GenericContext, definitions}});
	profile.setModified(m_ui->actionsViewWidget->isModified());

	return profile;
}