Foam::point Foam::CatmullRomSpline::position
(
    const label segment,
    const scalar mu
) const
{
    // out-of-bounds
    if (segment < 0)
    {
        return points().first();
    }
    else if (segment > nSegments())
    {
        return points().last();
    }

    const point& p0 = points()[segment];
    const point& p1 = points()[segment+1];

    // special cases - no calculation needed
    if (mu <= 0.0)
    {
        return p0;
    }
    else if (mu >= 1.0)
    {
        return p1;
    }


    // determine the end points
    point e0;
    point e1;

    if (segment == 0)
    {
        // end: simple reflection
        e0 = 2*p0 - p1;
    }
    else
    {
        e0 = points()[segment-1];
    }

    if (segment+1 == nSegments())
    {
        // end: simple reflection
        e1 = 2*p1 - p0;
    }
    else
    {
        e1 = points()[segment+2];
    }


    return 0.5 *
    (
        ( 2*p0 )
      + mu *
        (
            ( -e0 + p1 )
          + mu *
            (
                ( 2*e0 - 5*p0 + 4*p1 - e1 )
              + mu *
                ( -e0 + 3*p0 - 3*p1 + e1 )
            )
        )
    );
}
Exemplo n.º 2
0
// virtual
bool MayaNurbsCurveWriter::writeNurbsCurveAttrs(const UsdTimeCode &usdTime, UsdGeomNurbsCurves &primSchema)
{
    MStatus status = MS::kSuccess;

    // Write parent class attrs
    writeTransformAttrs(usdTime, primSchema);

    // Return if usdTime does not match if shape is animated
    if (usdTime.IsDefault() == isShapeAnimated() ) {
        // skip shape as the usdTime does not match if shape isAnimated value
        return true; 
    }

    MFnDependencyNode fnDepNode(getDagPath().node(), &status);
    MString name = fnDepNode.name();

    MFnNurbsCurve curveFn( getDagPath(), &status );
    if (!status) {
        MGlobal::displayError("MFnNurbsCurve() failed for MayaNurbsCurveWriter");
        return false;
    }

    // Get curve attrs ======
    unsigned int numCurves = 1; // Assuming only 1 curve for now
    VtArray<int> curveOrder(numCurves);
    VtArray<int> curveVertexCounts(numCurves);
    VtArray<float> curveWidths(numCurves);
    VtArray<GfVec2d> ranges(numCurves);

    curveOrder[0] = curveFn.degree()+1;
    curveVertexCounts[0] = curveFn.numCVs();
    TF_AXIOM(curveOrder[0] <= curveVertexCounts[0] );
    curveWidths[0] = 1.0; // TODO: Retrieve from custom attr

    double mayaKnotDomainMin;
    double mayaKnotDomainMax;
    status = curveFn.getKnotDomain(mayaKnotDomainMin, mayaKnotDomainMax);
    TF_AXIOM(status == MS::kSuccess);
    ranges[0][0] = mayaKnotDomainMin;
    ranges[0][1] = mayaKnotDomainMax;

    MPointArray mayaCurveCVs;
    status = curveFn.getCVs(mayaCurveCVs, MSpace::kObject);
    TF_AXIOM(status == MS::kSuccess);
    VtArray<GfVec3f> points(mayaCurveCVs.length()); // all CVs batched together
    for (unsigned int i=0; i < mayaCurveCVs.length(); i++) {
        points[i].Set(mayaCurveCVs[i].x, mayaCurveCVs[i].y, mayaCurveCVs[i].z);
    }

    MDoubleArray mayaCurveKnots;
    status = curveFn.getKnots(mayaCurveKnots);
    TF_AXIOM(status == MS::kSuccess);
    VtArray<double> curveKnots(mayaCurveKnots.length()); // all knots batched together
    for (unsigned int i=0; i < mayaCurveKnots.length(); i++) {
        curveKnots[i] = mayaCurveKnots[i];
    }

    // Gprim
    VtArray<GfVec3f> extent(2);
    UsdGeomCurves::ComputeExtent(points, curveWidths, &extent);
    primSchema.CreateExtentAttr().Set(extent, usdTime);

    // Curve
    primSchema.GetOrderAttr().Set(curveOrder);   // not animatable
    primSchema.GetCurveVertexCountsAttr().Set(curveVertexCounts); // not animatable
    primSchema.GetWidthsAttr().Set(curveWidths); // not animatable
    primSchema.GetKnotsAttr().Set(curveKnots);   // not animatable
    primSchema.GetRangesAttr().Set(ranges); // not animatable
    primSchema.GetPointsAttr().Set(points, usdTime); // CVs

    // TODO: Handle periodic and non-periodic cases

    return true;
}
Exemplo n.º 3
0
void mexFunction(int nlhs, mxArray  *plhs[], int nrhs, const mxArray  *prhs[])
{	
	int ref_or_direct = 1;			// ref_or_direct = 1 means interpret second input argument as reference indices
									// = 0 means interpret second input argument as reference vectors
	
	long past = 0;
	double epsilon = 0;
	
	/* check input args */
	
	if (nrhs < 4)
	{
		mexErrMsgTxt("Fast nearest neighbour searcher : Data set of points (row vectors), preprocessing data, reference indices or reference points \nand number of nearest neighbours must be given, epsilon (default = 0) is optional");
		return;
	}
	
	/* handle matrix I/O */
	
	const long N 		= mxGetM(prhs[0]);	
	const long dim  	= mxGetN(prhs[0]);
	const double* p 	= (double *)mxGetPr(prhs[0]);
	
	double* ref 	= (double *)mxGetPr(prhs[2]);
	long R; 										// number of query (reference) points
	
	const long NNR 	= (long) *((double *)mxGetPr(prhs[3]));
	
	if (N < 1) {
		mexErrMsgTxt("Data set must consist of at least two points (row vectors)");
		return;
	}		
	if (dim < 1) {
		mexErrMsgTxt("Data points must be at least of dimension one");
		return;
	}	
	if (NNR<1) {
		mexErrMsgTxt("At least one nearest neighbour must be requested");
		return;
	}	
	if ((mxGetN(prhs[2]) == 0) || (mxGetN(prhs[2]) == 0)) {
		mexErrMsgTxt("Wrong reference indices or reference points given");
		return;
	}	

	
	if (mxGetN(prhs[2]) == 1) {
		R = mxGetM(prhs[2]);
		ref_or_direct = 1;	
	} 
	else if ((mxGetM(prhs[2]) == 1) && (mxGetN(prhs[2]) != dim)) {
		R = mxGetN(prhs[2]);
		ref_or_direct = 1;	
	}
	else if (mxGetN(prhs[2]) == dim) {
		R = mxGetM(prhs[2]);
		ref_or_direct = 0;	
	} else  {
		mexErrMsgTxt("Cannot determine if second argument are reference indices or reference points");
		return;
	}	
	
/*******************************/
/*** Quick&Dirty patch, to manage onedimensional "direct" query-points. I. Wedekind, 16.9.2002 */
	if((mxGetN(prhs[2])==dim) && (ref_or_direct==1) && (nrhs<5))
	    {
		ref_or_direct=0;
	    }
/*******************************/

	if (R < 1) {
		mexErrMsgTxt("At least one reference index or point must be given");
		return;
	}	

	if (ref_or_direct) {		// interpret second argument as list of indices into the data set given as first argument 
		if (nrhs < 5)
		{
			mexErrMsgTxt("Fast nearest neighbour searcher : Data set of points (row vectors), preprocessing data, reference indices,\nnumber of nearest neighbours and past must be given");
			return;
		}
		past	= (long) *((double *)mxGetPr(prhs[4]));
		for (long i=0; i < R; i++) {
			if ((ref[i] < 1) || (ref[i]>N)) {
				mexErrMsgTxt("Reference indices out of range");
				return;
			}	
		}
		if ((N - (2*past)-1) < NNR)
		{
			mexErrMsgTxt("Fast nearest neighbour searcher : To many neighbors for each query point are requested");
			return;
		}
		if (nrhs > 5) 
			epsilon = (double) *((double *)mxGetPr(prhs[5]));		// support approximative queries		
	}  else {
		if (nrhs > 4) 
			epsilon = (double) *((double *)mxGetPr(prhs[4]));		// support approximative queries	
	}
	
	plhs[0] = mxCreateDoubleMatrix(R, NNR, mxREAL);
	double* nn = (double *) mxGetPr(plhs[0]);
	
	double* dists;
	
	if (nlhs > 1) {
		plhs[1] = mxCreateDoubleMatrix(R, NNR, mxREAL);
		dists = (double *) mxGetPr(plhs[1]);
	} else
		dists = (double *) malloc(R*NNR * sizeof(double));
	
	char* metric = 0;
	
	if (mxIsChar(mxGetField(prhs[1], 0, "optional"))) {	
    	long buflen = (mxGetM(mxGetField(prhs[1], 0, "optional")) * mxGetN(mxGetField(prhs[1], 0, "optional"))) + 1;
 		metric = (char*) mxMalloc(buflen);
        mxGetString(mxGetField(prhs[1], 0, "optional"), metric, buflen); 
	}
	
	if ((metric == 0) || (!strncmp("euclidian", metric, strlen(metric)))) {
		point_set<euclidian_distance> points(N,dim, p);	
		ATRIA< point_set<euclidian_distance> > searcher(points, prhs[1]);	// this constructor used the data from the preprocessing that are given by the second input argument
#ifdef PROFILE
		cout << "read in atria structure" << endl;
#endif	
		nn_search(searcher, nn, dists, R, N, dim, p, ref, NNR, past, epsilon, ref_or_direct);
		if (nlhs > 2) {
			plhs[2] = mxCreateDoubleMatrix(1, 1, mxREAL);
			*((double *) mxGetPr(plhs[2])) = searcher.search_efficiency();
		}	
	}
	else if (!strncmp("maximum", metric, strlen(metric))){
		point_set<maximum_distance> points(N,dim, p);	
		ATRIA< point_set<maximum_distance> > searcher(points, prhs[1]);
#ifdef PROFILE
		cout << "read in atria structure" << endl;
#endif		
		nn_search(searcher, nn, dists, R, N, dim, p, ref, NNR, past, epsilon, ref_or_direct);
		if (nlhs > 2) {
			plhs[2] = mxCreateDoubleMatrix(1, 1, mxREAL);
			*((double *) mxGetPr(plhs[2])) = searcher.search_efficiency();
		}		
	}
	else {
		mexErrMsgTxt("Unknown type of metric used to create ATRIA structure");
	}
		
	mxFree(metric);		
			
	if (!(nlhs > 1)) free(dists);
}	
void TestExportHighMesh(const char *filename, int frame_count)
{
    auto *ctx = usdiCreateContext();

    usdi::ExportSettings settings;
    settings.instanceable_by_default = true;
    usdiSetExportSettings(ctx, &settings);

    usdiCreateStage(ctx, filename);
    auto *root = usdiGetRoot(ctx);

    auto *xf = usdiCreateXform(ctx, root, "WaveMeshRoot");
    usdiPrimSetInstanceable(xf, true);
    {
        usdi::XformData data;
        usdiXformWriteSample(xf, &data);
    }

    auto *mesh = usdiCreateMesh(ctx, xf, "WaveMesh");
    {
        std::vector<std::vector<int>> counts(frame_count);
        std::vector<std::vector<int>> indices(frame_count);
        std::vector<std::vector<float3>> points(frame_count);
        std::vector<std::vector<float2>> uv(frame_count);
        std::vector<std::vector<float4>> colors(frame_count);

        usdi::Time t = 0.0;

        tbb::parallel_for(0, frame_count, [frame_count, &counts, &indices, &points, &uv, &colors](int i) {
            usdi::Time t = i;
            int resolution = 8;
            if (i < 30)      { resolution = 8; }
            else if (i < 60) { resolution = 16; }
            else if (i < 90) { resolution = 32; }
            else if (i < 120) { resolution = 64; }
            else if (i < 150) { resolution = 128; }
            else { resolution = 256; }
            GenerateWaveMesh(counts[i], indices[i], points[i], uv[i], 1.0f, 0.5f, resolution, (360.0 * 5 * DegToRad / frame_count) * i);

            auto& color = colors[i];
            color.resize(points[i].size());
            for (size_t ci = 0; ci < color.size(); ++ci) {
                color[ci] = {
                    std::sin((float)i * DegToRad * 2.1f) * 0.5f + 0.5f,
                    std::cos((float)i * DegToRad * 6.8f) * 0.5f + 0.5f,
                    std::sin((float)i * DegToRad * 11.7f) * 0.5f + 0.5f,
                    1.0f
                };
            }
        });
        for (int i = 0; i < frame_count; ++i) {
            auto& vertices = points[i];

            usdi::Time t = i;
            usdi::MeshData data;
            data.counts = counts[i].data();
            data.num_counts = counts[i].size();
            data.indices = indices[i].data();
            data.num_indices = indices[i].size();
            data.points = points[i].data();
            data.num_points = points[i].size();
            data.uvs = uv[i].data();
            data.colors = colors[i].data();
            usdiMeshWriteSample(mesh, &data, t);
        }

        usdiMeshPreComputeNormals(mesh, false);
        //usdiMeshPreComputeNormals(mesh, true);
    }

    {
        auto *ref1 = usdiCreateXform(ctx, root, "WaveMeshRef1");
        usdi::XformData data;
        data.position.x = 1.5f;
        usdiXformWriteSample(ref1, &data);

        auto *ref = usdiCreateOverride(ctx, "/WaveMeshRef1/Ref");
        usdiPrimAddReference(ref, nullptr, "/WaveMeshRoot");
    }
    {
        auto *ref2 = usdiCreateXform(ctx, root, "WaveMeshRef2");
        usdi::XformData data;
        data.position.x = -1.5f;
        usdiXformWriteSample(ref2, &data);

        auto *ref = usdiCreateOverride(ctx, "/WaveMeshRef2/Ref");
        usdiPrimAddReference(ref, nullptr, "/WaveMeshRoot");
    }

    usdiSave(ctx);
    usdiDestroyContext(ctx);
}
Exemplo n.º 5
0
// virtual
bool MayaMeshWriter::writeMeshAttrs(const UsdTimeCode &usdTime, UsdGeomMesh &primSchema)
{

    MStatus status = MS::kSuccess;

    // Write parent class attrs
    writeTransformAttrs(usdTime, primSchema);

    // Return if usdTime does not match if shape is animated
    if (usdTime.IsDefault() == isShapeAnimated() ) {
        // skip shape as the usdTime does not match if shape isAnimated value
        return true; 
    }

    MFnMesh lMesh( getDagPath(), &status );
    if ( !status )
    {
        MGlobal::displayError( "MFnMesh() failed for MayaMeshWriter" );
        return false;
    }
    unsigned int numVertices = lMesh.numVertices();
    unsigned int numPolygons = lMesh.numPolygons();

    // Set mesh attrs ==========
    // Get points
    // TODO: Use memcpy()
    const float* mayaRawPoints = lMesh.getRawPoints(&status);
    VtArray<GfVec3f> points(numVertices);
    for (unsigned int i = 0; i < numVertices; i++) {
        unsigned int floatIndex = i*3;
        points[i].Set(mayaRawPoints[floatIndex],
                      mayaRawPoints[floatIndex+1],
                      mayaRawPoints[floatIndex+2]);
    }
    primSchema.GetPointsAttr().Set(points, usdTime); // ANIMATED

    // Compute the extent using the raw points
    VtArray<GfVec3f> extent(2);
    UsdGeomPointBased::ComputeExtent(points, &extent);
    primSchema.CreateExtentAttr().Set(extent, usdTime);

    // Get faceVertexIndices
    unsigned int numFaceVertices = lMesh.numFaceVertices(&status);
    VtArray<int>     faceVertexCounts(numPolygons);
    VtArray<int>     faceVertexIndices(numFaceVertices);
    MIntArray mayaFaceVertexIndices; // used in loop below
    unsigned int curFaceVertexIndex = 0;
    for (unsigned int i = 0; i < numPolygons; i++) {
        lMesh.getPolygonVertices(i, mayaFaceVertexIndices);
        faceVertexCounts[i] = mayaFaceVertexIndices.length();
        for (unsigned int j=0; j < mayaFaceVertexIndices.length(); j++) {
            faceVertexIndices[ curFaceVertexIndex ] = mayaFaceVertexIndices[j]; // push_back
            curFaceVertexIndex++;
        }
    }
    primSchema.GetFaceVertexCountsAttr().Set(faceVertexCounts);   // not animatable
    primSchema.GetFaceVertexIndicesAttr().Set(faceVertexIndices); // not animatable

    // Read usdSdScheme attribute. If not set, we default to defaultMeshScheme
    // flag that can be user defined and initialized to catmullClark
    TfToken sdScheme = PxrUsdMayaMeshUtil::getSubdivScheme(lMesh, getArgs().defaultMeshScheme);    
    primSchema.CreateSubdivisionSchemeAttr(VtValue(sdScheme), true);

    // Polygonal Mesh Case
    if (sdScheme==UsdGeomTokens->none) {
        // Support for standard USD bool and with Mojito bool tag
        TfToken normalInterp=PxrUsdMayaMeshUtil::getEmitNormals(lMesh, UsdGeomTokens->none);
        
        if (normalInterp==UsdGeomTokens->faceVarying) {
            // Get References to members of meshData object
            MFloatVectorArray normalArray;
            MFloatVectorArray vertexNormalArray;
 
            lMesh.getNormals(normalArray, MSpace::kObject);

            // Iterate through each face in the mesh.
            vertexNormalArray.setLength(lMesh.numFaceVertices());
            VtArray<GfVec3f> meshNormals(lMesh.numFaceVertices());
            size_t faceVertIdx = 0;
            for (MItMeshPolygon faceIter(getDagPath()); !faceIter.isDone(); faceIter.next()) {
                // Iterate through each face-vertex.
                for (size_t locVertIdx = 0; locVertIdx < faceIter.polygonVertexCount();
                        ++locVertIdx, ++faceVertIdx) {
                    int index=faceIter.normalIndex(locVertIdx);
                    for (int j=0;j<3;j++) {
                        meshNormals[faceVertIdx][j]=normalArray[index][j];
                    }
                }
            }
            primSchema.GetNormalsAttr().Set(meshNormals, usdTime);
            primSchema.SetNormalsInterpolation(normalInterp);
        }
    } else {
        TfToken sdInterpBound = PxrUsdMayaMeshUtil::getSubdivInterpBoundary(
            lMesh, UsdGeomTokens->edgeAndCorner);

        primSchema.CreateInterpolateBoundaryAttr(VtValue(sdInterpBound), true);
        
        TfToken sdFVInterpBound = PxrUsdMayaMeshUtil::getSubdivFVInterpBoundary(
            lMesh);

        primSchema.CreateFaceVaryingLinearInterpolationAttr(
            VtValue(sdFVInterpBound), true);

        assignSubDivTagsToUSDPrim( lMesh, primSchema);
    }

    // Holes - we treat InvisibleFaces as holes
    MUintArray mayaHoles = lMesh.getInvisibleFaces();
    if (mayaHoles.length() > 0) {
        VtArray<int> subdHoles(mayaHoles.length());
        for (unsigned int i=0; i < mayaHoles.length(); i++) {
            subdHoles[i] = mayaHoles[i];
        }
        // not animatable in Maya, so we'll set default only
        primSchema.GetHoleIndicesAttr().Set(subdHoles);
    }

    // == Write UVSets as Vec2f Primvars
    MStringArray uvSetNames;
    if (getArgs().exportMeshUVs) {
        status = lMesh.getUVSetNames(uvSetNames);
    }
    for (unsigned int i=0; i < uvSetNames.length(); i++) {
        // Initialize the VtArray to the max possible size (facevarying)
        VtArray<GfVec2f> uvValues(numFaceVertices);
        TfToken interpolation=TfToken();
        // Gather UV data and interpolation into a Vec2f VtArray and try to compress if possible
        if (_GetMeshUVSetData(lMesh, uvSetNames[i], &uvValues, &interpolation) == MS::kSuccess) {
        
            // XXX:bug 118447
            // We should be able to configure the UV map name that triggers this
            // behavior, and the name to which it exports.
            // The UV Set "map1" is renamed st. This is a Pixar/USD convention
            TfToken setName(uvSetNames[i].asChar());
            if (setName == "map1") setName=UsdUtilsGetPrimaryUVSetName();
       
            // Create the primvar and set the values
            UsdGeomPrimvar uvSet = 
                primSchema.CreatePrimvar(setName, SdfValueTypeNames->Float2Array, interpolation);
            uvSet.Set( uvValues ); // not animatable
        }
    }
    
    // == Gather ColorSets
    MStringArray colorSetNames;
    if (getArgs().exportColorSets) {
        status = lMesh.getColorSetNames(colorSetNames);
    }
    // shaderColor is used in our pipeline as displayColor.
    // shaderColor is used to fill faces where the colorset is not assigned
    MColorArray shaderColors;
    MObjectArray shaderObjs;
    
    VtArray<GfVec3f> shadersRGBData;
    TfToken shadersRGBInterp;
    VtArray<float> shadersAlphaData;
    TfToken shadersAlphaInterp;

    // If exportDisplayColor is set to true or we have color sets,
    // gather color & opacity from the shader including per face
    // assignment. Color set require this to initialize unauthored/unpainted faces 
    if (getArgs().exportDisplayColor or colorSetNames.length()>0) {
        PxrUsdMayaUtil::GetLinearShaderColor(lMesh, numPolygons, 
                &shadersRGBData, &shadersRGBInterp, 
                &shadersAlphaData, &shadersAlphaInterp);
    }

    for (unsigned int i=0; i < colorSetNames.length(); i++) {

        bool isDisplayColor=false;

        if (colorSetNames[i]=="displayColor") {
            if (not getArgs().exportDisplayColor)
                continue;
            isDisplayColor=true;
        }
        
        if (colorSetNames[i]=="displayOpacity") {
            MGlobal::displayWarning("displayOpacity on mesh:" + lMesh.fullPathName() + 
            " is a reserved PrimVar name in USD. Skipping...");
            continue;
        }

        VtArray<GfVec3f> RGBData;
        TfToken RGBInterp;
        VtArray<GfVec4f> RGBAData;
        TfToken RGBAInterp;
        VtArray<float> AlphaData;
        TfToken AlphaInterp;
        MFnMesh::MColorRepresentation colorSetRep;
        bool clamped=false;

        // If displayColor uses shaderValues for non authored areas
        // and allow RGB and Alpha to have different interpolation
        // For all other colorSets the non authored values are set 
        // to (1,1,1,1) and RGB and Alpha will have the same interplation
        // since they will be emitted as a Vec4f
        if (not _GetMeshColorSetData( lMesh, colorSetNames[i],
                                        isDisplayColor,
                                        shadersRGBData, shadersAlphaData,
                                        &RGBData, &RGBInterp,
                                        &RGBAData, &RGBAInterp,
                                        &AlphaData, &AlphaInterp,
                                        &colorSetRep, &clamped)) {
            MGlobal::displayWarning("Unable to retrieve colorSet data: " +
                    colorSetNames[i] + " on mesh: "+ lMesh.fullPathName() + ". Skipping...");
            continue;
        }

        if (isDisplayColor) {
            // We tag the resulting displayColor/displayOpacity primvar as
            // authored to make sure we reconstruct the colorset on import
            // The RGB is also convererted From DisplayToLinear
            
            
            _setDisplayPrimVar( primSchema, colorSetRep,
                                RGBData, RGBInterp,
                                AlphaData, AlphaInterp,
                                clamped, true);
        } else {
            TfToken colorSetNameToken = TfToken(
                    PxrUsdMayaUtil::SanitizeColorSetName(
                        std::string(colorSetNames[i].asChar())));
            if (colorSetRep == MFnMesh::kAlpha) {
                    _createAlphaPrimVar(primSchema, colorSetNameToken,
                        AlphaData, AlphaInterp, clamped);
            } else if (colorSetRep == MFnMesh::kRGB) {
                    _createRGBPrimVar(primSchema, colorSetNameToken,
                        RGBData, RGBInterp, clamped);
            } else if (colorSetRep == MFnMesh::kRGBA) {
                    _createRGBAPrimVar(primSchema, colorSetNameToken,
                        RGBAData, RGBAInterp, clamped);
            }
        }
    }
    // Set displayColor and displayOpacity only if they are NOT authored already
    // Since this primvar will come from the shader and not a colorset,
    // we are not adding the clamp attribute as custom data
    // If a displayColor/displayOpacity is added, it's not considered authored
    // we don't need to reconstruct this as a colorset since it orgininated
    // from bound shader[s], so the authored flag is set to false
    // Given that this RGB is for display, we do DisplayToLinear conversion
    if (getArgs().exportDisplayColor) {
        _setDisplayPrimVar( primSchema, MFnMesh::kRGBA,
                                shadersRGBData, shadersRGBInterp,
                                shadersAlphaData, shadersAlphaInterp,
                                false, false);
    }
    return true;
}
Exemplo n.º 6
0
void QgsMapToolSplitParts::cadCanvasReleaseEvent( QgsMapMouseEvent *e )
{
  //check if we operate on a vector layer
  QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( mCanvas->currentLayer() );

  if ( !vlayer )
  {
    notifyNotVectorLayer();
    return;
  }

  if ( !vlayer->isEditable() )
  {
    notifyNotEditableLayer();
    return;
  }

  bool split = false;

  //add point to list and to rubber band
  if ( e->button() == Qt::LeftButton )
  {
    //If we snap the first point on a vertex of a line layer, we directly split the feature at this point
    if ( vlayer->geometryType() == QgsWkbTypes::LineGeometry && points().isEmpty() )
    {
      QgsPointLocator::Match m = mCanvas->snappingUtils()->snapToCurrentLayer( e->pos(), QgsPointLocator::Vertex );
      if ( m.isValid() )
      {
        split = true;
      }
    }

    int error = addVertex( e->mapPoint() );
    if ( error == 1 )
    {
      //current layer is not a vector layer
      return;
    }
    else if ( error == 2 )
    {
      //problem with coordinate transformation
      QgisApp::instance()->messageBar()->pushMessage(
        tr( "Coordinate transform error" ),
        tr( "Cannot transform the point to the layers coordinate system" ),
        QgsMessageBar::INFO,
        QgisApp::instance()->messageTimeout() );
      return;
    }

    startCapturing();
  }
  else if ( e->button() == Qt::RightButton )
  {
    split = true;
  }
  if ( split )
  {
    deleteTempRubberBand();

    //bring up dialog if a split was not possible (polygon) or only done once (line)
    bool topologicalEditing = QgsProject::instance()->topologicalEditing();
    vlayer->beginEditCommand( tr( "Parts split" ) );
    QgsGeometry::OperationResult returnCode = vlayer->splitParts( points(), topologicalEditing );
    vlayer->endEditCommand();
    if ( returnCode == QgsGeometry::OperationResult::NothingHappened )
    {
      QgisApp::instance()->messageBar()->pushMessage(
        tr( "No parts were split" ),
        tr( "If there are selected parts, the split tool only applies to those. If you would like to split all parts under the split line, clear the selection." ),
        QgsMessageBar::WARNING,
        QgisApp::instance()->messageTimeout() );
    }
    else if ( returnCode == QgsGeometry::OperationResult::GeometryEngineError )
    {
      QgisApp::instance()->messageBar()->pushMessage(
        tr( "No part split done" ),
        tr( "Cut edges detected. Make sure the line splits parts into multiple parts." ),
        QgsMessageBar::WARNING,
        QgisApp::instance()->messageTimeout() );
    }
    else if ( returnCode == QgsGeometry::OperationResult::InvalidBaseGeometry )
    {
      QgisApp::instance()->messageBar()->pushMessage(
        tr( "No part split done" ),
        tr( "The geometry is invalid. Please repair before trying to split it." ),
        QgsMessageBar::WARNING,
        QgisApp::instance()->messageTimeout() );
    }
    else if ( returnCode != QgsGeometry::OperationResult::Success )
    {
      //several intersections but only one split (most likely line)
      QgisApp::instance()->messageBar()->pushMessage(
        tr( "Split error" ),
        tr( "An error occurred during splitting." ),
        QgsMessageBar::WARNING,
        QgisApp::instance()->messageTimeout() );
    }

    stopCapturing();
  }
}
Exemplo n.º 7
0
int main() {

    const unsigned oversample = 2;
    const unsigned w = 2048*oversample, h = 2048*oversample;
    cout << "allocating memory for a " << w << " x " << h << " image buffer..." << flush;
    simg img( w, h, {0, 0, 0, 255} );
    cout << " done." << endl;

    // list of points
    const int numpoints = 5;
    uniform_int_distribution<> dist_int( 0, numpoints-1 );
    vector< double[2] > points( numpoints );

    // radius: 0.5 will just touch the edges of the image
    const double rad = 0.99 * 0.5;
    // initial rotation: not important but makes each image unique
    const double rot = rand01();

    // distribute points evenly around a circle (not necessary, but makes it easy to compare)
    for( int p = 0; p < numpoints; p++ ) {
        double angle = (rot + ((double)p / numpoints)) * 2. * 3.14159265358979323846;
        points[p][0] = 0.5 + rad*cos(angle);
        points[p][1] = 0.5 + rad*sin(angle);
    }

    // additive RGBA (may be negative, usually want to leave alpha = 0)
    const srgba_light light = {10, 10, 10, 0};

    // a touchy constant: too big and the render appears fuzzy
    const double beta = 1. / 2.;


    // note: may need to try many different starting points to get a good image
    // * note: so far has worked with a single starting point
    double point[2] = { rand01(), rand01() };

    // how many times to plot the point: too big = slow
    const unsigned long numplots = 100000000;

    // do a render
    cout << "rendering " << numplots << " points..." << flush;
    for( unsigned long i = 0; i < numplots; i++ ) {
        
        // pick a point to move toward
        int p = dist_int( rand_gen );

        // compute new coordinates
        point[0] = points[p][0] + beta * ( point[0] - points[p][0] );
        point[1] = points[p][1] + beta * ( point[1] - points[p][1] );

        // plot point
        if( point[0] >= 0. && point[0] < 1. && point[1] >= 0. && point[1] < 1. ) {
            unsigned x = floor(point[0] * w);
            unsigned y = floor(point[1] * h);
            img.add( x, y, light );
        }
    }
    cout << " done." << endl;

    char filename[1024];
    sprintf( filename, "%d-points_%ux%u_%lu-samples.png", numpoints, w, h, numplots );

    img.save( string(filename) );

    return 0;
}
    int
    process(const tendrils& in, const tendrils& out)
    {
      cv::Mat depth = in.get<cv::Mat>("depth");
      if (depth.empty())
        return ecto::OK;

      cv::Mat R, T, K;
      in.get<cv::Mat>("R").convertTo(R, CV_64F);
      in.get<cv::Mat>("T").convertTo(T, CV_64F);
      in.get<cv::Mat>("K").convertTo(K, CV_64F);

      if (R.empty() || T.empty() || K.empty())
        return ecto::OK;

      cv::Mat mask = cv::Mat::zeros(depth.size(), CV_8UC1);

      box_mask.create(depth.size());
      box_mask.setTo(cv::Scalar(0));

      std::vector<cv::Point3f> box(8);
      box[0] = cv::Point3f(*x_crop, *y_crop, *z_min);
      box[1] = cv::Point3f(-*x_crop, *y_crop, *z_min);
      box[2] = cv::Point3f(-*x_crop, -*y_crop, *z_min);
      box[3] = cv::Point3f(*x_crop, -*y_crop, *z_min);
      box[4] = cv::Point3f(*x_crop, *y_crop, *z_crop);
      box[5] = cv::Point3f(-*x_crop, *y_crop, *z_crop);
      box[6] = cv::Point3f(-*x_crop, -*y_crop, *z_crop);
      box[7] = cv::Point3f(*x_crop, -*y_crop, *z_crop);

      std::vector<cv::Point2f> projected, hull;
      cv::projectPoints(box, R, T, K, cv::Mat(4, 1, CV_64FC1, cv::Scalar(0)), projected);

      cv::convexHull(projected, hull, true);
      std::vector<cv::Point> points(hull.size());
      std::copy(hull.begin(), hull.end(), points.begin());
      cv::fillConvexPoly(box_mask, points.data(), points.size(), cv::Scalar::all(255));

      int width = mask.size().width;
      int height = mask.size().height;
      cv::Mat_<uint8_t>::iterator it = mask.begin<uint8_t>();
      cv::Mat_<uint8_t>::iterator mit = box_mask.begin();

      cv::Mat_<cv::Vec3f> points3d;
      depthTo3dMask(K, depth, box_mask, points3d);
      if (points3d.empty())
        return ecto::OK;

      cv::Matx<double, 3, 1> p, p_r, Tx(T); //Translation
      cv::Matx<double, 3, 3> Rx; //inverse Rotation
      Rx = cv::Mat(R.t());
      cv::Mat_<cv::Vec3f>::iterator point = points3d.begin();

//      std::cout << cv::Mat(Rx) << "\n" << cv::Mat(Tx) << std::endl;
//      std::cout << fx << " " << fy << " " << cx << " " << cy << " " << std::endl;
      double z_min_ = *z_min, z_max_ = *z_crop, x_min_ = -*x_crop, x_max_ = *x_crop, y_min_ = -*y_crop,
          y_max_ = *y_crop;
      for (int v = 0; v < height; v++)
      {
        for (int u = 0; u < width; u++, ++it, ++mit)
        {
          if (*mit == 0)
            continue;
          //calculate the point based on the depth
          p(0) = (*point).val[0];
          p(1) = (*point).val[1];
          p(2) = (*point).val[2];
          ++point;
          p_r = Rx * (p - Tx);
//          std::cout <<"p=" << cv::Mat(p) << ",p_r="<< cv::Mat(p_r) << std::endl;
          if (p_r(2) > z_min_ && p_r(2) < z_max_ && p_r(0) > x_min_ && p_r(0) < x_max_ && p_r(1) > y_min_
              && p_r(1) < y_max_)
            *it = 255;
        }
      }
      out["mask"] << mask;
      return ecto::OK;
    }
Exemplo n.º 9
0
ON_BOOL32 ON_Light::GetBBox( // returns true if successful
       double* boxmin,    // boxmin[dim]
       double* boxmax,    // boxmax[dim]
       ON_BOOL32 bGrowBox
       ) const
{
  bool rc = true;
  ON_3dPointArray points(16);

  switch(m_style)
  {
  case ON::camera_directional_light:
  case ON::world_directional_light:
    points.Append(m_location);
    points.Append(m_location+m_direction);
    break;

  case ON::camera_point_light:
  case ON::world_point_light:
    points.Append(m_location);
    break;

  case ON::camera_spot_light:
  case ON::world_spot_light:
    if ( m_spot_angle > 0.0 && m_spot_angle < 90.0 )
    {
      double r = m_direction.Length()*tan(ON_PI*m_spot_angle/180.0);
      ON_Circle c(ON_Plane(m_location+m_direction,m_direction),r);
      ON_BoundingBox cbox = c.BoundingBox();
      cbox.GetCorners( points );
    }
    else
    {
      points.Append(m_location+m_direction);
    }
    points.Append(m_location);
    break;

  case ON::ambient_light:
    points.Append(m_location);
    rc = false;
    break;
  
  case ON::world_linear_light:
    points.Append(m_location);
    points.Append(m_location+m_length);
    break;

  case ON::world_rectangular_light:
    points.Append(m_location);
    points.Append(m_location+m_length);
    points.Append(m_location+m_width);
    points.Append(m_location+m_width+m_length);
    {
      // include target and direction marker to avoid display clipping
      ON_3dPoint center(m_location+(m_width+m_length)*0.5);
      points.Append(center+m_direction);
      ON_3dVector marker(m_direction); 
      marker.Unitize();
      marker *= (m_width+m_length).Length()/12.0; // from GetRectangularLightSegments
      points.Append(center+marker);
    }
    break;

  default:
    rc = false;
    break;
  }

  if ( rc && points.Count() > 0 )
  {
     rc = ON_GetPointListBoundingBox( 3, 0, points.Count(), 3, 
                                      (double*)points.Array(), 
                                      boxmin, boxmax, 
                                      bGrowBox?true:false )
        ? true 
        : false;
  }

  return rc;
}
Exemplo n.º 10
0
int Delta::execute()
{

    Options sourceOptions;
    {
        sourceOptions.add<std::string>("filename", m_sourceFile);
        sourceOptions.add<bool>("debug", isDebug());
        sourceOptions.add<boost::uint32_t>("verbose", getVerboseLevel());
    }
    Stage* source = AppSupport::makeReader(sourceOptions);
    source->initialize();
    
    boost::uint32_t totalPointCount(source->getNumPoints());
    
    PointBuffer source_data(source->getSchema(), totalPointCount);
    StageSequentialIterator* source_iter = source->createSequentialIterator(source_data);

    boost::uint32_t  numRead = source_iter->read(source_data);
    assert(numRead == source_data.getNumPoints());

    delete source_iter;
    delete source;



    Options candidateOptions;
    {
        candidateOptions.add<std::string>("filename", m_candidateFile);
        candidateOptions.add<bool>("debug", isDebug());
        candidateOptions.add<boost::uint32_t>("verbose", getVerboseLevel());
    }

    Stage* candidate = AppSupport::makeReader(candidateOptions);

    candidate->initialize();    


    IndexedPointBuffer candidate_data(candidate->getSchema(), totalPointCount);
    StageSequentialIterator* candidate_iter = candidate->createSequentialIterator(candidate_data);

    numRead = candidate_iter->read(candidate_data);
    assert(numRead == candidate_data.getNumPoints());
        
    delete candidate_iter;    


    if (source_data.getNumPoints() != candidate_data.getNumPoints())
    {
        std::cerr << "Source and candidate files do not have the same point count, testing each source point only!" << std::endl;
    }
    

    // m_summary_x(xd);
    // m_summary_y(yd);
    // m_summary_z(zd);

    if (m_outputFileName.size())
    {
        m_outputStream = FileUtils::createFile(m_outputFileName);
    }

    candidate_data.build(m_3d);
    boost::uint32_t count(std::min(source_data.getNumPoints(), candidate_data.getNumPoints()));
    


    boost::scoped_ptr<std::map<Point, Point> > points(cumulatePoints(source_data, candidate_data));
    if (m_OutputDetail)
    {
        outputDetail(source_data, candidate_data, points.get());
        return 0;
    }
    
    std::map<Point, Point>::const_iterator i;
    for(i = points->begin(); i != points->end(); ++i)
    {
        Point const& s = i->first;
        Point const& c = i->second;

        double xd = s.x - c.x;
        double yd = s.y - c.y;
        double zd = s.z - c.z;        
        m_summary_x(xd);
        m_summary_y(yd);
        m_summary_z(zd);        
    }
    
    std::string headline("------------------------------------------------------------------------------------------");
    std::cout << headline << std::endl;
    std::cout << " Delta summary for source '" << m_sourceFile << "' and candidate '" << m_candidateFile <<"'" << std::endl;
    std::cout << headline << std::endl;
    std::cout << std::endl;
    
    std::string thead("----------- --------------- --------------- --------------");
    std::cout << thead << std::endl;
    std::cout << " Dimension       X             Y                  Z    " << std::endl;
    std::cout << thead << std::endl;
    
    boost::format fmt("%.4f");
    double sminx  = (boost::accumulators::min)(m_summary_x);
    double sminy  = (boost::accumulators::min)(m_summary_y);
    double sminz  = (boost::accumulators::min)(m_summary_z);
    double smaxx  = (boost::accumulators::max)(m_summary_x);
    double smaxy  = (boost::accumulators::max)(m_summary_y);
    double smaxz  = (boost::accumulators::max)(m_summary_z);
    
    double smeanx  = (boost::accumulators::mean)(m_summary_x);
    double smeany  = (boost::accumulators::mean)(m_summary_y);
    double smeanz  = (boost::accumulators::mean)(m_summary_z);
    
    std::cout << " Min        " << fmt % sminx << "            " << fmt % sminy << "            " << fmt % sminz<<std::endl;
    std::cout << " Min        " << fmt % smaxx << "            " << fmt % smaxy << "            " << fmt % smaxz<<std::endl;
    std::cout << " Mean       " << fmt % smeanx << "            " << fmt % smeany << "            " << fmt % smeanz<<std::endl;
    std::cout << thead << std::endl;
    
    return 0;
}
Exemplo n.º 11
0
std::vector<Triple> Seek::getVel(unsigned int ticks, unsigned int delta_ticks) {
    Triple cp, tp;

    std::tie(cp, tp) = points(this->character, this->target);
    return std::vector<Triple>(1, (tp - cp).normalized() * maxSpeed);
}
Exemplo n.º 12
0
void ElementTests::setup()
{
  /**********************************

   _________________________________
   |               |               |
   |               |               |
   |               |               |
   |       1       |       3       |
   |               |               |
   |               |               |
   |               |               |
   ---------------------------------
   |       |       |               |
   |   7   |   6   |               |
   |       |       |               |
   |-------0-------|       2       |
   |       | 11| 10|               |
   |   4   |---5---|               |
   |       | 8 | 9 |               |
   ---------------------------------

   in the code:
   _sw: 0
   _nw: 1
   _se: 2
   _ne: 3
   _sw_se: 5
   _sw_ne: 6
   _sw_se_se:  9
   _sw_se_ne: 10

   *********************************/

  // first, build a simple mesh
  FieldContainer<double> quadPoints(4,2);

  quadPoints(0,0) = 0.0; // x1
  quadPoints(0,1) = 0.0; // y1
  quadPoints(1,0) = 1.0;
  quadPoints(1,1) = 0.0;
  quadPoints(2,0) = 1.0;
  quadPoints(2,1) = 1.0;
  quadPoints(3,0) = 0.0;
  quadPoints(3,1) = 1.0;

  int H1Order = 2;
  int testOrder = H1Order;
  int horizontalCells = 2;
  int verticalCells = 2;

  double eps = 1.0; // not really testing for sharp gradients right now--just want to see if things basically work
  double beta_x = 1.0;
  double beta_y = 1.0;

  BFPtr confusionBF = ConfusionBilinearForm::confusionBF(eps,beta_x,beta_y);

  _mesh = MeshFactory::buildQuadMesh(quadPoints, horizontalCells, verticalCells, confusionBF, H1Order, testOrder);

  // the right way to determine the southwest element, etc. is as follows:
  FieldContainer<double> points(4,2);
  // southwest center:
  points(0,0) = 0.25;
  points(0,1) = 0.25;
  // southeast center:
  points(1,0) = 0.75;
  points(1,1) = 0.25;
  // northwest center:
  points(2,0) = 0.25;
  points(2,1) = 0.75;
  // northeast center:
  points(3,0) = 0.75;
  points(3,1) = 0.75;
  vector<ElementPtr> elements = _mesh->elementsForPoints(points, false);

  _sw = elements[0]; // as presently implemented, cellID = 0
  _se = elements[1]; // as presently implemented, cellID = 2
  _nw = elements[2]; // as presently implemented, cellID = 1
  _ne = elements[3]; // as presently implemented, cellID = 3

  vector<GlobalIndexType> cellIDsToRefine;
  cellIDsToRefine.push_back(_sw->cellID());

  _mesh->hRefine(cellIDsToRefine,RefinementPattern::regularRefinementPatternQuad());

  // get the new elements; these are all within the original SW quadrant
  // southwest center:
  points(0,0) = 0.125;
  points(0,1) = 0.125;
  // southeast center:
  points(1,0) = 0.375;
  points(1,1) = 0.125;
  // northwest center:
  points(2,0) = 0.125;
  points(2,1) = 0.375;
  // northeast center:
  points(3,0) = 0.375;
  points(3,1) = 0.375;

  elements = _mesh->elementsForPoints(points, false);
  _sw_se = elements[1]; // as presently implemented, cellID = 5
  _sw_ne = elements[3]; // as presently implemented, cellID = 6

  cellIDsToRefine.clear();
  cellIDsToRefine.push_back(_sw_se->cellID());

  _mesh->hRefine(cellIDsToRefine,RefinementPattern::regularRefinementPatternQuad());

  // get the new elements; these are all within the SE of the original SW quadrant
  // southwest center:
  points(0,0) = 0.31125;
  points(0,1) = 0.31125;
  // southeast center:
  points(1,0) = 0.4375;
  points(1,1) = 0.31125;
  // northwest center:
  points(2,0) = 0.31125;
  points(2,1) = 0.4375;
  // northeast center:
  points(3,0) = 0.4375;
  points(3,1) = 0.4375;

  elements = _mesh->elementsForPoints(points, false);
  _sw_se_se = elements[1]; // as presently implemented, cellID =  9
  _sw_se_ne = elements[3]; // as presently implemented, cellID = 10

  // setup test points:
  static const int NUM_POINTS_1D = 3;
  double x[NUM_POINTS_1D] = {-0.5,0.25,0.75};

  _testPoints1D = FieldContainer<double>(NUM_POINTS_1D,1);
  for (int i=0; i<NUM_POINTS_1D; i++)
  {
    _testPoints1D(i, 0) = x[i];
  }

}
void QgsMapToolAddFeature::canvasReleaseEvent( QMouseEvent * e )
{
  QgsDebugMsg( "entered." );

  QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( mCanvas->currentLayer() );

  if ( !vlayer )
  {
    QMessageBox::information( 0, tr( "Not a vector layer" ),
                              tr( "The current layer is not a vector layer" ) );
    return;
  }

  QGis::WkbType layerWKBType = vlayer->wkbType();

  QgsVectorDataProvider* provider = vlayer->dataProvider();

  if ( !( provider->capabilities() & QgsVectorDataProvider::AddFeatures ) )
  {
    QMessageBox::information( 0, tr( "Layer cannot be added to" ),
                              tr( "The data provider for this layer does not support the addition of features." ) );
    return;
  }

  if ( !vlayer->isEditable() )
  {
    QMessageBox::information( 0, tr( "Layer not editable" ),
                              tr( "Cannot edit the vector layer. Use 'Toggle Editing' to make it editable." )
                            );
    return;
  }

  // POINT CAPTURING
  if ( mode() == CapturePoint )
  {
    //check we only use this tool for point/multipoint layers
    if ( vlayer->geometryType() != QGis::Point )
    {
      QMessageBox::information( 0, tr( "Wrong editing tool" ),
                                tr( "Cannot apply the 'capture point' tool on this vector layer" ) );
      return;
    }


    QgsPoint idPoint; //point in map coordinates
    QList<QgsSnappingResult> snapResults;
    QgsPoint savePoint; //point in layer coordinates

    if ( mSnapper.snapToBackgroundLayers( e->pos(), snapResults ) == 0 )
    {
      idPoint = snapPointFromResults( snapResults, e->pos() );
      try
      {
        savePoint = toLayerCoordinates( vlayer, idPoint );
        QgsDebugMsg( "savePoint = " + savePoint.toString() );
      }
      catch ( QgsCsException &cse )
      {
        Q_UNUSED( cse );
        QMessageBox::information( 0, tr( "Coordinate transform error" ),
                                  tr( "Cannot transform the point to the layers coordinate system" ) );
        return;
      }
    }

    //only do the rest for provider with feature addition support
    //note that for the grass provider, this will return false since
    //grass provider has its own mechanism of feature addition
    if ( provider->capabilities() & QgsVectorDataProvider::AddFeatures )
    {
      QgsFeature* f = new QgsFeature( 0, "WKBPoint" );

      QgsGeometry *g = 0;
      if ( layerWKBType == QGis::WKBPoint || layerWKBType == QGis::WKBPoint25D )
      {
        g = QgsGeometry::fromPoint( savePoint );
      }
      else if ( layerWKBType == QGis::WKBMultiPoint || layerWKBType == QGis::WKBMultiPoint25D )
      {
        g = QgsGeometry::fromMultiPoint( QgsMultiPoint() << savePoint );
      }

      f->setGeometry( g );

      vlayer->beginEditCommand( tr( "Feature added" ) );

      if ( addFeature( vlayer, f ) )
      {
        vlayer->endEditCommand();
      }
      else
      {
        delete f;
        vlayer->destroyEditCommand();
      }

      mCanvas->refresh();
    }
  }
  else if ( mode() == CaptureLine || mode() == CapturePolygon )
  {
    //check we only use the line tool for line/multiline layers
    if ( mode() == CaptureLine && vlayer->geometryType() != QGis::Line )
    {
      QMessageBox::information( 0, tr( "Wrong editing tool" ),
                                tr( "Cannot apply the 'capture line' tool on this vector layer" ) );
      return;
    }

    //check we only use the polygon tool for polygon/multipolygon layers
    if ( mode() == CapturePolygon && vlayer->geometryType() != QGis::Polygon )
    {
      QMessageBox::information( 0, tr( "Wrong editing tool" ),
                                tr( "Cannot apply the 'capture polygon' tool on this vector layer" ) );
      return;
    }

    //add point to list and to rubber band
    int error = addVertex( e->pos() );
    if ( error == 1 )
    {
      //current layer is not a vector layer
      return;
    }
    else if ( error == 2 )
    {
      //problem with coordinate transformation
      QMessageBox::information( 0, tr( "Coordinate transform error" ),
                                tr( "Cannot transform the point to the layers coordinate system" ) );
      return;
    }

    if ( e->button() == Qt::LeftButton )
    {
      startCapturing();
    }
    else if ( e->button() == Qt::RightButton )
    {
      // End of string

      //lines: bail out if there are not at least two vertices
      if ( mode() == CaptureLine && size() < 2 )
      {
        stopCapturing();
        return;
      }

      //polygons: bail out if there are not at least two vertices
      if ( mode() == CapturePolygon && size() < 3 )
      {
        stopCapturing();
        return;
      }

      //create QgsFeature with wkb representation
      QgsFeature* f = new QgsFeature( 0, "WKBLineString" );

      QgsGeometry *g;

      if ( mode() == CaptureLine )
      {
        if ( layerWKBType == QGis::WKBLineString || layerWKBType == QGis::WKBLineString25D )
        {
          g = QgsGeometry::fromPolyline( points().toVector() );
        }
        else if ( layerWKBType == QGis::WKBMultiLineString || layerWKBType == QGis::WKBMultiLineString25D )
        {
          g = QgsGeometry::fromMultiPolyline( QgsMultiPolyline() << points().toVector() );
        }
        else
        {
          QMessageBox::critical( 0, tr( "Error" ), tr( "Cannot add feature. Unknown WKB type" ) );
          stopCapturing();
          return; //unknown wkbtype
        }

        f->setGeometry( g );
      }
      else // polygon
      {
        QgsGeometry *g;
        if ( layerWKBType == QGis::WKBPolygon ||  layerWKBType == QGis::WKBPolygon25D )
        {
          g = QgsGeometry::fromPolygon( QgsPolygon() << points().toVector() );
        }
        else if ( layerWKBType == QGis::WKBMultiPolygon ||  layerWKBType == QGis::WKBMultiPolygon25D )
        {
          g = QgsGeometry::fromMultiPolygon( QgsMultiPolygon() << ( QgsPolygon() << points().toVector() ) );
        }
        else
        {
          QMessageBox::critical( 0, tr( "Error" ), tr( "Cannot add feature. Unknown WKB type" ) );
          stopCapturing();
          return; //unknown wkbtype
        }

        f->setGeometry( g );

        int avoidIntersectionsReturn = f->geometry()->avoidIntersections();
        if ( avoidIntersectionsReturn == 1 )
        {
          //not a polygon type. Impossible to get there
        }
        else if ( avoidIntersectionsReturn == 2 )
        {
          //bail out...
          QMessageBox::critical( 0, tr( "Error" ), tr( "The feature could not be added because removing the polygon intersections would change the geometry type" ) );
          delete f;
          stopCapturing();
          return;
        }
        else if ( avoidIntersectionsReturn == 3 )
        {
          QMessageBox::critical( 0, tr( "Error" ), tr( "An error was reported during intersection removal" ) );
        }
      }

      vlayer->beginEditCommand( tr( "Feature added" ) );

      if ( addFeature( vlayer, f ) )
      {
        //add points to other features to keep topology up-to-date
        int topologicalEditing = QgsProject::instance()->readNumEntry( "Digitizing", "/TopologicalEditing", 0 );
        if ( topologicalEditing )
        {
          vlayer->addTopologicalPoints( f->geometry() );
        }

        vlayer->endEditCommand();
      }
      else
      {
        delete f;
        vlayer->destroyEditCommand();
      }

      stopCapturing();
    }
  }
}
Exemplo n.º 14
0
int points(int start, int end, long long x, long long y) {
    int c = (start + end)/2;
    if (start == end) return start;
    if (r[c] < (x*x)+(y*y)) points(c+1, end, x, y);
    else points(start, c, x, y);
}
Exemplo n.º 15
0
    // transfer to normal lists
    storedPoints().transfer(dynPoints);

    pointId.shrink();
    dynEdges.shrink();

    // Build inverse mapping (NASTRAN pointId -> index)
    Map<label> mapPointId(2*pointId.size());
    forAll(pointId, i)
    {
        mapPointId.insert(pointId[i], i);
    }

    // note which points were really used and which can be culled
    PackedBoolList usedPoints(points().size());


    // Pass1: relabel edges
    // ~~~~~~~~~~~~~~~~~~~~
    forAll(dynEdges, i)
    {
        edge& e = dynEdges[i];
        e[0] = mapPointId[e[0]];
        e[1] = mapPointId[e[1]];

        usedPoints.set(e[0]);
        usedPoints.set(e[1]);
    }
    pointId.clearStorage();
    mapPointId.clear();
Exemplo n.º 16
0
void Foam::processorPolyPatch::calcGeometry(PstreamBuffers& pBufs)
{
    if (Pstream::parRun())
    {
        {
            UIPstream fromNeighbProc(neighbProcNo(), pBufs);

            fromNeighbProc
                >> neighbFaceCentres_
                >> neighbFaceAreas_
                >> neighbFaceCellCentres_;
        }

        // My normals
        vectorField faceNormals(size());

        // Neighbour normals
        vectorField nbrFaceNormals(neighbFaceAreas_.size());

        // Face match tolerances
        scalarField tols = calcFaceTol(*this, points(), faceCentres());

        // Calculate normals from areas and check
        forAll(faceNormals, facei)
        {
            scalar magSf = mag(faceAreas()[facei]);
            scalar nbrMagSf = mag(neighbFaceAreas_[facei]);
            scalar avSf = (magSf + nbrMagSf)/2.0;

            // For small face area calculation the results of the area
            // calculation have been found to only be accurate to ~1e-20
            if (magSf < SMALL || nbrMagSf < SMALL)
            {
                // Undetermined normal. Use dummy normal to force separation
                // check.
                faceNormals[facei] = point(1, 0, 0);
                nbrFaceNormals[facei] = -faceNormals[facei];
                tols[facei] = GREAT;
            }
            else if (mag(magSf - nbrMagSf) > matchTolerance()*sqr(tols[facei]))
            {
                fileName nm
                (
                    boundaryMesh().mesh().time().path()
                   /name()+"_faces.obj"
                );

                Pout<< "processorPolyPatch::calcGeometry : Writing my "
                    << size()
                    << " faces to OBJ file " << nm << endl;

                writeOBJ(nm, *this, points());

                OFstream ccStr
                (
                    boundaryMesh().mesh().time().path()
                    /name() + "_faceCentresConnections.obj"
                );

                Pout<< "processorPolyPatch::calcGeometry :"
                    << " Dumping cell centre lines between"
                    << " corresponding face centres to OBJ file" << ccStr.name()
                    << endl;

                label vertI = 0;

                forAll(faceCentres(), faceI)
                {
                    const point& c0 = neighbFaceCentres_[faceI];
                    const point& c1 = faceCentres()[faceI];

                    writeOBJ(ccStr, c0, c1, vertI);
                }

                FatalErrorInFunction
                    << "face " << facei << " area does not match neighbour by "
                    << 100*mag(magSf - nbrMagSf)/avSf
                    << "% -- possible face ordering problem." << endl
                    << "patch:" << name()
                    << " my area:" << magSf
                    << " neighbour area:" << nbrMagSf
                    << " matching tolerance:"
                    << matchTolerance()*sqr(tols[facei])
                    << endl
                    << "Mesh face:" << start()+facei
                    << " vertices:"
                    << UIndirectList<point>(points(), operator[](facei))()
                    << endl
                    << "If you are certain your matching is correct"
                    << " you can increase the 'matchTolerance' setting"
                    << " in the patch dictionary in the boundary file."
                    << endl
                    << "Rerun with processor debug flag set for"
                    << " more information." << exit(FatalError);
            }
            else
            {
Exemplo n.º 17
0
void ExternalPortModel::setPort(const char* szPort)
{
    if(!szPort)
        return;
   
    strPort = szPort;

    PangoLayout *layout = gtk_widget_create_pango_layout((GtkWidget*)parentWindow->gobj(), 
                            szPort);
    int text_w, text_h;
    PangoFontDescription *fontdesc = pango_font_description_from_string(FONT_DESC);
    pango_layout_set_font_description (layout, fontdesc);
    pango_layout_get_pixel_size (layout, &text_w, &text_h);

    width = text_w + H_MARGINE*2 + PORT_DEPTH;
    height = text_h + V_MARGINE*2;
    
    if(type == INPUTD)
    {
        Goocanvas::Points points(5);
        points.set_coordinate(0, 0, 0);
        points.set_coordinate(1, width, 0);
        points.set_coordinate(2, width, height);
        points.set_coordinate(3, 0, height);
        points.set_coordinate(4, PORT_DEPTH, height/2.0);
        poly->property_points().set_value(points);
        shadow->property_points().set_value(points);
    }
    else
    {
        Goocanvas::Points points(5);
        points.set_coordinate(0, 0, 0);
        points.set_coordinate(1, width-PORT_DEPTH, 0);
        points.set_coordinate(2, width, height/2.0);
        points.set_coordinate(3, width-PORT_DEPTH, height);
        points.set_coordinate(4, 0, height);
        poly->property_points().set_value(points);
        shadow->property_points().set_value(points);
    }

    text->property_text() = szPort;
    text->property_x().set_value(PORT_DEPTH+H_MARGINE/2.0);
    text->property_y().set_value(height/2.0 - text_h/2.0);
    updateArrowCoordination();
    
    // updating all connections from/to this port 
    Application* application = parentWindow->manager.getKnowledgeBase()->getApplication();
    std::vector<ArrowModel*>::iterator itr;   
    if(type == OUTPUTD)
    {
        for(itr = sourceArrows.begin(); itr!= sourceArrows.end(); itr++)
        {
            Connection* pConnection = (*itr)->getConnection();
            Connection con = *pConnection;
            con.setFrom(szPort);
            parentWindow->manager.getKnowledgeBase()->updateConnectionOfApplication(application, *pConnection, con);
            pConnection->setFrom(szPort);
        }            
    }
    else
    {
        for(itr = destinationArrows.begin(); itr!= destinationArrows.end(); itr++)
        {
            Connection* pConnection = (*itr)->getConnection();
            Connection con = *pConnection;
            con.setTo(szPort);
            parentWindow->manager.getKnowledgeBase()->updateConnectionOfApplication(application, *pConnection, con);
            pConnection->setTo(szPort);
        }            
    }
}
Exemplo n.º 18
0
 bool Selector::ProcessStaticGeometry(Node *node, Virtual::StaticGeometry *geom)
 {        
     if (geom)
     {
         if (geom->GetCpuCache().IsOnCpu())
         {
             bool has_bsphere = false;
             bool has_bbox = false;
             Math::Line3D line = m_local_transform.top().Inversed() * m_view_ray;
             if (m_check_bounding_sphere)
             {
                 const Math::BoundingSphere& sphere = geom->GetBoundingSphere();
                 Math::vec3 p1, p2;
                 Math::Relation r = Math::CrossLineSphere(line, sphere, p1, p2);
                 if (r == Math::Relation::INTERSECT_2)
                 {
                     std::vector<Math::vec3> p(2);
                     p[0]= m_local_transform.top() * p1;
                     p[1] = m_local_transform.top() * p2;
                     Selection s;
                     s.SetPoints(p);
                     s.SetType(SelectionType::BoundingSphere);
                     s.SetObject(node);
                     m_selections.push_back(s);
                     has_bsphere = true;
                 }
                 if (r == Math::Relation::INTERSECT_1)
                 {
                     std::vector<Math::vec3> p(1);
                     p[0]= m_local_transform.top() * p1;
                     Selection s;
                     s.SetPoints(p);
                     s.SetType(SelectionType::BoundingSphere);
                     s.SetObject(node);
                     m_selections.push_back(s);
                     has_bsphere = true;
                 }
             }
             if (m_check_bounding_box)
             {
                 if (has_bsphere || !m_check_bounding_sphere)
                 {
                     const Math::BoundingBox& bbox = geom->GetBoundingBox();
                     Math::vec3 p;
                     Math::Relation r = Math::CrossLineBoundingBox(line, bbox, p);
                     if (r == Math::Relation::INTERSECT)
                     {
                         std::vector<Math::vec3> points(1);
                         points[0] = m_local_transform.top() * p;
                         Selection s;
                         s.SetPoints(points);
                         s.SetType(SelectionType::BoundingBox);
                         s.SetObject(node);
                         m_selections.push_back(s);
                         has_bbox = true;
                     }
                 }
             }
             if (m_check_geometry)
             {
                 if (has_bbox || !m_check_bounding_box)
                 {
                     std::vector<Math::vec3> points;
                     std::vector<size_t> faces;
                     Math::Relation r = Math::CrossLineTriangles(line, geom->GetCpuCache().GetVertices(), geom->GetCpuCache().GetFaces(), points, faces);
                     if (r == Math::Relation::INTERSECT)
                     {
                         //  return points to the worlds coordinate system
                         for (auto& p : points)
                         {
                             p = m_local_transform.top() * p;
                         }
                         Selection selection;
                         selection.SetPoints(points);
                         selection.SetFaces(faces);
                         selection.SetType(SelectionType::Geometry);
                         selection.SetObject(node);
                         m_selections.push_back(selection);
                     }
                 }
             }
         }
     }
     return ProcessChildren(node);
 }
Exemplo n.º 19
0
bool Iterative_Control::iterative_control_opt(vector<Thread*>& trajectory, vector<VectorXd>& controls, vector<vector<Thread*> >& sqp_debug_data, int num_opts, bool return_best_opt, double threshold) 
{
  if (trajectory.size() != _num_threads && trajectory.front()->num_pieces() != _num_vertices)
    return false;

  //make a copy of the start and goal threads
  _lastopt_startThread = new Thread(*trajectory.front());
  _lastopt_goalThread = new Thread(*trajectory.back());

  //vector to contain the new states
  VectorXd new_states((_num_threads-2)*_size_each_state + (_num_threads-1)*_size_each_control);

  char filename_goalvec[256];
  sprintf(filename_goalvec, "%s/%s_%s", SQP_BASE_FOLDER, _namestring, FILENAME_GOALVEC);

  char filename_alltrans[256];
  sprintf(filename_alltrans, "%s/%s_%s", SQP_BASE_FOLDER, _namestring, FILENAME_ALLTRANS);

  sqp_debug_data.resize(0); 

  vector<Thread*> best_trajectory;
  vector<VectorXd> best_controls; 
  double best_score = DBL_MAX;

  for (int opt_iter=0; opt_iter < num_opts; opt_iter++)
  {
    /* Memory leak, fix later. Needed to get jacobian computation done in parallel */ 
    vector<Thread*> trajectory_local;
    trajectory_local.resize(trajectory.size());
    #pragma omp parallel for
    for (int i = 0; i < trajectory.size(); i++) { 
      trajectory_local[i] = new Thread(*trajectory[i]);
    }
    trajectory = trajectory_local; 

    add_transitions_alltrans(trajectory);
    SparseMatrix<double> all_trans_sparse(_all_trans);
    Matrix_To_File(all_trans_sparse, filename_alltrans);
    //write all states out
    VectorXd goal_vector(_size_each_state*_num_threads);
    VectorXd state_for_file(_size_each_state);
    for (int i=0; i < trajectory.size(); i++)
    {
      thread_to_state(trajectory[i], state_for_file);
      goal_vector.segment(i*_size_each_state, _size_each_state) = state_for_file;
    }
    Vector_To_File(goal_vector, filename_goalvec);
    //LU<MatrixXd> lu_factorization((MatrixXd(all_trans_sparse.transpose())*all_trans_sparse));
    //VectorXd b = DynamicSparseMatrix<double>(all_trans_sparse.transpose())*goal_vector;
    //new_states = b;
    //lu_factorization.solve(b, &new_states);
    //lu_factorization.solveInPlace(new_states);
    

    //VectorXd c(goal_vector.rows());
    //(_all_trans*_all_trans.transpose()).svd().solve(goal_vector, &c);
 
    //new_states = _all_trans.transpose()*c;

    //std::cout << "error: " << (_all_trans*new_states - goal_vector).norm() << std::endl;

    vector<Vector3d> points(_num_vertices);
    vector<double> angles(_num_vertices);

    char filename_statevec_thisiter[256];
    sprintf(filename_statevec_thisiter, "%s/%s_%s%d.txt", SQP_BASE_FOLDER, _namestring, FILENAME_STATEVEC_BASE, opt_iter);

    char matlab_command[1024];
    sprintf(matlab_command, "%s -nodisplay -nodesktop -nojvm -r \"solve_sparse(%d, %d, \'%s\', %d, %d, \'%s\', \'%s\', %d, %d, %d)\"", MATLAB_INSTALL, _all_trans.rows(), _all_trans.cols(), filename_alltrans, goal_vector.rows(), goal_vector.cols(), filename_goalvec, filename_statevec_thisiter, _num_threads, _size_each_state, _size_each_control);
    std::cout << "command: " << matlab_command << std::endl;

    int return_value = system(matlab_command);
    File_To_Vector(filename_statevec_thisiter, new_states);
    

    cout << "NOT Minimizing Threads returned from MATLAB" << endl; 
    boost::progress_display progress(trajectory.size()-2);
    vector<Thread*> sqp_debug_data_iter;
    sqp_debug_data_iter.resize(trajectory.size());
    sqp_debug_data_iter[0] = new Thread(*trajectory[0]);
    sqp_debug_data_iter[trajectory.size()-1] = new Thread(*trajectory[trajectory.size()-1]);
    #pragma omp parallel for num_threads(NUM_CPU_THREADS)
    for (int i=1; i < trajectory.size()-1; i++)
    {
      VectorXd to_copy = new_states.segment(_size_each_state*(i-1), _size_each_state);
      trajectory[i]->copy_data_from_vector(to_copy);
      sqp_debug_data_iter[i] = new Thread(*trajectory[i]); 
      trajectory[i]->unviolate_total_length_constraint();
      trajectory[i]->project_length_constraint();
      //trajectory[i]->minimize_energy(150000000);
      ++progress;
    }

    sqp_debug_data.push_back(sqp_debug_data_iter);

    //copy out control
    controls.resize(_num_threads-1);
    vector<vector<VectorXd> > control_vector;
    for (int i=0; i < _num_threads-1; i++)
    {
      controls[i] = new_states.segment(_size_each_state*(_num_threads-2) + i*_size_each_control, _size_each_control);
    }

    vector<Thread*> trajectory_copy;  
    trajectory_copy.push_back(new Thread(*trajectory[0]));
    vector<Thread*> OLTrajectory;
    openLoopController(trajectory_copy, controls, OLTrajectory);
    double sqp_olc_score = util_planner.l2PointsDifference(OLTrajectory.back(), trajectory.back());
    cout << "SQP OLC score = " << sqp_olc_score << endl;
    OLTrajectory[OLTrajectory.size()-1] = trajectory[trajectory.size()-1];
    trajectory = OLTrajectory;
    //if (return_best_opt && sqp_olc_score < threshold) return true; 
    if (return_best_opt && sqp_olc_score < best_score) {
      best_score = sqp_olc_score;
      // cleanup
      if (best_trajectory.size() > 0) { 
        for (int i = 0; i < best_trajectory.size(); i++) {
          delete best_trajectory[i];
        }
      }
      best_trajectory.resize(trajectory.size());
      for (int i = 0; i < trajectory.size(); i++) { 
          best_trajectory[i] = new Thread(*trajectory[i]);
      }
      best_controls.resize(controls.size());
      for (int i = 0; i < controls.size(); i++) {
        best_controls[i] = controls[i];
      }
    }
  }

  if (return_best_opt) { 
    trajectory = best_trajectory;
    controls = best_controls;
    //for (int i = 10; i < controls.size(); i++) {
    //  controls[i].setZero();
    //}
  }

  return true;
}
Exemplo n.º 20
0
void mexFunction(int nlhs, mxArray  *plhs[], int nrhs, const mxArray  *prhs[])
{	
	int ref_or_direct = 1;			// ref_or_direct = 1 means interpret second input argument as reference indices
									// = 0 means interpret second input argument as reference vectors
	long past = 0;
	
	/* check input args */
	if (nrhs < 3)
	{
		mexErrMsgTxt("Fast nearest neighbour searcher : Data set of points (row vectors), reference indices or reference points \nand number of nearest neighbours must be given");
		return;
	}
	
	/* handle matrix I/O */
	
	const long N 		= mxGetM(prhs[0]);	
	const long dim  	= mxGetN(prhs[0]);
	const double* p 	= (double *)mxGetPr(prhs[0]);
	
	double* ref 	= (double *)mxGetPr(prhs[1]);
	long R; 										// number of query (reference) points
	
	const long NNR 	= (long) *((double *)mxGetPr(prhs[2]));
	
	if (N < 1) {
		mexErrMsgTxt("Data set must consist of at least two points (row vectors)");
		return;
	}		
	if (dim < 1) {
		mexErrMsgTxt("Data points must be at least of dimension one");
		return;
	}	
	if (NNR<1) {
		mexErrMsgTxt("At least one nearest neighbour must be requested");
		return;
	}	
	if ((mxGetN(prhs[1]) == 0) || (mxGetN(prhs[1]) == 0)) {
		mexErrMsgTxt("Wrong reference indices or reference points given");
		return;
	}	
	
	if (mxGetN(prhs[1]) == 1) {
		R = mxGetM(prhs[1]);
		ref_or_direct = 1;	
	} 
	else if ((mxGetM(prhs[1]) == 1) && (mxGetN(prhs[1]) != dim)) {
		R = mxGetN(prhs[1]);
		ref_or_direct = 1;	
	}
	else if (mxGetN(prhs[1]) == dim) {
		R = mxGetM(prhs[1]);
		ref_or_direct = 0;	
	} else  {
		mexErrMsgTxt("Cannot determine if second argument are reference indices or reference points");
		return;
	}	

	if (R < 1) {
		mexErrMsgTxt("At least one reference index or point must be given");
		return;
	}	

	if (ref_or_direct) {		// interpret second argument as list of indices into the data set given as first argument 
		if (nrhs < 4)
		{
#ifdef BRUTE		
			mexErrMsgTxt("Brute nearest neighbour searcher : Data set of points (row vectors), reference indices,\nnumber of nearest neighbours and past must be given");
#else
			mexErrMsgTxt("Fast nearest neighbour searcher : Data set of points (row vectors), reference indices,\nnumber of nearest neighbours and past must be given");
#endif
			return;
		}
		past = (long) *((double *)mxGetPr(prhs[3]));
		for (long i=0; i < R; i++) {
			if ((ref[i] < 1) || (ref[i]>N)) {
				mexErrMsgTxt("Reference indices out of range");
				return;
			}	
		}
		if ((N - (2*past)-1) < NNR)
		{
			mexErrMsgTxt("Fast nearest neighbour searcher : To many neighbors for each query point are requested");
			return;
		}		
		
	} 
	
#ifdef BRUTE
	point_set<squared_euclidian_distance> points(N,dim, p);		
	Brute< point_set<squared_euclidian_distance> > searcher(points);	
#else
	point_set<euclidian_distance> points(N,dim, p);	
	ATRIA< point_set<euclidian_distance> > searcher(points);	
#endif	
	
	if (searcher.geterr()) {
		mexErrMsgTxt("Error preparing searcher");
		return;
	}	 

	plhs[0] = mxCreateDoubleMatrix(R, NNR, mxREAL);
	double* nn = (double *) mxGetPr(plhs[0]);
	
	double* dists;
	
	if (nlhs > 1) {
		plhs[1] = mxCreateDoubleMatrix(R, NNR, mxREAL);
		dists = (double *) mxGetPr(plhs[1]);
	} else
		dists = new double[R*NNR];


	if (ref_or_direct) {
		for (long n=0; n < R; n++) { /* iterate over all reference points, given as index into the input point set */ 
			vector<neighbor> v;
			const long actual = (long) ref[n]-1;		/* Matlab to C means indices change from 1 to 0, 2 to 1, 3 to 2 ...*/
			
			searcher.search_k_neighbors(v, NNR, points.point_begin(actual), actual-past, actual+past);
			
			for (long k = 0; k < v.size(); k++) { 	// v is the sorted vector of neighbors
				nn[n+k*R] = v[k].index() + 1;	// convert indices back to Matlab (1..N) style 
#ifdef BRUTE
				dists[n+k*R] = sqrt(v[k].dist());
#else			
				dists[n+k*R] = v[k].dist();	
#endif	
			}	
		}
	} else {
		point_set<euclidian_distance> query_points(R, dim, ref);
		for (long n=0; n < R; n++) { 	/* iterate over all reference points, given explicitly */ 
			vector<neighbor> v;
			
			searcher.search_k_neighbors(v, NNR, query_points.point_begin(n), -1, -1);
			
			for (long k = 0; k < v.size(); k++) { 	// v is the sorted vector of neighbors
				nn[n+k*R] = v[k].index() + 1;	// convert indices back to Matlab (1..N) style 
#ifdef BRUTE
				dists[n+k*R] = sqrt(v[k].dist());
#else			
				dists[n+k*R] = v[k].dist();	
#endif				
			}	
		}
	}
		
	if (nlhs > 2) {
		plhs[2] = mxCreateDoubleMatrix(1, 1, mxREAL);
		*((double *) mxGetPr(plhs[2])) = searcher.search_efficiency();
	}
	
	if (!(nlhs > 1)) delete[] dists;
}	
Exemplo n.º 21
0
//-*****************************************************************************
IObjectDrw::IObjectDrw( IObject &iObj, bool iResetIfNoChildren )
  : m_object( iObj )
  , m_minTime( ( chrono_t )FLT_MAX )
  , m_maxTime( ( chrono_t )-FLT_MAX )
{
    // If not valid, just bail.
    if ( !m_object ) { return; }

    // IObject has no explicit time sampling, but its children may.
    size_t numChildren = m_object.getNumChildren();
    for ( size_t i = 0; i < numChildren; ++i )
    {
        const ObjectHeader &ohead = m_object.getChildHeader( i );

        // Decide what to make.
        DrawablePtr dptr;
        if ( IPolyMesh::matches( ohead ) )
        {
            IPolyMesh pmesh( m_object, ohead.getName() );
            if ( pmesh )
            {
                dptr.reset( new IPolyMeshDrw( pmesh ) );
            }
        }
        else if ( IPoints::matches( ohead ) )
        {
            IPoints points( m_object, ohead.getName() );
            if ( points )
            {
                dptr.reset( new IPointsDrw( points ) );
            }
        }
        else if ( ICurves::matches( ohead ) )
        {
            ICurves curves( m_object, ohead.getName() );
            if ( curves )
            {
                dptr.reset( new ICurvesDrw( curves ) );
            }
        }
        else if ( INuPatch::matches( ohead ) )
        {
            INuPatch nuPatch( m_object, ohead.getName() );
            if ( nuPatch )
            {
                dptr.reset( new INuPatchDrw( nuPatch ) );
            }
        }
        else if ( IXform::matches( ohead ) )
        {
            IXform xform( m_object, ohead.getName() );
            if ( xform )
            {
                dptr.reset( new IXformDrw( xform ) );
            }
        }
        else if ( ISubD::matches( ohead ) )
        {
            ISubD subd( m_object, ohead.getName() );
            if ( subd )
            {
                dptr.reset( new ISubDDrw( subd ) );
            }
        }
        else
        {
            IObject object( m_object, ohead.getName() );
            if ( object )
            {
                dptr.reset( new IObjectDrw( object, true ) );
            }
        }

        if ( dptr && dptr->valid() )
        {
            m_children.push_back( dptr );
            m_minTime = std::min( m_minTime, dptr->getMinTime() );
            m_maxTime = std::max( m_maxTime, dptr->getMaxTime() );
        }
    }

    // Make the bounds empty to start
    m_bounds.makeEmpty();

    // If we have no children, just leave.
    if ( m_children.size() == 0 && iResetIfNoChildren )
    {
        m_object.reset();
    }
}
Exemplo n.º 22
0
void QgsMapToolFillRing::canvasReleaseEvent( QMouseEvent * e )
{
  //check if we operate on a vector layer
  QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( mCanvas->currentLayer() );

  if ( !vlayer )
  {
    notifyNotVectorLayer();
    return;
  }

  if ( !vlayer->isEditable() )
  {
    notifyNotEditableLayer();
    return;
  }

  //add point to list and to rubber band
  if ( e->button() == Qt::LeftButton )
  {
    int error = addVertex( e->pos() );
    if ( error == 1 )
    {
      //current layer is not a vector layer
      return;
    }
    else if ( error == 2 )
    {
      //problem with coordinate transformation
      QMessageBox::information( 0, tr( "Coordinate transform error" ),
                                tr( "Cannot transform the point to the layers coordinate system" ) );
      return;
    }

    startCapturing();
  }
  else if ( e->button() == Qt::RightButton )
  {
    deleteTempRubberBand();

    closePolygon();

    vlayer->beginEditCommand( tr( "Ring added and filled" ) );
    int addRingReturnCode = vlayer->addRing( points() );
    if ( addRingReturnCode != 0 )
    {
      QString errorMessage;
      //todo: open message box to communicate errors
      if ( addRingReturnCode == 1 )
      {
        errorMessage = tr( "A problem with geometry type occured" );
      }
      else if ( addRingReturnCode == 2 )
      {
        errorMessage = tr( "The inserted Ring is not closed" );
      }
      else if ( addRingReturnCode == 3 )
      {
        errorMessage = tr( "The inserted Ring is not a valid geometry" );
      }
      else if ( addRingReturnCode == 4 )
      {
        errorMessage = tr( "The inserted Ring crosses existing rings" );
      }
      else if ( addRingReturnCode == 5 )
      {
        errorMessage = tr( "The inserted Ring is not contained in a feature" );
      }
      else
      {
        errorMessage = tr( "An unknown error occured" );
      }
      QMessageBox::critical( 0, tr( "Error, could not add ring" ), errorMessage );
      vlayer->destroyEditCommand();
    }
    else
    {
      // find parent feature and get it attributes
      double xMin, xMax, yMin, yMax;
      QgsRectangle bBox;

      xMin = std::numeric_limits<double>::max();
      xMax = -std::numeric_limits<double>::max();
      yMin = std::numeric_limits<double>::max();
      yMax = -std::numeric_limits<double>::max();

      for ( QList<QgsPoint>::const_iterator it = points().constBegin(); it != points().constEnd(); ++it )
      {
        if ( it->x() < xMin )
        {
          xMin = it->x();
        }
        if ( it->x() > xMax )
        {
          xMax = it->x();
        }
        if ( it->y() < yMin )
        {
          yMin = it->y();
        }
        if ( it->y() > yMax )
        {
          yMax = it->y();
        }
      }
      bBox.setXMinimum( xMin );
      bBox.setYMinimum( yMin );
      bBox.setXMaximum( xMax );
      bBox.setYMaximum( yMax );

      QgsFeatureIterator fit = vlayer->getFeatures( QgsFeatureRequest().setFilterRect( bBox ).setFlags( QgsFeatureRequest::ExactIntersect ) );

      QgsFeature f;
      bool res = false;
      while ( fit.nextFeature( f ) )
      {
        //create QgsFeature with wkb representation
        QgsFeature* ft = new QgsFeature( vlayer->pendingFields(),  0 );

        QgsGeometry *g;
        g = QgsGeometry::fromPolygon( QgsPolygon() << points().toVector() );
        ft->setGeometry( g );
        ft->setAttributes( f.attributes() );

        if ( QgsApplication::keyboardModifiers() == Qt::ControlModifier )
        {
          res = vlayer->addFeature( *ft );
        }
        else
        {
          QgsAttributeDialog *dialog = new QgsAttributeDialog( vlayer, ft, false, NULL, true );
          dialog->setIsAddDialog( true );
          res = dialog->exec(); // will also add the feature
        }

        if ( res )
        {
          vlayer->endEditCommand();
        }
        else
        {
          delete ft;
          vlayer->destroyEditCommand();
        }
        res = false;
      }
    }
    stopCapturing();
  }
}
int main(int argc, char **argv)
{
    ROS_ASSERT_MSG(argc>1,"Parameter required: action_server_name");
    ROS_INFO_STREAM("A client using the " << argv[1] << " action server");
    ros::Duration long_timeout (10.0);

    ros::init(argc, argv, "follow_joint_trajectory_client");
//    Client client("follow_joint_trajectory", true); // true -> don't need to call ros::spin()
    Client client(argv[1], true); // true -> don't need to call ros::spin()
    ROS_INFO("Waiting fot connecting with the server...");
    ROS_ASSERT_MSG(client.waitForServer(long_timeout),"Timeout. Server not available.");
    ROS_INFO("CONNECTED");


    unsigned int n_joints = 7;
    std::vector<std::string> joint_manes(n_joints);
    joint_manes[0]="left_s0";
    joint_manes[1]="left_s1";
    joint_manes[2]="left_e0";
    joint_manes[3]="left_e1";
    joint_manes[4]="left_w0";
    joint_manes[5]="left_w1";
    joint_manes[6]="left_w2";

    // One point trajectory
    trajectory_msgs::JointTrajectoryPoint point;
    point.positions.resize(n_joints,0.0);
    point.velocities.resize(n_joints,0.0);
    point.accelerations.resize(n_joints,0.0);    
    trajectory_msgs::JointTrajectory traj_home;
    traj_home.joint_names=joint_manes;
//    traj_home.header.stamp = ros::Time(0); // start inmediately
    traj_home.points.resize(1,point);
    traj_home.points[0].positions[0] = 1.57961671452;
    traj_home.points[0].positions[1] = 0.277267027094;
    traj_home.points[0].positions[2] = -1.9684808438;
    traj_home.points[0].positions[3] = 2.46510712332;
    traj_home.points[0].positions[4] = 1.49601476168;
    traj_home.points[0].positions[5] = 1.97768472852;
    traj_home.points[0].positions[6] = -0.0636602026245;
    traj_home.points[0].time_from_start = ros::Duration(10.0);
    // Action goal
    control_msgs::FollowJointTrajectoryGoal goal_home;
    goal_home.trajectory = traj_home;
    ROS_INFO_STREAM("Press ENTER to start to trajectory to home");
    std::cin.get();
    goal_home.trajectory.header.stamp = ros::Time::now(); // start now
    client.sendGoal(goal_home);
    ROS_ASSERT_MSG(client.waitForResult(),"Home not reached.");
    ROS_INFO("Home reached. Ready for next trajectory");
    ROS_INFO_STREAM("action client state is " << client.getState().toString());


    // Three point trajectory
    std::vector<trajectory_msgs::JointTrajectoryPoint> points(3,point);

//    time,       left_s0,      left_s1,       left_e0,      left_e1,      left_w0,      left_w1,      left_w2,
//    0.277026,   1.57961671452,0.277267027094,-1.9684808438,2.46510712332,1.49601476168,1.97768472852,-0.0636602026245
    points[0].positions[0] = 1.57961671452;
    points[0].positions[1] = 0.277267027094;
    points[0].positions[2] = -1.9684808438;
    points[0].positions[3] = 2.46510712332;
    points[0].positions[4] = 1.49601476168;
    points[0].positions[5] = 1.97768472852;
    points[0].positions[6] = -0.0636602026245;
    points[0].time_from_start = ros::Duration(0.277026);

//    time,       left_s0,       left_s1,       left_e0,        left_e1,      left_w0,      left_w1,      left_w2,
//    7.290323,   1.02163120356, 0.145728174683,-1.95889346389, 2.37115080016,1.57156331539,1.637140994,  -0.0644271930176
    points[1].positions[0] = 1.02163120356;
    points[1].positions[1] = 0.145728174683;
    points[1].positions[2] = -1.95889346389;
    points[1].positions[3] = 2.37115080016;
    points[1].positions[4] = 1.57156331539;
    points[1].positions[5] = 1.637140994;
    points[1].positions[6] = -0.0644271930176;
//    points[1].time_from_start = ros::Duration(7.290323);
    points[1].time_from_start = ros::Duration(4);

//    time,       left_s0,          left_s1,       left_e0,        left_e1,      left_w0,      left_w1,      left_w2,
//    13.590337,  -0.0951068087402, 0.107762150226,-2.06435464294, 1.504451656,  2.0129662866, 1.65708274422,-0.0636602026245
    points[2].positions[0] = -0.0951068087402;
    points[2].positions[1] = 0.107762150226;
    points[2].positions[2] = -2.06435464294;
    points[2].positions[3] = 1.504451656;
    points[2].positions[4] = 2.0129662866;
    points[2].positions[5] = 1.65708274422;
    points[2].positions[6] = -0.0636602026245;
//    points[2].time_from_start = ros::Duration(13.590337);
    points[2].time_from_start = ros::Duration(9);

    trajectory_msgs::JointTrajectory traj;
    traj.joint_names=joint_manes;
//    traj.header.stamp = ros::Time(0); // start inmediately
    traj.points=points;
    // Action goals
    control_msgs::FollowJointTrajectoryGoal goal;
    goal.trajectory = traj;
    ROS_INFO_STREAM("Press ENTER to start a new trajectory");
    std::cin.get();
    goal.trajectory.header.stamp = ros::Time::now() + ros::Duration(1.0); // start 1s after now
    client.sendGoal(goal);
    ROS_ASSERT_MSG(client.waitForResult(),"Goal not reached.");
    ROS_INFO("Goal reached!");
    ROS_INFO_STREAM("action client state is " << client.getState().toString());

    ros::shutdown();

}
void QgsMapToolAddFeature::canvasReleaseEvent( QMouseEvent * e )
{
  QgsDebugMsg( "entered." );

  QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( mCanvas->currentLayer() );

  if ( !vlayer )
  {
    notifyNotVectorLayer();
    return;
  }

  QGis::WkbType layerWKBType = vlayer->wkbType();

  QgsVectorDataProvider* provider = vlayer->dataProvider();

  if ( !( provider->capabilities() & QgsVectorDataProvider::AddFeatures ) )
  {
    QMessageBox::information( 0, tr( "Layer cannot be added to" ),
                              tr( "The data provider for this layer does not support the addition of features." ) );
    return;
  }

  if ( !vlayer->isEditable() )
  {
    notifyNotEditableLayer();
    return;
  }

  // POINT CAPTURING
  if ( mode() == CapturePoint )
  {
    //check we only use this tool for point/multipoint layers
    if ( vlayer->geometryType() != QGis::Point )
    {
      QMessageBox::information( 0, tr( "Wrong editing tool" ),
                                tr( "Cannot apply the 'capture point' tool on this vector layer" ) );
      return;
    }


    QgsPoint idPoint; //point in map coordinates
    QList<QgsSnappingResult> snapResults;
    QgsPoint savePoint; //point in layer coordinates

    if ( mSnapper.snapToBackgroundLayers( e->pos(), snapResults ) == 0 )
    {
      idPoint = snapPointFromResults( snapResults, e->pos() );
      try
      {
        savePoint = toLayerCoordinates( vlayer, idPoint );
        QgsDebugMsg( "savePoint = " + savePoint.toString() );
      }
      catch ( QgsCsException &cse )
      {
        Q_UNUSED( cse );
        QMessageBox::information( 0, tr( "Coordinate transform error" ),
                                  tr( "Cannot transform the point to the layers coordinate system" ) );
        return;
      }
    }

    //only do the rest for provider with feature addition support
    //note that for the grass provider, this will return false since
    //grass provider has its own mechanism of feature addition
    if ( provider->capabilities() & QgsVectorDataProvider::AddFeatures )
    {
      QgsFeature* f = new QgsFeature( 0 );

      QgsGeometry *g = 0;
      if ( layerWKBType == QGis::WKBPoint || layerWKBType == QGis::WKBPoint25D )
      {
        g = QgsGeometry::fromPoint( savePoint );
      }
      else if ( layerWKBType == QGis::WKBMultiPoint || layerWKBType == QGis::WKBMultiPoint25D )
      {
        g = QgsGeometry::fromMultiPoint( QgsMultiPoint() << savePoint );
      }

      f->setGeometry( g );

      vlayer->beginEditCommand( tr( "Feature added" ) );

      if ( addFeature( vlayer, f ) )
      {
        vlayer->endEditCommand();
      }
      else
      {
        delete f;
        vlayer->destroyEditCommand();
      }

      mCanvas->refresh();
    }
  }
  else if ( mode() == CaptureLine || mode() == CapturePolygon )
  {
    //check we only use the line tool for line/multiline layers
    if ( mode() == CaptureLine && vlayer->geometryType() != QGis::Line )
    {
      QMessageBox::information( 0, tr( "Wrong editing tool" ),
                                tr( "Cannot apply the 'capture line' tool on this vector layer" ) );
      return;
    }

    //check we only use the polygon tool for polygon/multipolygon layers
    if ( mode() == CapturePolygon && vlayer->geometryType() != QGis::Polygon )
    {
      QMessageBox::information( 0, tr( "Wrong editing tool" ),
                                tr( "Cannot apply the 'capture polygon' tool on this vector layer" ) );
      return;
    }

    //add point to list and to rubber band
    int error = addVertex( e->pos() );
    if ( error == 1 )
    {
      //current layer is not a vector layer
      return;
    }
    else if ( error == 2 )
    {
      //problem with coordinate transformation
      QMessageBox::information( 0, tr( "Coordinate transform error" ),
                                tr( "Cannot transform the point to the layers coordinate system" ) );
      return;
    }

    if ( e->button() == Qt::LeftButton )
    {
      startCapturing();
    }
    else if ( e->button() == Qt::RightButton )
    {
      // End of string

      //lines: bail out if there are not at least two vertices
      if ( mode() == CaptureLine && size() < 2 )
      {
        stopCapturing();
        return;
      }

      //polygons: bail out if there are not at least two vertices
      if ( mode() == CapturePolygon && size() < 3 )
      {
        stopCapturing();
        return;
      }

      //create QgsFeature with wkb representation
      QgsFeature* f = new QgsFeature( 0 );

      QgsGeometry *g;

      if ( mode() == CaptureLine )
      {
        if ( layerWKBType == QGis::WKBLineString || layerWKBType == QGis::WKBLineString25D )
        {
          g = QgsGeometry::fromPolyline( points().toVector() );
        }
        else if ( layerWKBType == QGis::WKBMultiLineString || layerWKBType == QGis::WKBMultiLineString25D )
        {
          g = QgsGeometry::fromMultiPolyline( QgsMultiPolyline() << points().toVector() );
        }
        else
        {
          QMessageBox::critical( 0, tr( "Error" ), tr( "Cannot add feature. Unknown WKB type" ) );
          stopCapturing();
          return; //unknown wkbtype
        }

        f->setGeometry( g );
      }
      else // polygon
      {
        if ( layerWKBType == QGis::WKBPolygon ||  layerWKBType == QGis::WKBPolygon25D )
        {
          g = QgsGeometry::fromPolygon( QgsPolygon() << points().toVector() );
        }
        else if ( layerWKBType == QGis::WKBMultiPolygon ||  layerWKBType == QGis::WKBMultiPolygon25D )
        {
          g = QgsGeometry::fromMultiPolygon( QgsMultiPolygon() << ( QgsPolygon() << points().toVector() ) );
        }
        else
        {
          QMessageBox::critical( 0, tr( "Error" ), tr( "Cannot add feature. Unknown WKB type" ) );
          stopCapturing();
          return; //unknown wkbtype
        }

        if ( !g )
        {
          stopCapturing();
          delete f;
          return; // invalid geometry; one possibility is from duplicate points
        }
        f->setGeometry( g );

        int avoidIntersectionsReturn = f->geometry()->avoidIntersections();
        if ( avoidIntersectionsReturn == 1 )
        {
          //not a polygon type. Impossible to get there
        }
#if 0
        else if ( avoidIntersectionsReturn == 2 ) //MH120131: disable this error message until there is a better way to cope with the single type / multi type problem
        {
          //bail out...
          QMessageBox::critical( 0, tr( "Error" ), tr( "The feature could not be added because removing the polygon intersections would change the geometry type" ) );
          delete f;
          stopCapturing();
          return;
        }
#endif
        else if ( avoidIntersectionsReturn == 3 )
        {
          QMessageBox::critical( 0, tr( "Error" ), tr( "An error was reported during intersection removal" ) );
        }

        if ( !f->geometry()->asWkb() ) //avoid intersection might have removed the whole geometry
        {
          QString reason;
          if ( avoidIntersectionsReturn != 2 )
          {
            reason = tr( "The feature cannot be added because it's geometry is empty" );
          }
          else
          {
            reason = tr( "The feature cannot be added because it's geometry collapsed due to intersection avoidance" );
          }
          QMessageBox::critical( 0, tr( "Error" ), reason );
          delete f;
          stopCapturing();
          return;
        }
      }

      vlayer->beginEditCommand( tr( "Feature added" ) );

      if ( addFeature( vlayer, f ) )
      {
        //add points to other features to keep topology up-to-date
        int topologicalEditing = QgsProject::instance()->readNumEntry( "Digitizing", "/TopologicalEditing", 0 );

        //use always topological editing for avoidIntersection.
        //Otherwise, no way to guarantee the geometries don't have a small gap in between.
        QStringList intersectionLayers = QgsProject::instance()->readListEntry( "Digitizing", "/AvoidIntersectionsList" );
        bool avoidIntersection = !intersectionLayers.isEmpty();
        if ( avoidIntersection ) //try to add topological points also to background layers
        {
          QStringList::const_iterator lIt = intersectionLayers.constBegin();
          for ( ; lIt != intersectionLayers.constEnd(); ++lIt )
          {
            QgsMapLayer* ml = QgsMapLayerRegistry::instance()->mapLayer( *lIt );
            QgsVectorLayer* vl = qobject_cast<QgsVectorLayer*>( ml );
            //can only add topological points if background layer is editable...
            if ( vl && vl->geometryType() == QGis::Polygon && vl->isEditable() )
            {
              vl->addTopologicalPoints( f->geometry() );
            }
          }
        }
        else if ( topologicalEditing )
        {
          vlayer->addTopologicalPoints( f->geometry() );
        }

        vlayer->endEditCommand();
      }
      else
      {
        delete f;
        vlayer->destroyEditCommand();
      }

      stopCapturing();
    }
  }
}
Exemplo n.º 25
0
void HilbertRTreeSplit<splitOrder>::
RedistributePointsEvenly(TreeType* parent,
                         const size_t firstSibling,
                         const size_t lastSibling)
{
  size_t numPoints = 0;
  size_t numPointsPerNode, numRestPoints;

  for (size_t i = firstSibling; i <= lastSibling; i++)
    numPoints += parent->Child(i).NumPoints();

  numPointsPerNode = numPoints / (lastSibling - firstSibling + 1);
  numRestPoints = numPoints % (lastSibling - firstSibling + 1);

  std::vector<size_t> points(numPoints);

  // Copy children's points in order to redistribute them.
  size_t iPoint = 0;
  for (size_t i = firstSibling; i <= lastSibling; i++)
  {
    for (size_t j = 0; j < parent->Child(i).NumPoints(); j++)
      points[iPoint++] = parent->Child(i).Point(j);
  }

  iPoint = 0;
  for (size_t i = firstSibling; i <= lastSibling; i++)
  {
    // Since we redistribute points of a sibling we should recalculate the
    // bound.
    parent->Child(i).Bound().Clear();

    size_t j;
    for (j = 0; j < numPointsPerNode; j++)
    {
      parent->Child(i).Bound() |= parent->Dataset().col(points[iPoint]);
      parent->Child(i).Point(j) = points[iPoint];
      iPoint++;
    }
    if (numRestPoints > 0)
    {
      parent->Child(i).Bound() |= parent->Dataset().col(points[iPoint]);
      parent->Child(i).Point(j) = points[iPoint];
      parent->Child(i).Count() = numPointsPerNode + 1;
      numRestPoints--;
      iPoint++;
    }
    else
    {
      parent->Child(i).Count() = numPointsPerNode;
    }
    parent->Child(i).numDescendants = parent->Child(i).Count();

    assert(parent->Child(i).NumPoints() <=
           parent->Child(i).MaxLeafSize());
  }

  // Fix the largest Hilbert values of the siblings.
  parent->AuxiliaryInfo().HilbertValue().RedistributeHilbertValues(parent,
      firstSibling, lastSibling);

  TreeType* root = parent;

  while (root != NULL)
  {
    root->AuxiliaryInfo().HilbertValue().UpdateLargestValue(root);
    root = root->Parent();
  }
}
Exemplo n.º 26
0
void TColorStyle::makeIcon(const TDimension &d) {
  checkErrorsByGL;
  TColorStyle *style = this->clone();
  checkErrorsByGL;

  TPaletteP tmpPalette = new TPalette();
  checkErrorsByGL;
  int id = tmpPalette->addStyle(style);
  checkErrorsByGL;

  int contextLx = pow(2.0, tceil(log((double)d.lx) / log(2.0)));
  int contextLy = pow(2.0, tceil(log((double)d.ly) / log(2.0)));
  TDimension dim(contextLx, contextLy);

  TOfflineGL *glContext = TOfflineGL::getStock(dim);

  checkErrorsByGL;
  glContext->clear(TPixel32::White);
  checkErrorsByGL;

  TVectorImageP img = new TVectorImage;
  checkErrorsByGL;
  img->setPalette(tmpPalette.getPointer());
  checkErrorsByGL;

  std::vector<TThickPoint> points(3);

  if (isRegionStyle() && !isStrokeStyle()) {
    points[0]        = TThickPoint(-55, -50, 1);
    points[1]        = TThickPoint(0, -60, 1);
    points[2]        = TThickPoint(55, -50, 1);
    TStroke *stroke1 = new TStroke(points);

    img->addStroke(stroke1);

    points[0]        = TThickPoint(50, -55, 1);
    points[1]        = TThickPoint(60, 0, 1);
    points[2]        = TThickPoint(50, 55, 1);
    TStroke *stroke2 = new TStroke(points);
    img->addStroke(stroke2);

    points[0]        = TThickPoint(55, 50, 1);
    points[1]        = TThickPoint(0, 60, 1);
    points[2]        = TThickPoint(-55, 50, 1);
    TStroke *stroke3 = new TStroke(points);
    img->addStroke(stroke3);

    points[0]        = TThickPoint(-50, 55, 1);
    points[1]        = TThickPoint(-60, 0, 1);
    points[2]        = TThickPoint(-50, -55, 1);
    TStroke *stroke4 = new TStroke(points);
    img->addStroke(stroke4);

    img->fill(TPointD(0, 0), id);
  } else if (isStrokeStyle() && !isRegionStyle()) {
    double rasX05 = d.lx * 0.5;
    double rasY05 = d.ly * 0.5;

    points[0]        = TThickPoint(-rasX05, -rasY05, 7);
    points[1]        = TThickPoint(0, -rasY05, 9);
    points[2]        = TThickPoint(rasX05, rasY05, 12);
    TStroke *stroke1 = new TStroke(points);

    stroke1->setStyle(id);

    img->addStroke(stroke1);
    points.clear();
  } else if (!isRasterStyle()) {
    assert(isStrokeStyle() && isRegionStyle());

    points[0]        = TThickPoint(-60, -30, 0.5);
    points[1]        = TThickPoint(0, -30, 0.5);
    points[2]        = TThickPoint(60, -30, 0.5);
    TStroke *stroke1 = new TStroke(points);
    stroke1->setStyle(id);
    img->addStroke(stroke1);

    points[0]        = TThickPoint(60, -30, 0.5);
    points[1]        = TThickPoint(60, 0, 0.5);
    points[2]        = TThickPoint(60, 30, 0.5);
    TStroke *stroke2 = new TStroke(points);
    stroke2->setStyle(id);
    img->addStroke(stroke2);

    points[0]        = TThickPoint(60, 30, 0.5);
    points[1]        = TThickPoint(0, 30, 0.5);
    points[2]        = TThickPoint(-60, 30, 0.5);
    TStroke *stroke3 = new TStroke(points);
    stroke3->setStyle(id);
    img->addStroke(stroke3);

    points[0]        = TThickPoint(-60, 30, 0.5);
    points[1]        = TThickPoint(-60, 0, 0.5);
    points[2]        = TThickPoint(-60, -30, 0.5);
    TStroke *stroke4 = new TStroke(points);
    stroke4->setStyle(id);
    img->addStroke(stroke4);

    img->fill(TPointD(0, 0), id);
  }

  TRectD bbox = img->getBBox();
  checkErrorsByGL;

  bbox = bbox.enlarge(TDimensionD(-10, -10));
  checkErrorsByGL;

  double scx = 0.9 * d.lx / bbox.getLx();
  double scy = 0.9 * d.ly / bbox.getLy();
  double sc  = std::min(scx, scy);
  double dx  = (d.lx - bbox.getLx() * sc) * 0.5;
  double dy  = (d.ly - bbox.getLy() * sc) * 0.5;
  TAffine aff =
      TScale(scx, scy) * TTranslation(-bbox.getP00() + TPointD(dx, dy));

  checkErrorsByGL;
  if (isRegionStyle() && !isStrokeStyle()) aff = aff * TTranslation(-10, -10);

  checkErrorsByGL;
  const TVectorRenderData rd(aff, TRect(), tmpPalette.getPointer(), 0, true);
  checkErrorsByGL;
  glContext->draw(img, rd);
  checkErrorsByGL;

  TRect rect(d);
  if (!m_icon || m_icon->getSize() != d) {
    checkErrorsByGL;
    m_icon = glContext->getRaster()->extract(rect)->clone();
  } else {
    checkErrorsByGL;
    m_icon->copy(glContext->getRaster()->extract(rect));
  }
}
Exemplo n.º 27
0
void QgsMapToolReshape::canvasReleaseEvent( QMouseEvent * e )
{
  //check if we operate on a vector layer //todo: move this to a function in parent class to avoid duplication
  QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( mCanvas->currentLayer() );

  if ( !vlayer )
  {
    notifyNotVectorLayer();
    return;
  }

  if ( !vlayer->isEditable() )
  {
    notifyNotEditableLayer();
    return;
  }

  //add point to list and to rubber band
  if ( e->button() == Qt::LeftButton )
  {
    int error = addVertex( e->pos() );
    if ( error == 1 )
    {
      //current layer is not a vector layer
      return;
    }
    else if ( error == 2 )
    {
      //problem with coordinate transformation
      QMessageBox::information( 0, tr( "Coordinate transform error" ),
                                   tr( "Cannot transform the point to the layers coordinate system" ) );
      return;
    }

    startCapturing();
  }
  else if ( e->button() == Qt::RightButton )
  {
    deleteTempRubberBand();

    //find out bounding box of mCaptureList
    if ( size() < 1 )
    {
      stopCapturing();
      return;
    }
    QgsPoint firstPoint = points().at( 0 );
    QgsRectangle bbox( firstPoint.x(), firstPoint.y(), firstPoint.x(), firstPoint.y() );
    for ( int i = 1; i < size(); ++i )
    {
      bbox.combineExtentWith( points().at( i ).x(), points().at( i ).y() );
    }

    //query all the features that intersect bounding box of capture line
    QgsFeatureIterator fit = vlayer->getFeatures( QgsFeatureRequest().setFilterRect( bbox ).setSubsetOfAttributes( QgsAttributeList() ) );
    QgsFeature f;
    int reshapeReturn;
    bool reshapeDone = false;

    vlayer->beginEditCommand( tr( "Reshape" ) );
    while ( fit.nextFeature( f ) )
    {
      //query geometry
      //call geometry->reshape(mCaptureList)
      //register changed geometry in vector layer
      QgsGeometry* geom = f.geometry();
      if ( geom )
      {
        reshapeReturn = geom->reshapeGeometry( points() );
        if ( reshapeReturn == 0 )
        {
          vlayer->changeGeometry( f.id(), geom );
          reshapeDone = true;
        }
      }
    }

    if ( reshapeDone )
    {
      vlayer->endEditCommand();
    }
    else
    {
      vlayer->destroyEditCommand();
    }

    stopCapturing();
  }
}
void Foam::processorPolyPatch::calcGeometry()
{
    if (Pstream::parRun())
    {
        {
            IPstream fromNeighbProc
            (
                Pstream::blocking,
                neighbProcNo(),
                3*(sizeof(label) + size()*sizeof(vector) + sizeof(scalar))
            );
            fromNeighbProc
                >> neighbFaceCentres_
                >> neighbFaceAreas_
                >> neighbFaceCellCentres_;
        }

        // My normals
        vectorField faceNormals(size());

        // Neighbour normals
        vectorField nbrFaceNormals(neighbFaceAreas_.size());

        // Calculate normals from areas and check

        // Cache face areas
        const vectorField::subField localFaceAreas = faceAreas();

        forAll (faceNormals, facei)
        {
            scalar magSf = mag(localFaceAreas[facei]);
            scalar nbrMagSf = mag(neighbFaceAreas_[facei]);
            scalar avSf = (magSf + nbrMagSf)/2.0;

            if (magSf < ROOTVSMALL && nbrMagSf < ROOTVSMALL)
            {
                // Undetermined normal. Use dummy normal to force separation
                // check. (note use of sqrt(VSMALL) since that is how mag
                // scales)
                faceNormals[facei] = point(1, 0, 0);
                nbrFaceNormals[facei] = faceNormals[facei];
            }
            else if (mag(magSf - nbrMagSf)/avSf > polyPatch::matchTol_)
            {
                FatalErrorIn
                (
                    "processorPolyPatch::calcGeometry()"
                )   << "face " << facei << " area does not match neighbour by "
                    << 100*mag(magSf - nbrMagSf)/avSf
                    << "% -- possible face ordering problem." << endl
                    << "patch: " << name()
                    << " my area:" << magSf
                    << " neighbour area: " << nbrMagSf
                    << " matching tolerance: " << polyPatch::matchTol_
                    << endl
                    << "Mesh face: " << start()+facei
                    << " vertices: "
                    << UIndirectList<point>(points(), operator[](facei))()
                    << endl
                    << "Rerun with processor debug flag set for"
                    << " more information." << exit(FatalError);
            }
            else
            {
                faceNormals[facei] = localFaceAreas[facei]/magSf;
                nbrFaceNormals[facei] = neighbFaceAreas_[facei]/nbrMagSf;
            }
        }

        calcTransformTensors
        (
            faceCentres(),
            neighbFaceCentres_,
            faceNormals,
            nbrFaceNormals,
            calcFaceTol(*this, points(), faceCentres())
        );
    }
Exemplo n.º 29
0
void VisualToolRotateXY::Draw() {
	if (!active_line) return;

	DrawAllFeatures();

	// Transform grid
	gl.SetOrigin(org->pos);
	gl.SetRotation(angle_x, angle_y, angle_z);
	gl.SetShear(fax, fay);

	// Draw grid
	gl.SetLineColour(colour[0], 0.5f, 2);
	gl.SetModeLine();
	float r = colour[0].Red() / 255.f;
	float g = colour[0].Green() / 255.f;
	float b = colour[0].Blue() / 255.f;

	// Number of lines on each side of each axis
	static const int radius = 15;
	// Total number of lines, including center axis line
	static const int line_count = radius * 2 + 1;
	// Distance between each line in pixels
	static const int spacing = 20;
	// Length of each grid line in pixels from axis to one end
	static const int half_line_length = spacing * (radius + 1);
	static const float fade_factor = 0.9f / radius;

	std::vector<float> colors(line_count * 8 * 4);
	for (int i = 0; i < line_count * 8; ++i) {
		colors[i * 4 + 0] = r;
		colors[i * 4 + 1] = g;
		colors[i * 4 + 2] = b;
		colors[i * 4 + 3] = (i + 3) % 4 > 1 ? 0 : (1.f - abs(i / 8 - radius) * fade_factor);
	}

	std::vector<float> points(line_count * 8 * 2);
	for (int i = 0; i < line_count; ++i) {
		int pos = spacing * (i - radius);

		points[i * 16 + 0] = pos;
		points[i * 16 + 1] = half_line_length;

		points[i * 16 + 2] = pos;
		points[i * 16 + 3] = 0;

		points[i * 16 + 4] = pos;
		points[i * 16 + 5] = 0;

		points[i * 16 + 6] = pos;
		points[i * 16 + 7] = -half_line_length;

		points[i * 16 + 8] = half_line_length;
		points[i * 16 + 9] = pos;

		points[i * 16 + 10] = 0;
		points[i * 16 + 11] = pos;

		points[i * 16 + 12] = 0;
		points[i * 16 + 13] = pos;

		points[i * 16 + 14] = -half_line_length;
		points[i * 16 + 15] = pos;
	}

	gl.DrawLines(2, points, 4, colors);

	// Draw vectors
	gl.SetLineColour(colour[3], 1.f, 2);
	float vectors[] = {
		0.f, 0.f, 0.f,
		50.f, 0.f, 0.f,
		0.f, 0.f, 0.f,
		0.f, 50.f, 0.f,
		0.f, 0.f, 0.f,
		0.f, 0.f, 50.f,
	};
	gl.DrawLines(3, vectors, 6);

	// Draw arrow tops
	float arrows[] = {
		60.f,  0.f,  0.f,
		50.f, -3.f, -3.f,
		50.f,  3.f, -3.f,
		50.f,  3.f,  3.f,
		50.f, -3.f,  3.f,
		50.f, -3.f, -3.f,

		 0.f, 60.f,  0.f,
		-3.f, 50.f, -3.f,
		 3.f, 50.f, -3.f,
		 3.f, 50.f,  3.f,
		-3.f, 50.f,  3.f,
		-3.f, 50.f, -3.f,

		 0.f,  0.f, 60.f,
		-3.f, -3.f, 50.f,
		 3.f, -3.f, 50.f,
		 3.f,  3.f, 50.f,
		-3.f,  3.f, 50.f,
		-3.f, -3.f, 50.f,
	};

	gl.DrawLines(3, arrows, 18);

	gl.ResetTransform();
}
Exemplo n.º 30
0
void compute(int nlhs, mxArray  *plhs[], int nrhs, const mxArray  *prhs[], const int atria_preprocessing_given,  METRIC dummy)
{ 
	long i,j,n,k;		/* loop variables */ 

	/* handle matrix I/O */
	
	const long N = mxGetM(prhs[0]);	
	const long dim = mxGetN(prhs[0]);
	const double* p  	= (double *)mxGetPr(prhs[0]);
	
	const long R = max(mxGetM(prhs[1]), mxGetN(prhs[1]));
	const double* ref 	= (double *)mxGetPr(prhs[1]);
	
	const double  relative_range = (double) *((double *)mxGetPr(prhs[2]));
	const long past	= (long) *((double *)mxGetPr(prhs[3]));
	
	if (N < 1) {
		mexErrMsgTxt("Data set must consist of at least two points (row vectors)");
		return;
	}		
	if (dim < 2) {
		mexErrMsgTxt("Data points must be at least of dimension two");
		return;
	}		
	if ((mxGetN(prhs[1]) == 0) || (mxGetM(prhs[1]) == 0)) {
		mexErrMsgTxt("Wrong reference indices given");
		return;
	}	
		
	if (R < 1) {
		mexErrMsgTxt("At least one reference index or point must be given");
		return;
	}	

	for (i=0; i < R; i++) {
		if ((ref[i] < 1) || (ref[i]>N)) {
			mexErrMsgTxt("Reference indices out of range");
			return;
		}	
	}
	
	point_set<METRIC> points(N,dim, p);	
	ATRIA< point_set<METRIC> >* searcher = 0;	

#ifdef MATLAB_MEX_FILE	
	if (atria_preprocessing_given) {
		searcher = new ATRIA< point_set<METRIC> >(points, prhs[-1]);	// this constructor used the data from the preprocessing 
		if (searcher->geterr()) {
			delete searcher;
			searcher = 0;
		}
	} 
#endif
	
	if (searcher == 0) {
		searcher = new ATRIA< point_set<METRIC> >(points);	
	}
	
	if (searcher->geterr()) {
		mexErrMsgTxt("Error preparing searcher");
		return;
	}	 		
	
	double range;
	
	if (relative_range > 0)	
		range = relative_range * searcher->data_set_radius();  // compute the maximal search radius using information about attractor size
	else
		range = fabs(relative_range); 	// if relative_range is negativ, use it's value (without sign) as maximal search radius  

	mexPrintf("Number of reference points            : %d\n", R);
	mexPrintf("Upper bound for attractor size        : %f\n", 2 * searcher->data_set_radius());	
	mexPrintf("Maximal search radius                 : %f\n", range);

	plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
	double* out = (double *) mxGetPr(plhs[0]);
	
	unsigned long counter = 0;	
	double sum = 0;

	for (n=0; n < R; n++) { 		/* iterate over all reference points */ 
          const long actual = (long) ref[n]-1;		/* Matlab to C means indices change from 1 to 0, 2 to 1, 3 to 2 ...*/

		if (actual > past) {
			vector<neighbor> v;

			searcher->search_range(v, range, points.point_begin(actual), actual-past, N); // don't search points from [actual-past .. N-1]
			//overall_points += (actual-past);	// count the total number of points pairs that were at least theoretically tested

			if (v.size() > 0) {	
				vector<neighbor>::iterator i;
				
				for (i = v.begin(); i < v.end(); i++) { // v is unsorted
					const double dist = (*i).dist();
					if (dist > 0) {
						sum += log(dist/range);
						counter++;
					}
				}
			}
		}
	}

	if (counter > 0) *out = -((double)counter)/sum;
	else *out = 0;
		
	delete searcher;
}