// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void StatsGenMDFWidget::extractStatsData(int index, StatsData* statsData, unsigned int phaseType)
{
  Q_UNUSED(index)
  VectorOfFloatArray arrays;
  if(phaseType == SIMPL::PhaseType::PrimaryPhase)
  {
    PrimaryStatsData* pp = PrimaryStatsData::SafePointerDownCast(statsData);
    arrays = pp->getMDF_Weights();
  }
  if(phaseType == SIMPL::PhaseType::PrecipitatePhase)
  {
    PrecipitateStatsData* pp = PrecipitateStatsData::SafePointerDownCast(statsData);
    arrays = pp->getMDF_Weights();
  }
  if(phaseType == SIMPL::PhaseType::TransformationPhase)
  {
    TransformationStatsData* tp = TransformationStatsData::SafePointerDownCast(statsData);
    arrays = tp->getMDF_Weights();
  }

  QVector<float> axis;
  QVector<float> angle;
  QVector<float> weights;

  for (int i = 0; i < arrays.size(); i++)
  {
    if(arrays[i]->getName().compare(SIMPL::StringConstants::Axis) == 0)
    {
       axis = QVector<float>(static_cast<int>(arrays[i]->getSize())); // This one is 3xn in size
      ::memcpy( &(axis.front()), arrays[i]->getVoidPointer(0), sizeof(float)*axis.size() );
    }

    if(arrays[i]->getName().compare(SIMPL::StringConstants::Angle) == 0)
    {
      angle = QVector<float>(static_cast<int>(arrays[i]->getNumberOfTuples()));
      ::memcpy( &(angle.front()), arrays[i]->getVoidPointer(0), sizeof(float)*angle.size() );
    }

    if(arrays[i]->getName().compare(SIMPL::StringConstants::Weight) == 0)
    {
      weights = QVector<float>(static_cast<int>(arrays[i]->getNumberOfTuples()));
      ::memcpy( &(weights.front()), arrays[i]->getVoidPointer(0), sizeof(float)*weights.size() );
    }
  }
    if (arrays.size() > 0)
    {
      // Load the data into the table model
      m_MDFTableModel->setTableData(angle, axis, weights);
    }

  on_m_MDFUpdateBtn_clicked();
}
void FileUploader::download(const QString &rootPath, const QVector<mtp::ObjectId> &objectIds)
{
	_model->moveToThread(&_workerThread);
	_total = 0;

	mtp::ObjectId currentParentId = _model->parentObjectId();

	QVector<QPair<QString, mtp::ObjectId> > input;
	for(auto id : objectIds)
		input.push_back(qMakePair(rootPath, id));

	QVector<QPair<QString, mtp::ObjectId> > files;
	while(!input.empty())
	{
		QString prefix = input.front().first;
		mtp::ObjectId id = input.front().second;
		input.pop_front();

		MtpObjectsModel::ObjectInfo oi = _model->getInfoById(id);
		if (oi.Format == mtp::ObjectFormat::Association)
		{
			//enumerate here
			QString dirPath = prefix + "/" + oi.Filename;
			mtp::SessionPtr session = _model->session();
			mtp::msg::ObjectHandles handles = session->GetObjectHandles(mtp::Session::AllStorages, mtp::ObjectFormat::Any, id);
			qDebug() << "found " << handles.ObjectHandles.size() << " objects in " << dirPath;
			for(mtp::ObjectId id : handles.ObjectHandles)
				input.push_back(qMakePair(dirPath, id));
		}
		else
		{
			_total += oi.Size;
			files.push_back(qMakePair(prefix + "/" + oi.Filename, id));
		}
	}

	qDebug() << "downloading " << files.size() << " file(s), " << _total << " bytes";
	_startedAt = QDateTime::currentDateTime();
	_aborted = false;
	if (_total < 1)
		_total = 1;

	for(const auto & file : files)
	{
		if (_aborted)
			break;
		emit executeCommand(new DownloadFile(file.first, file.second));
	}
	emit executeCommand(new FinishQueue(currentParentId));
}
void CorrespondenceSearch::applyCorrespondence(const PartsCorrespondence & correspondence)
{	
	QVector<ParticleMesh*> input; input << sA << sB;
	QVector<Particles> particles; 
	particles << sA->particles << sB->particles;

	for( auto & pairing : correspondence )
	{
		PartCorresponder::correspondSegments( pairing, input, particles );

		// DEBUG:
		if( true )
		{
			auto ls = new starlab::LineSegments(3);
			auto boxA = sA->segmentBoundingBox( input[0]->property["segments"].value<Segments>()[pairing.first] );
			auto boxB = sB->segmentBoundingBox( input[1]->property["segments"].value<Segments>()[pairing.second] );
			ls->addLine( Vector3( boxA.center() ), Vector3(boxB.center() + Vector3(1,0,0)), Qt::black );
			debug << ls;
		}
	}

	// Assign back
	sA->particles = particles.front();
	sB->particles = particles.back();
}
// 获取下一时刻所有目标的状态
std::vector<State> TargetDataReader::getNextStates()
{
    std::vector<State> re;
    QVector<QString> *dv;
    QString line;
    if (allDataVector.at(0)->size() > 0) {
//        QString line = dataVector.front();
//        State s = createStateFromLine(line);
//        if (re.size() == 0) {
//            re.push_back(s);
//            dataVector.pop_front();
//        } else {
//            State preState = re.back();
//            if (preState.getTime() == s.getTime()) {
//                re.push_back(s);
//                dataVector.pop_front();
//            }
//        }
        for(int i = 0; i < allDataVector.size();i++)
        {
            dv = allDataVector[i];
            if(dv->size() > 0){
                line = dv->front();
                State s = createStateFromLine(line);
                re.push_back(s);
                dv->pop_front();
            }
        }
    }
    return re;
}
Exemple #5
0
void Scene::render()
{
    for(int i = -CWIDTH / 2; i < CWIDTH / 2; i ++)
    {
        qDebug() << i;
        for(int j = -CHEIGHT / 2; j < CHEIGHT / 2; j ++)
        {
            QVector<Ray*> rSeq = camera->pixelLight(i, j);
            int s = rSeq.size();
            Intensity rgb(0, 0, 0);
            while(!rSeq.empty())
            {
                Ray* tmp = rSeq.front();

                rgb = rgb + (1.0 / s) * getIntensity(tmp);
                rSeq.pop_front();
                if(tmp != NULL)
                {
                    delete tmp;
                    tmp = NULL;
                }
            }
            pixels[i + CWIDTH / 2][j + CHEIGHT / 2] = rgb.toRGB();

        }

    }
}
Exemple #6
0
void UpdateLevelOfDetailJob::updateEntityLod(Entity *entity)
{
    if (!entity->isEnabled())
        return; // skip disabled sub-trees, since their bounding box is probably not valid anyway

    QVector<LevelOfDetail *> lods = entity->renderComponents<LevelOfDetail>();
    if (!lods.empty()) {
        LevelOfDetail* lod = lods.front();  // other lods are ignored

        if (lod->isEnabled() && !lod->thresholds().isEmpty()) {
            switch (lod->thresholdType()) {
            case QLevelOfDetail::DistanceToCameraThreshold:
                updateEntityLodByDistance(entity, lod);
                break;
            case QLevelOfDetail::ProjectedScreenPixelSizeThreshold:
                updateEntityLodByScreenArea(entity, lod);
                break;
            default:
                Q_ASSERT(false);
                break;
            }
        }
    }

    const auto children = entity->children();
    for (Qt3DRender::Render::Entity *child : children)
        updateEntityLod(child);
}
// Returns true if this node is to be deleted.
static bool nodePruneAction_impl(
        Process::MessageNode& node,
        const Id<Process::ProcessModel>& proc,
        QVector<Process::ProcessStateData>& vec,
        const QVector<Process::ProcessStateData>& other_vec)
{
    int vec_size = vec.size();
    if(vec_size > 1)
    {
        // We just remove the element
        // corresponding to this process.
        auto it = find_if(vec,
                      [&] (const auto& data) {
            return data.process == proc;
        });

        if(it != vec.end())
        {
            vec.erase(it);
        }
    }
    else if(vec_size == 1)
    {
        // We may be able to remove the whole node
        if(vec.front().process == proc)
            vec.clear();

        // If false, nothing is removed.
        return vec.isEmpty()
            && other_vec.isEmpty()
            && !node.values.userValue;
    }

    return false;
}
void PartCorresponder::match1DGridChunk( QVector< QVector<SliceChunk> > sortedChunk, const QVector<ParticleMesh *> & input, QVector<Particles> & particles )
{
	QVector< QVector<SliceChunk> > readyChunkPairs;

	auto & sortedChunkFront = sortedChunk.front();
	auto & sortedChunkBack = sortedChunk.back();

	// Different number of chunks
	if( sortedChunkFront.size() != sortedChunkBack.size() )
	{
		int targetSize = std::min( sortedChunkFront.size(), sortedChunkBack.size() );

		if(targetSize == 1)
		{
			QVector<SliceChunk> chunkPairs;
			if( sortedChunkFront.size() == 1 ) chunkPairs.push_back( sortedChunkFront.front() );
			else chunkPairs.push_back( mergeChunks( sortedChunkFront, input.front(), particles.front() ) );

			if( sortedChunkBack.size() == 1) chunkPairs.push_back( sortedChunkBack.front() );
			else chunkPairs.push_back( mergeChunks( sortedChunkBack, input.back(), particles.back() ) );

			readyChunkPairs.push_back( chunkPairs );
		}
		else
		{
			// For now we use basic matching.. later we should either split / merge
			for(auto v : distributeVectors(sortedChunkFront.size(), sortedChunkBack.size()))
			{
				QVector<SliceChunk> p;
				p << sortedChunkFront[v.first] << sortedChunkBack[v.second];
				readyChunkPairs.push_back( p );
			}
		}
	}
	else
	{
		// Same number of elements, simply match them up
		for(size_t i = 0; i < sortedChunk.front().size(); i++)
		{
			readyChunkPairs.push_back( QVector<SliceChunk>() << sortedChunkFront.at(i) << sortedChunkBack.at(i) );
		}
	}

	// Match each pair of chunks
	for(auto & pairChunk : readyChunkPairs)
		matchChunk(pairChunk, input, particles);
}
Exemple #9
0
void TaskSheet::prepareGrowShrinkSheet()
{
    Structure::Node * n = node();
    QVector<Structure::Link*> edges = filterEdges(n, active->getEdges(n->id));

	property["edges"].setValue( active->getEdgeIDs(edges) );

    if (edges.size() == 1)
    {
        prepareSheetOneEdge( edges.front() );
    }

    if (edges.size() == 2)
    {
        prepareSheetTwoEdges( edges.front(), edges.back() );
    }
}
Exemple #10
0
Shot::Shot(Common::Person person, const QPoint& pos, int height, const QVector<QPixmap>& vecPix, QGraphicsItem* parent) : AbstractSprite(parent)
    , m_rectSprite(QRect(pos.x(), pos.y(), vecPix.front().width(), vecPix.front().width()))
    , m_person(person)
{
    if(person == Common::Person::Player)
    {
        m_posBoundingSprite = QPoint(pos.x(), pos.y() - vecPix.front().height() + 4);
        QSound::play(":sound/resource/sound/playerShot.wav");
    }
    else if(person == Common::Person::Enemy)
    {
        m_posBoundingSprite = pos;
        QSound::play(":sound/resource/sound/enemyShot.wav");
    }
    m_pixSprite_ = vecPix;
    m_heightBounding = height;
    setSpeed(5);
}
Exemple #11
0
	void SeparateTabBar::UpdateComputedWidths () const
	{
		const auto cnt = count ();
		ComputedWidths_.resize (cnt);

		const auto maxTabWidth = width () / 4;

		struct TabInfo
		{
			int Idx_;
			int WidthHint_;
		};
		QVector<TabInfo> infos;
		for (int i = 0; i < cnt - 1; ++i)
			infos.push_back ({ i, std::min (QTabBar::tabSizeHint (i).width (), maxTabWidth) });
		std::sort (infos.begin (), infos.end (),
				[] (const TabInfo& l, const TabInfo& r) { return l.WidthHint_ < r.WidthHint_; });

		const auto hspace = std::max (style ()->pixelMetric (QStyle::PM_TabBarTabHSpace), 10);
		const auto btnWidth = AddTabButton_ ? AddTabButton_->sizeHint ().width () + hspace : 30;

		auto remainder = width () - btnWidth;

		while (!infos.isEmpty ())
		{
			auto currentMax = remainder / infos.size ();
			if (infos.front ().WidthHint_ > currentMax)
				break;

			const auto& info = infos.front ();
			remainder -= info.WidthHint_;
			ComputedWidths_ [info.Idx_] = info.WidthHint_;
			infos.pop_front ();
		}

		if (infos.isEmpty ())
			return;

		const auto uniform = remainder / infos.size ();
		for (const auto& info : infos)
			ComputedWidths_ [info.Idx_] = uniform;
	}
Exemple #12
0
void TaskSheet::executeCrossingSheet( double t )
{
	Node *n = node(), *tn = targetNode();

	QVector<Link*> edges = active->getEdges( property["edges"].value< QVector<int> >() );

	if (property.contains("path"))
	{
		Vector3 p0 = n->position(Vec4d(0,0,0,0));
		Vector3 delta(0,0,0);

		if(!edges.isEmpty())
		{
			p0 = edges.front()->position(n->id);

			// Blend Deltas
			Structure::Link *slink = edges.front();
			Structure::Link* tlink = target->getEdge(slink->property["correspond"].toInt());
			Vector3 d1 = slink->position(n->id) - slink->positionOther(n->id);
			Vector3 d2 = tlink->position(tn->id) - tlink->positionOther(tn->id);
			delta = AlphaBlend(t, d1, d2);
		}

		executeMorphSheet(t);
		
		// Cancel any absolute movement
		if(!edges.isEmpty())
			n->moveBy(p0 - edges.front()->position(n->id));

		// Move it to the correct position
		Array1D_Vector3 path = property["path"].value< Array1D_Vector3 >();
		int idx = t * (path.size() - 1);

		Vector3 oldPosOnMe = p0;
		Vector3 newPosOnMe = path[idx] + delta;

		n->moveBy(newPosOnMe - p0);
	}
}
Exemple #13
0
QVector<QVector<double>> multipl(QVector<QVector<double>> a, QVector<QVector<double>> b)
{
    int m = a.size();
    int n = b.front().size();

    if(a.front().size()!=b.size())
    {
        qDebug() << "mxn";
    }

    QVector<double> e(n,0);
    QVector<QVector<double>> ab(m,e);

    for(int i = 0; i < m; i++)
    {
        for(int j = 0; j< n;j++)
        {
            ab[i][j]=product(a,b,i,j);
        }
    }
    return ab;
}
//Input Port #0: Buffer_Size = 1, Params_Type = ProcessorMulti_Processor_SimpleCollect_Params, Data_Type = ProcessorMulti_Processor_SimpleCollect_Data
bool DECOFUNC(processMonoDrainData)(void * paramsPtr, void * varsPtr, QVector<void *> drainParams, QVector<void *> drainData)
{
	VisualizationMono_Processor_SimpleCollect_Params * params=(VisualizationMono_Processor_SimpleCollect_Params *)paramsPtr;
	VisualizationMono_Processor_SimpleCollect_Vars * vars=(VisualizationMono_Processor_SimpleCollect_Vars *)varsPtr;
	QVector<ProcessorMulti_Processor_SimpleCollect_Params *> drainparams; copyQVector(drainparams,drainParams);
	QVector<ProcessorMulti_Processor_SimpleCollect_Data *> draindata; copyQVector(draindata,drainData);
	if(draindata.size()==0){return 0;}
	/*======Please Program below======*/
	/*
	Function: process draindata.
	*/
    vars->label->setText(draindata.front()->simplestatus);
	return 1;
}
Exemple #15
0
void TaskSheet::executeGrowShrinkSheet(double t)
{
	Structure::Sheet* structure_sheet = ((Structure::Sheet*)node());
	QVector<Link*> edges = active->getEdges( property["edges"].value< QVector<int> >() );

	/// Single edge case
	if ( property.contains("deltas") )
	{
		Array2D_Vector3 cpts = property["orgCtrlPoints"].value<Array2D_Vector3>();
		Array2D_Vector3 deltas = property["deltas"].value<Array2D_Vector3>();

		// Grow sheet
		for(size_t u = 0; u < structure_sheet->surface.mNumUCtrlPoints; u++)
			for(size_t v = 0; v < structure_sheet->surface.mNumVCtrlPoints; v++)
				structure_sheet->surface.mCtrlPoint[u][v] = cpts[u][v] + (deltas[u][v] * t);
	}

	/// Two edges case
	if( property.contains("pathA") && property.contains("pathB") && property.contains("cpCoords") )
	{
		QVector< GraphDistance::PathPointPair > pathA = property["pathA"].value< QVector< GraphDistance::PathPointPair > >();
		QVector< GraphDistance::PathPointPair > pathB = property["pathB"].value< QVector< GraphDistance::PathPointPair > >();
		if(pathA.size() == 0 || pathB.size() == 0)	return;

		double dt = t;
		if(type == SHRINK) dt = 1 - t;

		double decodeT = qMin(1.0, dt * 2.0);

		int idxA = dt * (pathA.size() - 1);
		int idxB = dt * (pathB.size() - 1);

		// Move to next step
		Vector3 pointA = pathA[idxA].position(active);
		Vector3 pointB = pathB[idxB].position(active);

		Structure::Link *linkA = edges.front(), *linkB = edges.back();
		if (type == GROW){
			linkA = target->getEdge(linkA->property["correspond"].toInt());
			linkB = target->getEdge(linkB->property["correspond"].toInt());
		}

		Vector3d deltaA = linkA->property["delta"].value<Vector3d>() * dt;
		Vector3d deltaB = linkB->property["delta"].value<Vector3d>() * dt;

		Array1D_Vector3 decoded = Curve::decodeCurve(property["cpCoords"].value<CurveEncoding>(), pointA + deltaA, pointB + deltaB, decodeT);
		structure_sheet->setControlPoints( decoded );
	}
}
Exemple #16
0
QVector<QVector<double>> transpose(QVector<QVector<double>> a)
{
        int m = a.size();
        int n = a.front().size();
        QVector<double> r(m);
        QVector<QVector<double>> aT(n,r);
        for(int i = 0; i < m; i++)
        {
            for(int j = 0; j < n; j++)
            {
                aT[j][i]=a[i][j];
            }
        }
        return aT;
}
//Input Port #0: Buffer_Size = 10, Params_Type = ProcessorMulti_Processor_Control_Params, Data_Type = ProcessorMulti_Processor_Control_Data
bool DECOFUNC(processMonoDrainData)(void * paramsPtr, void * varsPtr, QVector<void *> drainParams, QVector<void *> drainData)
{
	TransmitterMono_Gazebo_OrderGenerate_Params * params=(TransmitterMono_Gazebo_OrderGenerate_Params *)paramsPtr;
	TransmitterMono_Gazebo_OrderGenerate_Vars * vars=(TransmitterMono_Gazebo_OrderGenerate_Vars *)varsPtr;
	QVector<ProcessorMulti_Processor_Control_Params *> drainparams; copyQVector(drainparams,drainParams);
	QVector<ProcessorMulti_Processor_Control_Data *> draindata; copyQVector(draindata,drainData);
	if(draindata.size()==0){return 0;}
	/*======Please Program below======*/
	/*
	Function: process draindata.
	*/
    ProcessorMulti_Processor_Control_Data* control = draindata.front();
    vars->controlPub->sendMessage(-control->left_vel, -control->right_vel);
	return 1;
}
Exemple #18
0
void GlVizualizer::transform(QVector<float> &s )
{

    for(int x = 0; x < s.size(); ++x)
        s[x] *= 2;

    float *front = static_cast<float*>( &s.front() );

    m_fht->spectrum( front );
    m_fht->scale( front, 1.0 / 20 );

    //the second half is pretty dull, so only show it if the user has a large analyzer
    //by setting to m_scope.size() if large we prevent interpolation of large analyzers, this is good!
    s.resize( m_scope.size() <= MAX_COLUMNS/2 ? MAX_COLUMNS/2 : m_scope.size() );
}
Exemple #19
0
void AddressDialog::suggestionClicked( QListWidgetItem * item )
{
	IAddressLookup* addressLookup = MapData::instance()->addressLookup();
	if ( addressLookup == NULL )
		return;

	QString text = item->text();
	if ( m_mode == City ) {
		QVector< int > placeIDs;
		QVector< UnsignedCoordinate > placeCoordinates;
		if ( !addressLookup->GetPlaceData( text, &placeIDs, &placeCoordinates ) )
			return;

		m_placeID = placeIDs.front();
		if ( placeIDs.size() > 1 )
		{
			int id = PlaceChooser::selectPlaces( placeCoordinates, this );
			if ( id >= 0 && id < placeIDs.size() )
				m_placeID = placeIDs[id];
			else
				return;
		}
		m_ui->cityEdit->setText( text );
		m_ui->cityEdit->setDisabled( true );
		m_ui->streetEdit->setEnabled( true );
		m_ui->streetEdit->setFocus();
		m_ui->resetStreet->setEnabled( true );
		m_mode = Street;
		streetTextChanged( m_ui->streetEdit->text() );
	} else {
		QVector< int > segmentLength;
		QVector< UnsignedCoordinate > coordinates;
		if ( !addressLookup->GetStreetData( m_placeID, text, &segmentLength, &coordinates ) )
			return;
		if ( coordinates.size() == 0 )
			return;
		if ( m_skipStreetPosition ) {
			m_result = coordinates.first();
			accept();
			return;
		}
		if( !StreetChooser::selectStreet( &m_result, segmentLength, coordinates, this ) )
			return;
		m_ui->streetEdit->setText( text );
		accept();
	}
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
FloatArrayType::Pointer TransformationStatsData::generateBinNumbers()
{
  float featureDiameterInfo[3];
  getFeatureDiameterInfo(featureDiameterInfo);
  QVector<float> bins;
  float d = featureDiameterInfo[2];
  while (d <= featureDiameterInfo[1])
  {
    //  qDebug() << d << "\n";
    bins.push_back(d);
    d = d + featureDiameterInfo[0];
  }
  // Copy this into the DataArray<float>
  m_BinNumbers = FloatArrayType::CreateArray(bins.size(), DREAM3D::StringConstants::BinNumber );
  ::memcpy(m_BinNumbers->getVoidPointer(0), &(bins.front()), bins.size() * sizeof(float));
  return m_BinNumbers;
}
Exemple #21
0
float Scene::getSourceRay(int i, Point* p)
{
    Point* oi1 = sources.at(i)->getOrigin();
    Ray sourceRay(*oi1, *p - *oi1, 0);
    float f1 = distance(oi1, p);
    int s1 = models.size();
    int k1 = 0;
    for(k1 = 0; k1 < s1; k1 ++)
    {
        float s = models.at(k1)->intersection(sourceRay);
        if((s > THRE * 10) && (f1 - s > THRE * 10)) break;
    }
    if(k1 == s1) return 1;

    int cnt = 0;
    QVector<Point *> org = sources.at(i)->sampleOrigin();
    int size = org.size();
    for(int j = 0; j < size; j ++)
    {
        Point* oi = org.at(j);
        Point op = *p - *oi;
        Ray sourceRay(*oi, op, 0);
        float f = distance(oi, p);
        int s = models.size();
        int k = 0;
        for(k = 0; k < s; k ++)
        {
            float s = models.at(k)->intersection(sourceRay);
            if((s > THRE * 10) && (f - s > THRE * 10)) break;
        }
        if(k == s) cnt ++;
    }
    while(!org.empty())
    {
        Point* first = org.front();
        if(first != NULL)
        {
            delete first;
            first = NULL;
        }
        org.pop_front();
    }
    return qMin(2 * cnt / (size + 0.0), 1.0);
}
Exemple #22
0
int writeScalarData(const QString& hdfPath,
                    const QVector<T>& scalar_data,
                    const QString& name,
                    int numComp, int32_t rank, hsize_t* dims)
{
  hid_t gid = H5Gopen(m_FileId, hdfPath.toLatin1().data(), H5P_DEFAULT );
  if (gid < 0)
  {
    qDebug() << "Error opening Group " << hdfPath;
    return gid;
  }
  herr_t err = QH5Utilities::createGroupsFromPath(H5_SCALAR_DATA_GROUP_NAME, gid);
  if (err < 0)
  {
    qDebug() << "Error creating HDF Group " << H5_SCALAR_DATA_GROUP_NAME;
    return err;
  }
  hid_t cellGroupId = H5Gopen(gid, H5_SCALAR_DATA_GROUP_NAME, H5P_DEFAULT );
  if(err < 0)
  {
    qDebug() << "Error writing string attribute to HDF Group " << H5_SCALAR_DATA_GROUP_NAME;
    return err;
  }

  T* data = const_cast<T*>(&(scalar_data.front()));


  err = QH5Lite::replacePointerDataset(cellGroupId, name, rank, dims, data);
  if (err < 0)
  {
    qDebug() << "Error writing array with name: " << name;
  }
  err = QH5Lite::writeScalarAttribute(cellGroupId, name, DREAM3D::HDF5::NumComponents, numComp);
  if (err < 0)
  {
    qDebug() << "Error writing dataset " << name;
  }
  err = H5Gclose(cellGroupId);

  err = H5Gclose(gid);
  return err;
}
Exemple #23
0
void UpdateLevelOfDetailJob::updateEntityLodByScreenArea(Entity *entity, LevelOfDetail *lod)
{
    QMatrix4x4 viewMatrix;
    QMatrix4x4 projectionMatrix;
    if (!Render::CameraLens::viewMatrixForCamera(m_manager->renderNodesManager(), lod->camera(), viewMatrix, projectionMatrix))
        return;

    PickingUtils::ViewportCameraAreaGatherer vcaGatherer(lod->camera());
    const QVector<PickingUtils::ViewportCameraAreaTriplet> vcaTriplets = vcaGatherer.gather(m_frameGraphRoot);
    if (vcaTriplets.isEmpty())
        return;

    const PickingUtils::ViewportCameraAreaTriplet &vca = vcaTriplets.front();

    const QVector<qreal> thresholds = lod->thresholds();
    Sphere bv(lod->center(), lod->radius());
    if (!lod->hasBoundingVolumeOverride() && entity->worldBoundingVolume() != nullptr) {
        bv = *(entity->worldBoundingVolume());
    } else {
        bv.transform(*entity->worldTransform());
    }

    bv.transform(projectionMatrix * viewMatrix);
    const float sideLength = bv.radius() * 2.f;
    float area = vca.viewport.width() * sideLength * vca.viewport.height() * sideLength;

    const QRect r = windowViewport(vca.area, vca.viewport);
    area =  std::sqrt(area * r.width() * r.height());

    const int n = thresholds.size();
    for (int i = 0; i < n; ++i) {
        if (thresholds[i] < area || i == n -1) {
            m_filterValue = approxRollingAverage<30>(m_filterValue, i);
            i = qBound(0, static_cast<int>(qRound(m_filterValue)), n - 1);
            if (lod->currentIndex() != i)
                lod->setCurrentIndex(i);
            break;
        }
    }
}
Exemple #24
0
void MapEditor::generateRandom()
{
    setWindowTitle(name + " - " + "random map(unsaved)");
    fileSaved = false;
    QVector<QVector<QPointF> > m;
    for (int i = 0; i < 15; i++)
    {
        QVector<QPointF> l;
        int w = qMax(qrand() % 400, 10);
        int h = qMax(qrand() % 300, 10);
        int px = qrand() % (editArea->width() - w);
        int py = qrand() % (editArea->height() - h);
        for (int j = 0; j < 5; j++)
        {
            l.append(QPointF(px + qrand() % w, py + qrand() % h));
        }
        if (qrand() % 5 == 0)
            l.append(l.front());
        m.append(l);
    }
    editArea->setMap(m);
}
Exemple #25
0
QVector<double> xVector(QVector<QVector<double>> a, QVector<double> b1)
{
    QVector<QVector<double>> b2;
    for(auto y : b1)
    {
        b2.push_back(QVector<double>(1,y));
    }
    QVector<QVector<double>> aT = transpose(a);
    QVector<QVector<double>> atA = multipl(aT,a);
    QVector<QVector<double>> invAtA = inverse(atA);
    QVector<QVector<double>> atB = multipl(aT,b2);
    QVector<QVector<double>> x = multipl(invAtA,atB);
    QVector<double> result;
    if(x.front().size()==1)
    {
        qDebug() << "Вектор икс получен";
        for(auto row : x)
        {
            result.push_back(row.front());
        }
    }
    return result;
}
//Input Port #0: Buffer_Size = 10, Params_Type = SensorInternalEvent_Sensor_Joystick_Params, Data_Type = SensorInternalEvent_Sensor_Joystick_Data
bool DECOFUNC(processMonoDrainData)(void * paramsPtr, void * varsPtr, QVector<void *> drainParams, QVector<void *> drainData)
{
	SourceDrainMono_Sensor_stm32comm_Params * params=(SourceDrainMono_Sensor_stm32comm_Params *)paramsPtr;
	SourceDrainMono_Sensor_stm32comm_Vars * vars=(SourceDrainMono_Sensor_stm32comm_Vars *)varsPtr;
	QVector<SensorInternalEvent_Sensor_Joystick_Params *> drainparams; copyQVector(drainparams,drainParams);
	QVector<SensorInternalEvent_Sensor_Joystick_Data *> draindata; copyQVector(draindata,drainData);
	if(draindata.size()==0){return 0;}
	/*======Please Program below======*/
	/*
	Function: process draindata.
	*/
    SensorInternalEvent_Sensor_Joystick_Data* inputdata = draindata.front();
    double left_vel = inputdata->linear_vel + params->WheelBase*inputdata->angular_vel/2;
    double right_vel = inputdata->linear_vel - params->WheelBase*inputdata->angular_vel/2;


//    double left_motor = left_vel*25*4096/(2*vars->pi*params->WheelRadius)/100; //编码器1024线,4倍频后转一圈4096脉冲,电机是25:1(单位脉冲/10ms)
//    double right_motor = right_vel*25*4096/(2*vars->pi*params->WheelRadius)/100; //编码器1024线,4倍频后转一圈4096脉冲,电机是25:1(单位脉冲/10ms)
    ///20150328 没装编码器前的测试
    short left_motor = left_vel * 1000;
    short right_motor = right_vel * 1000;

    char dataput[7];
    char data_size = 4;
    dataput[0] = params->send_packhead.at(0);
    dataput[1] = data_size;
    *(short*)&dataput[2] = (short)left_motor;
    *(short*)&dataput[4] = (short)right_motor;
    dataput[6] = params->send_packtail.at(0);

    int n = vars->serialport->write(dataput, 7);
    if(n < 0)
    {
        return 0;
    }
	return 1;
}
Exemple #27
0
void TaskSheet::prepareCrossingSheet()
{
	Structure::Node * n = node();

	//QVector<Structure::Link*> edges = filterEdges(n, active->getEdges(n->id));

	// For now, let us only use one edge:
	QVector<Structure::Link*> edges;
	edges.push_back( filterEdges(n, active->getEdges(n->id)).front() );

	if (edges.size() == 1)
	{
		// Start and end
		Link * link = edges.front();
		Vector3d start = link->positionOther(n->id);
		NodeCoord futureNodeCord = futureLinkCoord(link);
		Vector3d end = active->position(futureNodeCord.first,futureNodeCord.second);

		// Geodesic distances on the active graph excluding the running tasks
		QVector< GraphDistance::PathPointPair > path;
		QVector<QString> exclude = active->property["activeTasks"].value< QVector<QString> >();
		GraphDistance gd( active, exclude );
		gd.computeDistances( end, DIST_RESOLUTION );  
		gd.smoothPathCoordTo( start, path );

		// Check
		if(path.size() < 2) { path.clear(); path.push_back(GraphDistance::PathPointPair( PathPoint(futureNodeCord.first, futureNodeCord.second))); }

		property["path"].setValue( GraphDistance::positionalPath(active, path) );

		// Save links paths
		path.back() = GraphDistance::PathPointPair( PathPoint(futureNodeCord.first, futureNodeCord.second)  );
		link->setProperty("path", path);
	}

	property["edges"].setValue( active->getEdgeIDs(edges) );
}
Exemple #28
0
QVector<QVector<double>> inverse(QVector<QVector<double>> a)
{
    int m = a.size();
    int n = a.front().size();
    if(n!=m)
    {
        qDebug() << "n!=m";
        return a;
    }

    //Единичная матрица
    QVector<double> e(n,0);
    QVector<QVector<double>> one(n,e);
    for(int i =0; i<n;i++)
    {
        one[i][i]=1;
    }
    //Объединение
    for(int i = 0; i < n; i++)
    {
        a[i]+=one[i];
    }

    int nn=n+n;
    //Прямой ход
    for(int k = 0; k < m; k++)
    {
        double akk = a[k][k];
        if(akk==0)
        {
            qDebug() << "front element equal 0";
        }
        for(int i = 0; i<nn; i++)
        {
            if(a[k][i]!=0)
            {
                a[k][i]/=akk;
            }
        }
        for(int i = k+1; i<m; i++)
        {
            double front_el = a[i][k];
            for(int j = k; j<nn; j++)
            {
                a[i][j]-=front_el*a[k][j];
            }
        }
    }

    for(int k = m-1; k>=0; k--)
    {
        for(int i = k-1; i>=0; i--)
        {
            double front_el = a[i][k];
            for(int j = k; j<nn;j++)
            {
                a[i][j]-=front_el*a[k][j];
            }
        }
    }
    QVector<QVector<double>> L;
    for(int i = 0; i<m;i++)
    {
        QVector<double> tmp;
        tmp = a[i];
        tmp.erase(tmp.begin()+n,tmp.end());
        L.push_back(tmp);
        a[i].erase(a[i].begin(),a[i].begin()+n);
    }
    return a;
}
//Input Port #0: Buffer_Size = 1, Params_Type = SensorTimer_Sensor_Laser_Params, Data_Type = SensorTimer_Sensor_Laser_Data
bool DECOFUNC(processMonoDrainData)(void * paramsPtr, void * varsPtr, QVector<void *> drainParams, QVector<void *> drainData)
{
	VisualizationMono_Sensor_Laser_Params * params=(VisualizationMono_Sensor_Laser_Params *)paramsPtr;
	VisualizationMono_Sensor_Laser_Vars * vars=(VisualizationMono_Sensor_Laser_Vars *)varsPtr;
	QVector<SensorTimer_Sensor_Laser_Params *> drainparams; copyQVector(drainparams,drainParams);
	QVector<SensorTimer_Sensor_Laser_Data *> draindata; copyQVector(draindata,drainData);
    if(draindata.size()==0)
    {
        vars->beams->setText("No Data");
        return 0;
    }
    /*======Please Program below======*/
    /*
    Function: process draindata.
    */
    vars->startangle=90+drainparams.front()->first_step*0.25;
    vars->endtangle=90+drainparams.front()->last_step*0.25;
    vars->resolution=drainparams.front()->skip_step*0.25;

    QImage image;
    if(params->frontonly)
    {
        image=QImage(params->imageradius*2,params->imageradius,QImage::Format_RGBA8888);
    }
    else
    {
        image=QImage(params->imageradius*2,params->imageradius*2,QImage::Format_RGBA8888);
    }
    image.fill(32);
    vars->painter.begin(&image);

    QPen centerpen(QColor(255,0,0,255));
    QPen gridpen(QColor(0,255,0,128));
    QPen beampen(QColor(0,0,255,196));
    QPen textpen(Qt::black);
    int i,n;

    vars->painter.setPen(gridpen);
    vars->painter.setBrush(Qt::NoBrush);
    n=params->range/params->interval;
    int radiusstep=params->imageradius/n;
    int centerx=params->imageradius;
    int centery=params->imageradius;
    for(i=1;i<=n;i++)
    {
        int radius=i*radiusstep;
        vars->painter.drawEllipse(QPoint(centerx,centery),radius,radius);
    }

    centerx=params->imageradius-params->calib_width/2;
    centery=params->imageradius - params->calib_height;

    vars->painter.setPen(centerpen);
    vars->painter.setBrush(QBrush(Qt::red,Qt::SolidPattern));
    vars->painter.drawEllipse(QPoint(centerx,centery),2,2);

    vars->painter.setPen(beampen);
    double ratio=double(params->imageradius)/double(params->range);
    n=draindata.front()->datasize;

    double pi=3.1415926535897932384626433832795/180.0;
    //left laser visual
    for(i=0;i<n;i++)
    {
        double theta=(vars->startangle+vars->resolution*i)*pi;
        double distance=ratio*(draindata.front()->ldata[i]);
        int x=int(distance*cos(theta)+0.5);
        int y=int(-distance*sin(theta)+0.5);
        if(params->laserbeam)
        {
            vars->painter.drawLine(centerx,centery,x+centerx,y+centery);
        }
        else
        {
            vars->painter.drawEllipse(x+centerx,y+centery,2,2);
        }
    }
    //right laser visual
    centerx=params->imageradius + params->calib_width/2;
    centery=params->imageradius - params->calib_height;

    vars->painter.setPen(centerpen);
    vars->painter.setBrush(QBrush(Qt::red,Qt::SolidPattern));
    vars->painter.drawEllipse(QPoint(centerx,centery),2,2);


    vars->painter.setPen(beampen);
    for(i=0;i<n;i++)
    {
        double theta=(vars->startangle+vars->resolution*i)*pi;
        double distance=ratio*(draindata.front()->rdata[i]);
        int x=int(distance*cos(theta)+0.5);
        int y=int(-distance*sin(theta)+0.5);
        if(params->laserbeam)
        {
            vars->painter.drawLine(centerx,centery,x+centerx,y+centery);
        }
        else
        {
            vars->painter.drawEllipse(x+centerx,y+centery,2,2);
        }
    }

    QFontMetrics fm=vars->painter.fontMetrics();
    int height=fm.ascent()+fm.descent();
    vars->painter.setPen(textpen);
    vars->painter.drawText(0,height,QString("Interval = %1 cm").arg(params->interval));
    vars->painter.drawText(0,height*2,QString("System Time: %1").arg(draindata.front()->qtimestamp.toString("HH:mm:ss:zzz")));
    vars->painter.drawText(0,height*3,QString("URG Time: %1").arg(draindata.front()->timestamp));

    vars->painter.end();
    vars->beams->setPixmap(QPixmap::fromImage(image));
    return 1;
	
	return 1;
}
Exemple #30
0
void QSvgText::draw(QPainter *p, QSvgExtraStates &states)
{
    applyStyle(p, states);
    qreal oldOpacity = p->opacity();
    p->setOpacity(oldOpacity * states.fillOpacity);

    // Force the font to have a size of 100 pixels to avoid truncation problems
    // when the font is very small.
    qreal scale = 100.0 / p->font().pointSizeF();
    Qt::Alignment alignment = states.textAnchor;

    QTransform oldTransform = p->worldTransform();
    p->scale(1 / scale, 1 / scale);

    qreal y = 0;
    bool initial = true;
    qreal px = m_coord.x() * scale;
    qreal py = m_coord.y() * scale;
    QSizeF scaledSize = m_size * scale;

    if (m_type == TEXTAREA) {
        if (alignment == Qt::AlignHCenter)
            px += scaledSize.width() / 2;
        else if (alignment == Qt::AlignRight)
            px += scaledSize.width();
    }

    QRectF bounds;
    if (m_size.height() != 0)
        bounds = QRectF(0, py, 1, scaledSize.height()); // x and width are not used.

    bool appendSpace = false;
    QVector<QString> paragraphs;
    QStack<QTextCharFormat> formats;
    QVector<QList<QTextLayout::FormatRange> > formatRanges;
    paragraphs.push_back(QString());
    formatRanges.push_back(QList<QTextLayout::FormatRange>());

    for (int i = 0; i < m_tspans.size(); ++i) {
        if (m_tspans[i] == LINEBREAK) {
            if (m_type == TEXTAREA) {
                if (paragraphs.back().isEmpty()) {
                    QFont font = p->font();
                    font.setPixelSize(font.pointSizeF() * scale);

                    QTextLayout::FormatRange range;
                    range.start = 0;
                    range.length = 1;
                    range.format.setFont(font);
                    formatRanges.back().append(range);

                    paragraphs.back().append(QLatin1Char(' '));;
                }
                appendSpace = false;
                paragraphs.push_back(QString());
                formatRanges.push_back(QList<QTextLayout::FormatRange>());
            }
        } else {
            WhitespaceMode mode = m_tspans[i]->whitespaceMode();
            m_tspans[i]->applyStyle(p, states);

            QFont font = p->font();
            font.setPixelSize(font.pointSizeF() * scale);

            QString newText(m_tspans[i]->text());
            newText.replace(QLatin1Char('\t'), QLatin1Char(' '));
            newText.replace(QLatin1Char('\n'), QLatin1Char(' '));

            bool prependSpace = !appendSpace && !m_tspans[i]->isTspan() && (mode == Default) && !paragraphs.back().isEmpty() && newText.startsWith(QLatin1Char(' '));
            if (appendSpace || prependSpace)
                paragraphs.back().append(QLatin1Char(' '));

            bool appendSpaceNext = (!m_tspans[i]->isTspan() && (mode == Default) && newText.endsWith(QLatin1Char(' ')));

            if (mode == Default) {
                newText = newText.simplified();
                if (newText.isEmpty())
                    appendSpaceNext = false;
            }

            QTextLayout::FormatRange range;
            range.start = paragraphs.back().length();
            range.length = newText.length();
            range.format.setFont(font);
            range.format.setTextOutline(p->pen());
            range.format.setForeground(p->brush());

            if (appendSpace) {
                Q_ASSERT(!formatRanges.back().isEmpty());
                ++formatRanges.back().back().length;
            } else if (prependSpace) {
                --range.start;
                ++range.length;
            }
            formatRanges.back().append(range);

            appendSpace = appendSpaceNext;
            paragraphs.back() += newText;

            m_tspans[i]->revertStyle(p, states);
        }
    }

    if (states.svgFont) {
        // SVG fonts not fully supported...
        QString text = paragraphs.front();
        for (int i = 1; i < paragraphs.size(); ++i) {
            text.append(QLatin1Char('\n'));
            text.append(paragraphs[i]);
        }
        states.svgFont->draw(p, m_coord * scale, text, p->font().pointSizeF() * scale, states.textAnchor);
    } else {
        for (int i = 0; i < paragraphs.size(); ++i) {
            QTextLayout tl(paragraphs[i]);
            QTextOption op = tl.textOption();
            op.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
            tl.setTextOption(op);
            tl.setAdditionalFormats(formatRanges[i]);
            tl.beginLayout();

            forever {
                QTextLine line = tl.createLine();
                if (!line.isValid())
                    break;
                if (m_size.width() != 0)
                    line.setLineWidth(scaledSize.width());
            }
            tl.endLayout();

            bool endOfBoundsReached = false;
            for (int i = 0; i < tl.lineCount(); ++i) {
                QTextLine line = tl.lineAt(i);

                qreal x = 0;
                if (alignment == Qt::AlignHCenter)
                    x -= 0.5 * line.naturalTextWidth();
                else if (alignment == Qt::AlignRight)
                    x -= line.naturalTextWidth();

                if (initial && m_type == TEXT)
                    y -= line.ascent();
                initial = false;

                line.setPosition(QPointF(x, y));

                // Check if the current line fits into the bounding rectangle.
                if ((m_size.width() != 0 && line.naturalTextWidth() > scaledSize.width())
                    || (m_size.height() != 0 && y + line.height() > scaledSize.height())) {
                    // I need to set the bounds height to 'y-epsilon' to avoid drawing the current
                    // line. Since the font is scaled to 100 units, 1 should be a safe epsilon.
                    bounds.setHeight(y - 1);
                    endOfBoundsReached = true;
                    break;
                }

                y += 1.1 * line.height();
            }
            tl.draw(p, QPointF(px, py), QVector<QTextLayout::FormatRange>(), bounds);

            if (endOfBoundsReached)
                break;
        }
    }

    p->setWorldTransform(oldTransform, false);
    p->setOpacity(oldOpacity);
    revertStyle(p, states);
}