IfcSchema::IfcProductDefinitionShape* IfcGeom::tesselate(const TopoDS_Shape& shape, double deflection) {
	BRepMesh_IncrementalMesh(shape, deflection);

	IfcSchema::IfcFace::list::ptr faces(new IfcSchema::IfcFace::list);

	for (TopExp_Explorer exp(shape, TopAbs_FACE); exp.More(); exp.Next()) {
		const TopoDS_Face& face = TopoDS::Face(exp.Current());
		TopLoc_Location loc;
		Handle(Poly_Triangulation) tri = BRep_Tool::Triangulation(face, loc);

		if (!tri.IsNull()) {
			const TColgp_Array1OfPnt& nodes = tri->Nodes();
			std::vector<IfcSchema::IfcCartesianPoint*> vertices;
			for (int i = 1; i <= nodes.Length(); ++i) {
				gp_Pnt pnt = nodes(i).Transformed(loc);
				std::vector<double> xyz; xyz.push_back(pnt.X()); xyz.push_back(pnt.Y()); xyz.push_back(pnt.Z());
				IfcSchema::IfcCartesianPoint* cpnt = new IfcSchema::IfcCartesianPoint(xyz);
				vertices.push_back(cpnt);
			}
			const Poly_Array1OfTriangle& triangles = tri->Triangles();
			for (int i = 1; i <= triangles.Length(); ++i) {
				int n1, n2, n3;
				triangles(i).Get(n1, n2, n3);
				IfcSchema::IfcCartesianPoint::list::ptr points(new IfcSchema::IfcCartesianPoint::list);
				points->push(vertices[n1 - 1]);
				points->push(vertices[n2 - 1]);
				points->push(vertices[n3 - 1]);
				IfcSchema::IfcPolyLoop* loop = new IfcSchema::IfcPolyLoop(points);
				IfcSchema::IfcFaceOuterBound* bound = new IfcSchema::IfcFaceOuterBound(loop, face.Orientation() != TopAbs_REVERSED);
				IfcSchema::IfcFaceBound::list::ptr bounds(new IfcSchema::IfcFaceBound::list);
				bounds->push(bound);
				IfcSchema::IfcFace* face2 = new IfcSchema::IfcFace(bounds);
				faces->push(face2);
			}
		}
	}
	IfcSchema::IfcOpenShell* shell = new IfcSchema::IfcOpenShell(faces);
	IfcSchema::IfcConnectedFaceSet::list::ptr shells(new IfcSchema::IfcConnectedFaceSet::list);
	shells->push(shell);
	IfcSchema::IfcFaceBasedSurfaceModel* surface_model = new IfcSchema::IfcFaceBasedSurfaceModel(shells);

	IfcSchema::IfcRepresentation::list::ptr reps(new IfcSchema::IfcRepresentation::list);
	IfcSchema::IfcRepresentationItem::list::ptr items(new IfcSchema::IfcRepresentationItem::list);

	items->push(surface_model);

	IfcSchema::IfcShapeRepresentation* rep = new IfcSchema::IfcShapeRepresentation(
		0, std::string("Facetation"), std::string("SurfaceModel"), items);

	reps->push(rep);
	IfcSchema::IfcProductDefinitionShape* shapedef = new IfcSchema::IfcProductDefinitionShape(boost::none, boost::none, reps);

	return shapedef;
}
예제 #2
0
Mesh_Ptr Mesh_File_Reader::read(
    const Label & name,
    bool load_vertices,
    bool load_triangles,
    bool load_triangle_strips,
    bool load_mapping
)  /* throw IO_Error */
{
    Mesh_Ptr mesh_ptr(new Mesh());
    Mesh &mesh = *mesh_ptr.get();
    
    Filename binary_filename(_mesh_path / (name + ".bin"));    
    if(!boost::filesystem::exists(binary_filename)) 
    {
        Filename vertex_filename, triangle_filename, 
            triangle_strip_filename, mapping_filename;
        if (load_vertices)
            vertex_filename = _mesh_path / (name + ".vert");
        if (load_triangles)
            triangle_filename = _mesh_path / (name + ".tri");
        if (load_triangle_strips)
            triangle_strip_filename = _mesh_path / (name + ".strip");
        if (load_mapping)
            mapping_filename = _mesh_path / (name + ".map");
        Mesh_ASCII_File_Parser parser;
        parser.read_mesh(
            vertex_filename,
            triangle_filename,
            triangle_strip_filename,
            mapping_filename,
            vertex_count(mesh),
            triangle_count(mesh),
            triangle_strip_length(mesh),
            vertices(mesh),
            vertex_sections(mesh),
            vertex_relative_distances(mesh),
            triangles(mesh),
            triangle_strip(mesh));
    } else {
        Mesh_Binary_File_Parser parser;
        parser.read_mesh(
            binary_filename,
            load_vertices,
            load_triangles,
            load_triangle_strips,
            load_mapping,
            vertex_count(mesh),
            triangle_count(mesh),
            triangle_strip_length(mesh),
            vertices(mesh),
            vertex_sections(mesh),
            vertex_relative_distances(mesh),
            triangles(mesh),
            triangle_strip(mesh));
    }
    
    return mesh_ptr;
}
예제 #3
0
void EdgeCell::drawRawTopology(Time time, ViewSettings & viewSettings)
{
    bool screenRelative = viewSettings.screenRelative();
    if(screenRelative)
    {
        triangles(viewSettings.edgeTopologyWidth() / viewSettings.zoom(), time).draw();
    }
    else
    {
        triangles(viewSettings.edgeTopologyWidth(), time).draw();
    }
}
예제 #4
0
//Draw textures within the m_texture_planes[plane_id].
void mgTLData::drawt_texture_image_part(
	const MGTextureImages& teximage,	//texture image data.
	const double back_color[4],	//back ground color data.
	int plane_id	//indicates if only parts of texture data be drawn.
		//let i1=m_texture_planes[plane_id]->index(), and i2=m_texture_planes[plane_id+1]->index().
		//Then rects of m_rects[i1] to m_rects[i2-1] are to be drawn.
)const{
	mgGDL::draw_texture_image_set_up(back_color);

	const mgTLTriangles& tris=triangles();
	mgTLTriangles::const_triIterator first=tris.begin(), last=tris.end();;
	const std::vector<mgTLTexPlane*>& texplanes=tlrects().texture_planes();
	int ntpls=texplanes.size();
	if(plane_id<ntpls){
		int i1=texplanes[plane_id]->index();
		const mgTLRect& recti=rect(i1);
		int tri_id1=rect(i1).triangle_id();
		first+=tri_id1;
		if(plane_id<ntpls-1){
			int i2=texplanes[plane_id+1]->index();
			int tri_id2=rect(i2).triangle_id();
			last=first+(tri_id2-tri_id1);
		}
	}
	draw_texture(teximage,first,last);

	mgGDL::draw_texture_image_end_up();
}
std::vector<Triangle> PenultimateTriangle::connectInnerPoints()
{
    std::vector<Triangle> triangles(3);
    Point p1=getVertex(0);
    Point p2=getVertex(1);
    Point p3=getVertex(2);
    
    Point fp1=inners.at(0);
    Point fp2=inners.at(1);
    Point fp3=inners.at(2);
    double ttt=attributes.at("ttt");
    double nnn=attributes.at("nnn");
    
    if ( (ttt>0.0 && nnn>0.0) || (ttt<0.0 && nnn<0.0) )
    {
        //std::cout << "\n\n\n" << ttt << " " << nnn << "\n\n\n";
        triangles.at(0)=Triangle(p1,fp2,p2);
        triangles.at(1)=Triangle(p2,fp3,p3);
        triangles.at(2)=Triangle(p3,fp1,p1);
    }
    else
    {
        //std::cout << "\n\n\n" << ttt << " " << nnn << "\n\n\n";
        triangles.at(0)=Triangle(p2,fp1,p1);
        triangles.at(1)=Triangle(p3,fp2,p2);
        triangles.at(2)=Triangle(p1,fp3,p3);
    }
    return triangles;
}
예제 #6
0
파일: main.cpp 프로젝트: cnovel/SurfRec
std::vector< std::vector <Point> > cubeProcessing(Cube c, std::vector< std::vector<int> > rotations, float res) {
	std::vector<int> markedVertices;

	int nbPointsInside = 0;
	bool swap = false;
	for (int i = 0; i < c.listOfPoints.size(); i++) {
		if (insideModel(c.listOfPoints[i])) {
			markedVertices.push_back(1);
			nbPointsInside++;
		} else {
			markedVertices.push_back(0);
		}
	}

	if (nbPointsInside > 4) {
		for (int i = 0; i < 8; i++) {
			markedVertices[i] = (markedVertices[i] == 1)?0:1;
		}
	}

	int code = -1;

	for (int i = 0; i < rotations.size(); i++) {
		code = computeRotatedCode(markedVertices, rotations[i]);
		if (acceptable(code)) {
			std::vector< std::vector <Point> > cubeTriangles = triangles(code, res, rotations[i], c);
			if (nbPointsInside <= 4) {
				return cubeTriangles;
			} else {
				return invertTriangles(cubeTriangles);
			}
		}
	}
}
예제 #7
0
Node *AbsoluteTransformator::toAbsolute(Node *relativeRoot, glm::mat4 transform) {
    if (relativeRoot == nullptr) new Group();
    glm::mat4 newTransform = relativeRoot->transform() * transform;
    Node *absoluteRoot;
    if (relativeRoot->children().size() > 0) {
        Group *absoluteGroup = new Group();
        for (auto child : relativeRoot->children()) {
            Node *absoluteChild = toAbsolute(static_cast<Node *>(child), newTransform);
            if (absoluteChild != nullptr) {
                absoluteGroup->append(absoluteChild);
            }
        }
        absoluteRoot = absoluteGroup;
    } else {
        PolygonalDrawable *poly = dynamic_cast<PolygonalDrawable *>(relativeRoot);
        if (poly == nullptr) {
            absoluteRoot = new Group();
        } else {
            auto relativeGeometry = poly->geometry();
            auto vertices = relativeGeometry->copyVertices();
            auto absoluteGeometry = new TriangleObject();
            p_TriangleList triangles = absoluteGeometry->triangles();
            
            for (auto index : relativeGeometry->indices()) {
                glm::vec4 homogenous = newTransform * glm::vec4(vertices.at(index), 1.0f);
                triangles->push_back(homogenous.xyz * (1 / homogenous.w));
            }
            absoluteRoot = absoluteGeometry;
        }
    }
    absoluteRoot->setName(relativeRoot->name());
    absoluteRoot->setReferenceFrame(Node::RF_Absolute);
    return absoluteRoot;
}
예제 #8
0
void testA2VColor()
{
    std::cout << "a2vectorTest testA2VColor" << std::endl;

    aam::Vertices2DList vertices(TOTAL_POINTS_NUMBER);
    aam::Vertices2DList basePoints(TOTAL_POINTS_NUMBER);

    for (int i = 0; i < TOTAL_POINTS_NUMBER; i++)
    {
        vertices[i].y = verticesAData[2 * i];
        vertices[i].x = verticesAData[2 * i + 1];
        basePoints[i].y = basePointsData[2 * i];
        basePoints[i].x = basePointsData[2 * i + 1];
    }

    std::vector<cv::Vec3i> triangles(TRIANGLES_NUMBER);

    for (int i = 0; i < TRIANGLES_NUMBER; i++)
    {
        triangles[i] = cv::Vec3i(&trianglesData[i * 3]);
    }

    try
    {
        cv::Mat im = cv::imread("data/01-1m.jpg");
        cv::Mat_<cv::Vec<aam::RealType, 3> > colorImage =
                cv::Mat_<cv::Vec<aam::RealType, 3> >(im) / 255.0;

        cv::Mat objectPixels = cv::imread("data/object_pixels.bmp",
                cv::IMREAD_GRAYSCALE);
        int nCount = cv::countNonZero(objectPixels);
        cv::Mat J;
        aam::RealMatrix grayVector;

        aam::AAMFunctions2D::appearance2Vector(colorImage, vertices,
                basePoints,
                objectPixels, nCount, triangles, J, grayVector);

//        cv::imshow("test", J);
//        cv::waitKey(0);
        if (J.cols != objectPixels.cols || J.rows != objectPixels.rows)
        {
            std::cout << "%TEST_FAILED% time=0 testname=testA2VColor (a2vectorTest) message=Invalid output texture size" << std::endl;
        }
        else if (J.channels() != 3)
        {
            std::cout << "%TEST_FAILED% time=0 testname=testA2VColor (a2vectorTest) message=Invalid output texture channels count" << std::endl;
        }
        else if (grayVector.cols != 1 || grayVector.rows != 3 * 52314)
        {
            std::cout << "%TEST_FAILED% time=0 testname=testA2VColor (a2vectorTest) message=Invalid output vector size" << std::endl;
        }
    }
    catch (std::exception& e)
    {
        std::cout << "%TEST_FAILED% time=0 testname=testA2VColor (a2vectorTest) message=Exception occured: " <<
                e.what() << std::endl;
    }
}
예제 #9
0
/* A more complex drawing function, using 2 separate viewports */
void draw_multi()
{
  GLint viewport[4];

  glScissor(0, 0, window_w, window_h);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  /* First viewport with triangles, teapot or torus, etc. */
  glViewport((GLint)(window_w * 0.05), (GLint)(window_h * 0.525),
             (GLsizei)(window_w * 0.9), (GLsizei)(window_h * 0.45));
  glScissor((GLint)(window_w * 0.05), (GLint)(window_h * 0.525),
            (GLsizei)(window_w * 0.9), (GLsizei)(window_h * 0.45));
  glClearColor(0.2, 0.2, 0.2, 0.);
  glGetIntegerv(GL_VIEWPORT, viewport);

  gl2psBeginViewport(viewport);

  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glOrtho(-1.3,1.3, -1.3,1.3, -1.3,1.3);
  glMatrixMode(GL_MODELVIEW);

  objects();
  triangles();
  extras();
  text();

  gl2psEndViewport();

  /* Second viewport with cube, image, etc. */
  glViewport((GLint)(window_w * 0.05), (GLint)(window_h * 0.025),
             (GLsizei)(window_w * 0.9), (GLsizei)(window_h * 0.45));
  glScissor((GLint)(window_w * 0.05), (GLint)(window_h * 0.025),
             (GLsizei)(window_w * 0.9), (GLsizei)(window_h * 0.45));
  glClearColor(0.8, 0.8, 0.8, 0.);
  glGetIntegerv(GL_VIEWPORT, viewport);

  gl2psBeginViewport(viewport);

  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glOrtho(-1.3,1.3, -1.3,1.3, -1.3,1.3);
  glMatrixMode(GL_MODELVIEW);

  glPushMatrix();
  glRotatef(rotation, 1., 1., 1.);
  image(-0.8, -0.3, GL_TRUE);
  cube();
  extras();
  image(-0.8, 0.4, GL_FALSE);
  glPopMatrix();

  gl2psEndViewport();

  glClearColor(0.5, 0.5, 0.5, 0.);
  glFlush();
}
예제 #10
0
// OpenGL display for shading.
void mgTLData::draw_texture(
	const MGTextureImage& teximage
)const{
	const mgTLTriangles& tris=triangles();
	for(mgTLTriangles::const_triIterator i=tris.begin(); i!=tris.end(); ++i){
		draw_texture_image_tri(**i,teximage.box());
	}
}
void ColladaSerializer::ColladaExporter::ColladaGeometries::write(const std::string mesh_id, const std::string& default_material_name, const std::vector<double>& positions, const std::vector<double>& normals, const std::vector<int>& indices, const std::vector<int> material_ids, const std::vector<IfcGeom::Material>& materials) {
	// The goal of the IfcGeom::Iterator is to filter out empty geometries, but
	// since this function would crash trying to deference the material_ids in
	// that case, a hard return statement is added just in case.
	if (indices.empty()) return;

	openMesh(mesh_id);

	// The normals vector can be empty for example when the WELD_VERTICES setting is used.
	// IfcOpenShell does not provide them with multiple face normals collapsed into a single vertex.
	const bool has_normals = !normals.empty();

	addFloatSource(mesh_id, COLLADASW::LibraryGeometries::POSITIONS_SOURCE_ID_SUFFIX, positions);
	if (has_normals) {
		addFloatSource(mesh_id, COLLADASW::LibraryGeometries::NORMALS_SOURCE_ID_SUFFIX, normals);
	}

	COLLADASW::VerticesElement vertices(mSW);
	vertices.setId(mesh_id + COLLADASW::LibraryGeometries::VERTICES_ID_SUFFIX );
	vertices.getInputList().push_back(COLLADASW::Input(COLLADASW::InputSemantic::POSITION, "#" + mesh_id + COLLADASW::LibraryGeometries::POSITIONS_SOURCE_ID_SUFFIX));
	vertices.add();
	
	std::vector<int>::const_iterator index_range_start = indices.begin();
	std::vector<int>::const_iterator material_it = material_ids.begin();
	int previous_material_id = -1;
	for (std::vector<int>::const_iterator it = indices.begin(); ; it += 3) {
		const int current_material_id = *(material_it++);
		const int num_triangles = std::distance(index_range_start, it) / 3;
		if ((previous_material_id != current_material_id && num_triangles > 0) || (it == indices.end())) {
			COLLADASW::Triangles triangles(mSW);
			triangles.setMaterial(materials[previous_material_id].name());
			triangles.setCount(num_triangles);
			int offset = 0;
			triangles.getInputList().push_back(COLLADASW::Input(COLLADASW::InputSemantic::VERTEX,"#" + mesh_id + COLLADASW::LibraryGeometries::VERTICES_ID_SUFFIX, offset++ ) );
			if (has_normals) {
				triangles.getInputList().push_back(COLLADASW::Input(COLLADASW::InputSemantic::NORMAL,"#" + mesh_id + COLLADASW::LibraryGeometries::NORMALS_SOURCE_ID_SUFFIX, offset++ ) );
			}
			triangles.prepareToAppendValues();
			for (std::vector<int>::const_iterator jt = index_range_start; jt != it; ++jt) {
				const int idx = *jt;
				if (has_normals) {
					triangles.appendValues(idx, idx);
				} else {
					triangles.appendValues(idx);
				}
			}
			triangles.finish();
			index_range_start = it;
		}
		previous_material_id = current_material_id;
		if (it == indices.end()) {
			break;
		}
	}

	closeMesh();
	closeGeometry();
}
예제 #12
0
vector<Triangle> getTriangles(p2t::CDT &cdt, double z)
{
  vector<p2t::Triangle*> ptriangles = cdt.GetTriangles();
  vector<Triangle> triangles(ptriangles.size());
  for (guint i=0; i < ptriangles.size(); i++) {
    triangles[i] = getTriangle(ptriangles[i], z);
  }
  return triangles;
}
예제 #13
0
파일: surface.cpp 프로젝트: A1kmm/libzinc
void Surface::tessellate()
{
	TopLoc_Location loc;
	Handle_Poly_Triangulation triangulation = BRep_Tool::Triangulation( m_face, loc );
	if ( triangulation.IsNull() )
	{
		return;
	}
	int num_triangles = triangulation->NbTriangles();

	const TColgp_Array1OfPnt& nodes = triangulation->Nodes();
	const Poly_Array1OfTriangle& triangles = triangulation->Triangles();
	const TColgp_Array1OfPnt2d& uvNodes = triangulation->UVNodes();
	m_surfaceUVRep.resize( 2 * 3 * num_triangles );
	m_surfacePointIndecies.resize( 3 * num_triangles );
	Standard_Integer n1, n2, n3 = 0;
	Standard_Integer num_invalid_triangles = 0;
	Standard_Integer current_triangle = 0;
	for ( Standard_Integer i = 0; i < num_triangles; i++ )
	{
		Poly_Triangle triangle = triangles( i + 1 );
		bool face_reversed = (m_face.Orientation() == TopAbs_REVERSED);

		if ( face_reversed )
			triangle.Get( n1, n3, n2 );
		else
			triangle.Get( n1, n2, n3 );

		if (triangleIsValid(nodes(n1), nodes(n2), nodes(n3)))
		{
			gp_Pnt2d uv1 = uvNodes.Value(n1);
			gp_Pnt2d uv2 = uvNodes.Value(n2);
			gp_Pnt2d uv3 = uvNodes.Value(n3);

			m_surfacePointIndecies.push_back( 3 * current_triangle + 0 );
			m_surfaceUVRep[ 6 * current_triangle + 0 ] = uv1.X();
			m_surfaceUVRep[ 6 * current_triangle + 1 ] = uv1.Y();
			m_surfacePointIndecies.push_back( 3 * current_triangle + 1 );
			m_surfaceUVRep[ 6 * current_triangle + 2 ] = uv2.X();
			m_surfaceUVRep[ 6 * current_triangle + 3 ] = uv2.Y();
			m_surfacePointIndecies.push_back( 3 * current_triangle + 2 );
			m_surfaceUVRep[ 6 * current_triangle + 4 ] = uv3.X();
			m_surfaceUVRep[ 6 * current_triangle + 5 ] = uv3.Y();

			current_triangle++;
		}
		else
		{
			num_invalid_triangles++;
		}
	}
	if (num_invalid_triangles > 0)
	{
		m_surfaceUVRep.resize(2 * 3 * (num_triangles - num_invalid_triangles));
	}
}
예제 #14
0
/* A simple drawing function, using the default viewport */
void draw_single()
{
  glScissor(0, 0, window_w, window_h);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  triangles();
  extras();
  objects();
  text();
  glFlush();
}
예제 #15
0
Ref<TriangleSoup> PolygonSoup::triangle_mesh() const {
  if (!triangle_mesh_) {
    Array<Vector<int,3> > triangles(half_edge_count-2*counts.size());
    int offset=0, t=0;
    for (int p=0;p<counts.size();p++) {
      for (int i=0;i<counts[p]-2;i++)
        triangles[t++].set(vertices[offset],vertices[offset+i+1],vertices[offset+i+2]);
      offset+=counts[p];
    }
    triangle_mesh_ = new_<TriangleSoup>(triangles,nodes());
  }
  return ref(triangle_mesh_);
}
//#####################################################################
// Function Generate_Triangles
//#####################################################################
template<class T> TRIANGULATED_SURFACE<T>* Generate_Triangles(const SPHERE<VECTOR<T,3> >& sphere,int levels)
{
    typedef VECTOR<T,3> TV;
    TRIANGULATED_SURFACE<T>* surface=TRIANGULATED_SURFACE<T>::Create();
    GEOMETRY_PARTICLES<TV>& particles=surface->particles;particles.array_collection->Add_Elements(6);
    particles.X(1)=TV(-1,0,0);particles.X(2)=TV(1,0,0);particles.X(3)=TV(0,-1,0);
    particles.X(4)=TV(0,1,0);particles.X(5)=TV(0,0,-1);particles.X(6)=TV(0,0,1);
    ARRAY<VECTOR<int,3> >& triangles=surface->mesh.elements;triangles.Exact_Resize(8);
    triangles(1).Set(1,6,4);triangles(2).Set(1,3,6);triangles(3).Set(6,2,4);triangles(4).Set(6,3,2);
    triangles(5).Set(5,1,4);triangles(6).Set(5,3,1);triangles(7).Set(2,3,5);triangles(8).Set(2,5,4);
    surface->mesh.number_nodes=6;
    surface->mesh.Initialize_Neighbor_Nodes();
    for(int i=1;i<=levels;i++) surface->Root_Three_Subdivide();
    for(int p=1;p<=particles.array_collection->Size();p++) particles.X(p)=sphere.center+sphere.radius*particles.X(p).Normalized();
    return surface;
}
double ClusteringCoefficient::exactGlobal(Graph& G) {
	count z = G.upperNodeIdBound();
	std::vector<count> triangles(z); // triangles including node u (every triangle is counted six times)

	std::vector<std::vector<bool> > nodeMarker(omp_get_max_threads());
	for (auto &nm : nodeMarker) {
		nm.resize(z, false);
	}

	G.balancedParallelForNodes([&](node u){

		size_t tid = omp_get_thread_num();
		count tr = 0;

		if (G.degree(u) > 1) {
			G.forEdgesOf(u, [&](node u, node v) {
				nodeMarker[tid][v] = true;
			});

			G.forEdgesOf(u, [&](node u, node v) {
				G.forEdgesOf(v, [&](node v, node w) {
					if (nodeMarker[tid][w]) {
						tr += 1;
					}
				});
			});

			G.forEdgesOf(u, [&](node u, node v) {
				nodeMarker[tid][v] = false;
			});
		}

		triangles[u] = tr;
	});

  double denominator = G.parallelSumForNodes([&](node u){
		return G.degree(u) * (G.degree(u) - 1);
	});

	double cc = G.parallelSumForNodes([&](node u){
		return triangles[u];
	});

	cc /= denominator;

	return cc;
}
PointOnFacesProjector::Result PointOnFacesProjector::projected(const gp_Pnt& point) const
{
  // Find the closest node in the triangulations
  internal::NodeBndBoxSelector selector(point);
  if (d->m_ubTree.Select(selector) <= 0)
    return PointOnFacesProjector::Result();

  const int minNodeId = selector.minDistanceNodeIndex().first;
  const Handle_Poly_Triangulation& triangulation = selector.minDistanceNodeIndex().second;

  // Find the triangle where distance is minimum
  const TColgp_Array1OfPnt& nodes = triangulation->Nodes();
  const Poly_Array1OfTriangle& triangles = triangulation->Triangles();
  double minDist = std::numeric_limits<double>::max();
  const Poly_Triangle* minTriangle = NULL;
  gp_Pnt projectedPnt;
  for (int iTri = triangles.Lower(); iTri <= triangles.Upper(); iTri++) {
    const Poly_Triangle& t = triangles(iTri);
    int n1, n2, n3;
    t.Get(n1, n2, n3);
    if (minNodeId == n1 || minNodeId == n2 || minNodeId == n3) {
      const std::pair<gp_Pnt, bool> projPntInfo = math::projectPointOnTriangle(point,
                                                                               nodes(t(1)),
                                                                               nodes(t(2)),
                                                                               nodes(t(3)));
      const double dist = point.SquareDistance(projPntInfo.first);
      if (dist < minDist) {
        minTriangle = &t;
        minDist = dist;
        projectedPnt = projPntInfo.first;
      }
    }
  }

  if (minTriangle != NULL) {
    const TopoDS_Face* face = d->triangulationToFace(triangulation);
    const TopAbs_Orientation faceOrientation = face != NULL ? face->Orientation() : TopAbs_FORWARD;
    const gp_Vec triNormal = occ::MathTools::triangleNormal(nodes, *minTriangle, faceOrientation);
    return PointOnFacesProjector::Result(face != NULL ? *face : TopoDS_Face(),
                                         projectedPnt,
                                         triNormal);
  }
  return PointOnFacesProjector::Result();
}
예제 #19
0
void ParallelogramLight::set(const QVector3D &origin, const QVector3D &u, const QVector3D &v)
{
    QVector3D p0 = origin,
            p1 = origin + u,
            p2 = origin + v,
            p3 = origin + u + v,
            n = QVector3D::crossProduct(u, v).normalized();

    Vertex* v0 = new Vertex(p0, n);
    Vertex* v1 = new Vertex(p1, n);
    Vertex* v2 = new Vertex(p2, n);
    Vertex* v3 = new Vertex(p3, n);

    Triangle* t0 = new Triangle(v0, v1, v3);
    Triangle* t1 = new Triangle(v0, v3, v2);

    QVector<Triangle*> triangles(2);
    triangles[0] = t0;
    triangles[1] = t1;
    setTriangles(triangles);
}
예제 #20
0
Shape* constructShapeFromMsg(const shape_msgs::Mesh &shape_msg)
{      
  if (shape_msg.triangles.empty() || shape_msg.vertices.empty())
  {
    logWarn("Mesh definition is empty");
    return NULL;
  }
  else
  {
    EigenSTL::vector_Vector3d vertices(shape_msg.vertices.size());
    std::vector<unsigned int> triangles(shape_msg.triangles.size() * 3);
    for (unsigned int i = 0 ; i < shape_msg.vertices.size() ; ++i)
      vertices[i] = Eigen::Vector3d(shape_msg.vertices[i].x, shape_msg.vertices[i].y, shape_msg.vertices[i].z);
    for (unsigned int i = 0 ; i < shape_msg.triangles.size() ; ++i)
    {
      unsigned int i3 = i * 3;
      triangles[i3++] = shape_msg.triangles[i].vertex_indices[0];
      triangles[i3++] = shape_msg.triangles[i].vertex_indices[1];
      triangles[i3] = shape_msg.triangles[i].vertex_indices[2];
    }
    return createMeshFromVertices(vertices, triangles);
  }
}
예제 #21
0
Triangles & KeyFace::triangles()
{
    return triangles(time());
}
예제 #22
0
int main(int argc, char** argv) {
	if(argc != 2) {
		std::cerr<<"Invalid number of inputs. Enter a scene to load\n";
		return -1;
	}

	std::cout<<"Divide and Conquer Ray Tracing - GPU Version 2.0\n";
	std::cout<<"Using Thrust Major Version : "<<THRUST_MAJOR_VERSION<<" ; Thrust Minor Version : "<<THRUST_MINOR_VERSION<<"\n";
	
	// load the ini file to get stuff
	std::cout<<"Reading Ini File\n";
	IniFile ifile;
	ifile.parseIniFile("dacrt.ini");
	ifile.printValues();
	DacrtRunTimeParameters rtparams;
	if(ifile.rtparams_set) {
		rtparams.BUFFER_SIZE = ifile.buffer_size; rtparams.MAX_SEGMENTS = ifile.max_segments; rtparams.MAX_SEGMENT_THRESHOLD = ifile.max_segment_threshold;
		rtparams.NUM_RAYS_PER_BLOCK = ifile.num_rays_per_block; rtparams.PARALLEL_RAY_THRESHOLD = ifile.parallel_ray_threshold; rtparams.PARALLEL_TRI_THRESHOLD = ifile.parallel_tri_threshold;
		rtparams.TRI_SHARED_MEMORY_SPACE = ifile.shared_memory_tri_space;
		rtparams.GRID_DIM_X = ifile.grid_dim_x; rtparams.GRID_DIM_Y = ifile.grid_dim_y; rtparams.GRID_DIM_Z = ifile.grid_dim_z;
	}

	Cuda::printCudaDevices();
	
	Model* m = new Model(argv[1], ifile.data_layout);
	m->printStats();
	Scene* myscene = NULL;
	Renderer* renderer =  NULL;

	if(ifile.data_layout == "soa") {
		TriangleArray triangles(m->triangles[0], m->triangles[1], m->triangles[2]);
		
		// add the transform code here
		float angle = 15.0f;
		Transform roty = rotateY(angle);
		size_t NUM_FRAMES = (size_t)360.0f/angle;

#ifdef _MSC_VER
	std::string filename = "output";
	std::string aofilename = "aoutput";
	//std::string logdir = ".\\logs\\";
#else
	std::string filename = "./output";
	//std::string logdir = "./logs/";
#endif
		std::string filetype = ".jpg";
		std::string logfile = ".csv";


		for(size_t i = 0; i < 1; i++) {

			myscene = new Scene(triangles, m->num_faces, ifile.data_layout, ifile.morton_tris);
			if(!ifile.look_at_set) { 
				myscene->setCameraParams(ifile.eye_pt, ifile.width, ifile.height);
			} else {
				myscene->setCameraParams(ifile.eye_pt, ifile.look_at, ifile.width, ifile.height);
			}
			myscene->initScene(ifile.gpu_setup);

			// Create the output file
			std::stringstream fileno;
			fileno << i;
			std::string finalname = filename + fileno.str() + filetype;
			std::string aofinalname = aofilename + fileno.str() + filetype;
			//std::string logname = logdir + fileno.str() + logfile;

			// Runtime parameters for dacrt algorithm
			if(!ifile.rtparams_set) {
				//renderer = new Renderer(myscene, ifile.data_layout, ifile.outputFileName.c_str(), ifile.morton_rays, ifile.shadow, ifile.secondary_rays, ifile.point_light, false, false);		// setting secondary by default to false
				renderer = new Renderer(myscene, ifile.data_layout, finalname.c_str(), aofinalname.c_str(), ifile.morton_rays, ifile.shadow, ifile.secondary_rays, ifile.point_light, false, false);		// setting secondary by default to false
			} else {
				//renderer = new Renderer(myscene, ifile.data_layout, ifile.outputFileName.c_str(), ifile.morton_rays, ifile.shadow, ifile.secondary_rays, rtparams, ifile.point_light, ifile.gpu_setup);
				renderer = new Renderer(myscene, ifile.data_layout, finalname.c_str(), aofinalname.c_str(), ifile.morton_rays, ifile.shadow, ifile.secondary_rays, rtparams, ifile.point_light, ifile.gpu_setup);
			}

			if(ifile.samples) {
				renderer->render((Method)ifile.primary_ray_method, (Method)ifile.shadow_ray_method, (Method)ifile.secondary_ray_method, 1, 1, ifile.num_samples);
			} else {
				std::cout<<"No Samples set. Setting default value of 1\n";
				renderer->render((Method)ifile.primary_ray_method, (Method)ifile.shadow_ray_method, (Method)ifile.secondary_ray_method, 1, 1, 1);
			}

			// rotate eye point
			ifile.eye_pt = roty(ifile.eye_pt);

			// free up memory here
			if(myscene != NULL) delete myscene;
			if(renderer != NULL) delete renderer;
			//if(m != NULL) delete m;
		}


	} else if(ifile.data_layout == "aos") {

		TriangleArrayAos triangles(m->triangles_aos);
		myscene = new Scene(triangles, m->num_faces, ifile.data_layout, ifile.morton_tris);
		myscene->setCameraParams(ifile.eye_pt, ifile.width, ifile.height);
		myscene->initScene();
		renderer = new Renderer(myscene, ifile.data_layout, ifile.outputFileName.c_str(), NULL, ifile.morton_rays, ifile.shadow, false, ifile.point_light);
		renderer->render((Method)ifile.primary_ray_method, (Method)ifile.shadow_ray_method, (Method)ifile.secondary_ray_method);
	} else {
		std::cerr<<"SEVERE : Invalid data type!!\nExiting\n";
		exit(-1);
	}
	
	//if(myscene != NULL) delete myscene;
	//if(renderer != NULL) delete renderer;
	if(m != NULL) delete m;

#ifdef _WIN32
	_CrtDumpMemoryLeaks();
#endif

	return 0;
}
예제 #23
0
/*
n: number of side subdivisions
n=2 -> 4 triangles,  2 sampling levels
n=3 -> 9 triangles
n=4 -> 16 triangles, 3 sampling levels
*/
std::vector<Triangle> getTrianglesForOctant(const int n) {
	glm::vec3 v0 = glm::vec3(1, 0, 0);
	glm::vec3 v1 = glm::vec3(0, 1, 0);
	glm::vec3 v2 = glm::vec3(0, 0, 1);
	

	glm::vec3 v0v1 = v1 - v0;
	glm::vec3 v0v2 = v2 - v0;
	glm::vec3 v1v2 = v2 - v1;
	
	glm::vec3 planenormal = glm::cross(v0v1, v0v2);
	printf("%2.3f %2.3f %2.3f \n", planenormal.x, planenormal.y, planenormal.z);
	float incr = 1.0/n;

	/*
	std::vector<float> subdiv;	
	for (int i = 0; i < n; ++i) {
		subdiv.push_back( i*incr );
	}
	
	std::vector<glm::vec2> v0v1_subdiv;
	std::vector<glm::vec2> v0v2_subdiv;
	std::vector<glm::vec2> v1v2_subdiv;
	
	for (int i = 1; i < n; ++i) {
		v0v1_subdiv.push_back( v0 + v0v1 * subdiv[i] );
		v0v2_subdiv.push_back( v0 + v0v2 * subdiv[i] );
		v1v2_subdiv.push_back( v1 + v1v2 * subdiv[i] );
	}

	std::vector<glm::vec2> lines;
	lines.push_back(v0v1);
	lines.push_back(v0v2);
	lines.push_back(v1v2);
	for (int i = 0; i < n-1; ++i) {
		//v0v1 parallels
		lines.push_back( v1v2_subdiv[i] - v0v2_subdiv[i] );

		//v0v2 parallels
		lines.push_back( v1v2_subdiv[i] - v0v1_subdiv[i] );

		//v1v2 parallels
		lines.push_back( v0v2_subdiv[i] - v0v1_subdiv[i] );
	}
	*/
	
	const int nsquare = n*n;
	std::vector<Triangle> triangles(nsquare);
	
	int triangles_per_row = n;
	
	int triangleId = 0;

	for (int i = 0; i < n; ++i) { // rows
		glm::vec3 rowBottomLeftOffset = v0 + v0v1 * (incr * i);
		glm::vec3 rowTopLeftOffset = v0 + v0v1 * (incr * (i+1));

		for (int j = 0; j < triangles_per_row;   ++j) { //triangles per row, pointing up (es: 0, 2, 4, 6)
			 
			glm::vec3 triv0 = rowBottomLeftOffset + v0v2 * (incr * j);
			glm::vec3 triv1 = rowTopLeftOffset + v0v2 * (incr*j);
			glm::vec3 triv2 = rowBottomLeftOffset + v0v2 * (incr * (j + 1));
				
			triangles[triangleId] = Triangle(triv0, triv1, triv2);
			triangleId += 2;
		}
		triangleId = triangleId -(2*triangles_per_row) + 1;
		for (int j = 0; j < triangles_per_row-1; ++j) { //triangles per row, pointing down (es: 1, 3, 5)

			glm::vec3 triv0 = triangles[triangleId-1].v[1];
			glm::vec3 triv1 = triangles[triangleId+1].v[1];
			glm::vec3 triv2 = triangles[triangleId-1].v[2];			
			
			triangles[triangleId] = Triangle(triv0, triv1, triv2);			
			triangleId += 2;
		}
		--triangles_per_row;		
	}
	
	for (int i = 0; i < triangles.size(); ++i) {
			auto t = triangles[i];
			printf("%d v0(%1.2f, %1.2f, %1.2f) v1(%1.2f, %1.2f, %1.2f) v2(%1.2f, %1.2f, %1.2f) c(%1.2f, %1.2f, %1.2f)\n\n", 
			  i,
			  t.v[0].x, t.v[0].y, t.v[0].z,
			  t.v[1].x, t.v[1].y, t.v[1].z,
			  t.v[2].x, t.v[2].y, t.v[2].z,
			  t.centroid.x, t.centroid.y, t.centroid.z);
	}

	return triangles;
}
    void operator()(MeshType const & input_mesh,
                    MeshType const & output_mesh,
                    viennagrid_plc plc_output_mesh,
                    PointType const & N)
    {
      typedef viennagrid::result_of::const_element_range<MeshType>::type ConstElementRangeType;
      typedef viennagrid::result_of::iterator<ConstElementRangeType>::type ConstElementRangeIterator;

      viennagrid::result_of::element_copy_map<>::type copy_map(output_mesh, false);

      ConstElementRangeType triangles( input_mesh, 2 );
      for (ConstElementRangeIterator tit = triangles.begin(); tit != triangles.end(); ++tit)
      {
        ElementType v[3];
        PointType p[3];
        double dp[3];

        for (int pi = 0; pi != 3; ++pi)
        {
          v[pi] = viennagrid::vertices(*tit)[pi];
          p[pi] = viennagrid::get_point( v[pi] );

          dp[pi] = viennagrid::inner_prod( p[pi], N );
        }

        if ( !inside(dp[0]) && !inside(dp[1]) && !inside(dp[2]) )
        {
          // all points outside -> ignore
          continue;
        }

        int on_plane_count = 0;
        for (int pi = 0; pi != 3; ++pi)
          if ( on_plane(dp[pi]) )
            ++on_plane_count;

        if (on_plane_count == 3)
          continue;

        if (on_plane_count == 2)
        {
//           std::cout << "!!!!!!!!!!!!!!!!!!!!!!!!  on_plane_count = 2" << std::endl;
          int not_on_plane_index = !on_plane(dp[0]) ? 0 : !on_plane(dp[1]) ? 1 : 2;
          if ( inside(dp[not_on_plane_index]) )
          {
            copy_map(*tit);

            int oi0 = (not_on_plane_index == 0) ? 1 : 0;
            int oi1 = (not_on_plane_index == 2) ? 1 : 2;

            add_line(copy_map(v[oi0]), copy_map(v[oi1]));
          }
//           else
//             std::cout << "   outside -> skipping" << std::endl;
          continue;
        }

        if (on_plane_count == 1)
        {
//           std::cout << "!!!!!!!!!!!!!!!!!!!!!!!!  on_plane_count = 1" << std::endl;
          int on_plane_index = on_plane(dp[0]) ? 0 : on_plane(dp[1]) ? 1 : 2;
          int oi0 = (on_plane_index == 0) ? 1 : 0;
          int oi1 = (on_plane_index == 2) ? 1 : 2;

          if ( !inside(dp[oi0]) && !inside(dp[oi1]) )
            continue;

          if ( inside(dp[oi0]) && inside(dp[oi1]) )
          {
            copy_map(*tit);
            continue;
          }

          // oi0 is inside
          if ( !inside(dp[oi0]) )
            std::swap(oi0, oi1);

          ElementType v_ = get_vertex(output_mesh, N, v[oi0], v[oi1]);
          viennagrid::make_triangle( output_mesh, copy_map(v[on_plane_index]), copy_map(v[oi0]), v_);

          add_line(v_, copy_map(v[on_plane_index]));
          continue;
        }


        if ( inside(dp[0]) && inside(dp[1]) && inside(dp[2])  )
        {
          // all points inside -> copy
          copy_map(*tit);
          continue;
        }

        int pos_count = 0;
        for (int pi = 0; pi != 3; ++pi)
          if ( inside(dp[pi]) )
            ++pos_count;

        int pi = (dp[0]*dp[1] > 0) ? 2 : (dp[1]*dp[2] > 0) ? 0 : 1;
        int oi0 = (pi == 0) ? 1 : 0;
        int oi1 = (pi == 2) ? 1 : 2;

        ElementType v1_ = get_vertex(output_mesh, N, v[pi], v[oi0]);
        ElementType v2_ = get_vertex(output_mesh, N, v[pi], v[oi1]);
        add_line(v1_, v2_);

        if (pos_count == 1)
        {
          viennagrid::make_triangle( output_mesh, copy_map(v[pi]), v1_, v2_);
        }
        else
        {
          viennagrid::make_triangle( output_mesh, copy_map(v[oi0]), copy_map(v[oi1]), v1_);
          viennagrid::make_triangle( output_mesh, copy_map(v[oi1]), v1_, v2_);
        }
      }

      std::vector<viennagrid_int> line_ids;
      std::map<ElementType, viennagrid_int> vertices_on_hyperplane;

      for (LinesOnHyperplaneType::iterator it = lines_on_hyperplane.begin(); it != lines_on_hyperplane.end(); ++it)
      {
        vertices_on_hyperplane.insert( std::make_pair((*it).first, -1) );
        vertices_on_hyperplane.insert( std::make_pair((*it).second, -1) );
      }

      for (std::map<ElementType, viennagrid_int>::iterator vit = vertices_on_hyperplane.begin(); vit != vertices_on_hyperplane.end(); ++vit)
      {
        PointType p = viennagrid::get_point( (*vit).first );
        viennagrid_plc_vertex_create(plc_output_mesh, &p[0], &vit->second);
      }

      for (LinesOnHyperplaneType::iterator it = lines_on_hyperplane.begin(); it != lines_on_hyperplane.end(); ++it)
      {
        viennagrid_int line_id;
        viennagrid_plc_line_create(plc_output_mesh,
                                   vertices_on_hyperplane[(*it).first],
                                   vertices_on_hyperplane[(*it).second],
                                   &line_id);
        line_ids.push_back(line_id);
      }

      viennagrid_plc_facet_create(plc_output_mesh, line_ids.size(), &line_ids[0], NULL);
    }
예제 #25
0
파일: xymatch.c 프로젝트: krzul/dia
/*--------------------------------------------------------*/
int main(int argc, char *argv[])
{
        char    *inp1name, *inp2name, *parfname, *outfname,
                *corrname;
        short   *sat1, *sat2;
        int     i,
                nobj1, nobj2,
                nsub1, nsub2,
                nmatch,
                maxobj,
                *index;
        float   *x1, *y1, *x2, *y2,
                *mag1, *mag2,
                *xs1, *ys1, *xs2, *ys2,
                *xm1, *ym1, *xm2, *ym2,
                coeffx[3], coeffy[3];
        FILE    *outf;
        PARAMS  par;

/* IO stuff */
  if (argc != 6) usage();

  parfname = argv[1];
  inp1name = argv[2];
  inp2name = argv[3];
  outfname = argv[4];
  corrname = argv[5];

  read_params(parfname, &par);

  nobj1=read_objects(inp1name, &x1, &y1, &mag1, &sat1);
  if (par.verbose) printf("%d objects read from %s\n", nobj1, inp1name);
  if (par.nsub > nobj1) par.nsub = nobj1;
  nsub1=bright_end(nobj1, x1, y1, mag1, par.nsub, &xs1, &ys1, par.verbose);

  nobj2=read_objects(inp2name, &x2, &y2, &mag2, &sat2);
  if (par.verbose) printf("%d objects read from %s\n", nobj2, inp2name);
  if (par.nsub > nobj2) par.nsub = nobj2;
  nsub2=bright_end(nobj2, x2, y2, mag2, par.nsub, &xs2, &ys2, par.verbose);

printf("nsub1= %d\n", nsub1);
printf("nsub2= %d\n", nsub2);

  par.nsub=(nsub1 < nsub2 ? nsub1 : nsub2);
  if (par.verbose > 1) printf("par.nsub= %d\n", par.nsub);

  free(mag1);
  free(mag2);

  if (par.verbose > 2)
  {
    printf("Coordinates of the brighest objects:\n");
    printf("  X1    Y1      X2    Y2\n");
    printf("--------------------------\n");
    for (i=0; i<par.nsub; i++)
      printf("%8.2f %8.2f    %8.2f %8.2f\n", xs1[i], ys1[i], xs2[i], ys2[i]);
    printf("--------------------------\n\n");
  }

/* match nsub brightest stars for approximate transformation */
  maxobj=(nobj1 > nobj2 ? nobj1 : nobj2);
  if (par.verbose > 2) printf("maxobj= %d\n", maxobj);

  if (!(index=(int *)calloc(maxobj, sizeof(int)))) errmess("calloc(index)");

  triangles(xs1, ys1, xs2, ys2, par.nsub, par.nsub, index, par);

  if (!(xm1=(float *)malloc(sizeof(float)))) errmess("malloc(xm1)");
  if (!(ym1=(float *)malloc(sizeof(float)))) errmess("malloc(ym1)");
  if (!(xm2=(float *)malloc(sizeof(float)))) errmess("malloc(xm2)");
  if (!(ym2=(float *)malloc(sizeof(float)))) errmess("malloc(ym2)");

  nmatch=0;
  for (i=0; i<par.nsub; i++)
  {
    if (index[i] != -1)
    {
      if (!(xm1=(float *)realloc(xm1, (nmatch+1)*sizeof(float))))
        errmess("realloc(xm1)");
      if (!(ym1=(float *)realloc(ym1, (nmatch+1)*sizeof(float))))
        errmess("realloc(ym1)");
      if (!(xm2=(float *)realloc(xm2, (nmatch+1)*sizeof(float))))
        errmess("realloc(xm2)");
      if (!(ym2=(float *)realloc(ym2, (nmatch+1)*sizeof(float))))
        errmess("realloc(ym2)");

      xm1[nmatch]=xs1[i];
      ym1[nmatch]=ys1[i];
      xm2[nmatch]=xs2[index[i]];
      ym2[nmatch]=ys2[index[i]];
      nmatch++;
    }
  }

  free(xs1);
  free(ys1);
  free(xs2);
  free(ys2);

  if (nmatch < 2)
  {
    printf("ERROR: nmatch < 2\n");
    exit(2);
  }
  if (par.verbose) printf("%d objects matched by triangles()\n", nmatch);

/* linear fit to nmatch stars indentified by triangles */
  xy_lin(xm1, ym1, xm2, ym2, nmatch, coeffx, coeffy);

  free(xm1);
  free(ym1);
  free(xm2);
  free(ym2);

  if (par.verbose > 1)
  {
    printf("Linear transformation data:\n");
    printf("----------------------\n");
    for (i=0; i<3; i++)
      printf("coeffx[%d]= %12g   coeffy[%d]= %12g\n",
        i, coeffx[i], i, coeffy[i]);
    printf("----------------------\n");
  }

  nobj1=reject_saturated(nobj1, &x1, &y1, sat1);
  nobj2=reject_saturated(nobj2, &x2, &y2, sat2);
  if (par.verbose > 1)
  {
    printf("%d objects from %s left after reject_saturated()\n",
      nobj1, inp1name);
    printf("%d objects from %s left after reject_saturated()\n",
      nobj2, inp2name);
  }

  free(sat1);
  free(sat2);

/* using linear fit transform one list and look for close neighbors */
  for (i=0; i<nobj1; i++)
    maxobj=refine(coeffx, coeffy, x1, y1, x2, y2, nobj1, nobj2, index,
      par.ptol);
  if (par.verbose)
  {
    printf("%d objects left in the template list after refine()\n", maxobj);
    printf("Writing matched list to %s\n\n", outfname);
  }

  if (!(outf=fopen(outfname, "w"))) errmess("outfname");
  for (i=0; i<nobj1; i++)
    if (index[i] != -1)
      fprintf(outf, "%9.3f %10.3f %10.3f %10.3f\n",
                    x1[i], y1[i], x2[index[i]], y2[index[i]]);
  fclose(outf);

  free(index);
  free(x1); free(y1);
  free(x2); free(y2);

  if (!(outf=fopen(corrname, "w"))) errmess(corrname);

  fprintf(outf, "%d  %d  %s",
          (int)(coeffx[2]+0.5), (int)(coeffy[2]+0.5), inp2name);

  fclose(outf);

  return(0);
}
예제 #26
0
PcaModel PcaModel::loadStatismoModel(path h5file, PcaModel::ModelType modelType)
{
	logging::Logger logger = Loggers->getLogger("shapemodels");
	PcaModel model;

	// Load the shape or color model from the .h5 file
	string h5GroupType;
	if (modelType == ModelType::SHAPE) {
		h5GroupType = "shape";
	} else if (modelType == ModelType::COLOR) {
		h5GroupType = "color";
	}

	H5::H5File h5Model;

	try {
		h5Model = H5::H5File(h5file.string(), H5F_ACC_RDONLY);
	}
	catch (H5::Exception& e) {
		string errorMessage = "Could not open HDF5 file: " + string(e.getCDetailMsg());
		logger.error(errorMessage);
		throw errorMessage;
	}

	// Load either the shape or texture mean
	string h5Group = "/" + h5GroupType + "/model";
	H5::Group modelReconstructive = h5Model.openGroup(h5Group);

	// Read the mean
	H5::DataSet dsMean = modelReconstructive.openDataSet("./mean");
	hsize_t dims[2];
	dsMean.getSpace().getSimpleExtentDims(dims, NULL);	// dsMean.getSpace() leaks memory... maybe a hdf5 bug, maybe vlenReclaim(...) could be a fix. No idea.
	//H5::DataSpace dsp = dsMean.getSpace();
	//dsp.close();
	Loggers->getLogger("shapemodels").debug("Dimensions of the model mean: " + lexical_cast<string>(dims[0]));
	model.mean = Mat(1, dims[0], CV_32FC1); // Use a row-vector, because of faster memory access and I'm not sure the memory block is allocated contiguously if we have multiple rows.
	dsMean.read(model.mean.ptr<float>(0), H5::PredType::NATIVE_FLOAT);
	model.mean = model.mean.t(); // Transpose it to a col-vector
	dsMean.close();

	// Read the eigenvalues
	dsMean = modelReconstructive.openDataSet("./pcaVariance");
	dsMean.getSpace().getSimpleExtentDims(dims, NULL);
	Loggers->getLogger("shapemodels").debug("Dimensions of the pcaVariance: " + lexical_cast<string>(dims[0]));
	model.eigenvalues = Mat(1, dims[0], CV_32FC1);
	dsMean.read(model.eigenvalues.ptr<float>(0), H5::PredType::NATIVE_FLOAT);
	model.eigenvalues = model.eigenvalues.t();
	dsMean.close();

	// Read the PCA basis matrix
	dsMean = modelReconstructive.openDataSet("./pcaBasis");
	dsMean.getSpace().getSimpleExtentDims(dims, NULL);
	Loggers->getLogger("shapemodels").debug("Dimensions of the PCA basis matrix: " + lexical_cast<string>(dims[0]) + ", " + lexical_cast<string>(dims[1]));
	model.pcaBasis = Mat(dims[0], dims[1], CV_32FC1);
	dsMean.read(model.pcaBasis.ptr<float>(0), H5::PredType::NATIVE_FLOAT);
	dsMean.close();

	modelReconstructive.close(); // close the model-group

	// Read the noise variance (not implemented)
	/*dsMean = modelReconstructive.openDataSet("./noiseVariance");
	float noiseVariance = 10.0f;
	dsMean.read(&noiseVariance, H5::PredType::NATIVE_FLOAT);
	dsMean.close(); */

	// Read the triangle-list
	string representerGroupName = "/" + h5GroupType + "/representer";
	H5::Group representerGroup = h5Model.openGroup(representerGroupName);
	dsMean = representerGroup.openDataSet("./reference-mesh/triangle-list");
	dsMean.getSpace().getSimpleExtentDims(dims, NULL);
	Loggers->getLogger("shapemodels").debug("Dimensions of the triangle-list: " + lexical_cast<string>(dims[0]) + ", " + lexical_cast<string>(dims[1]));
	Mat triangles(dims[0], dims[1], CV_32SC1);
	dsMean.read(triangles.ptr<int>(0), H5::PredType::NATIVE_INT32);
	dsMean.close();
	representerGroup.close();
	model.triangleList.resize(triangles.rows);
	for (unsigned int i = 0; i < model.triangleList.size(); ++i) {
		model.triangleList[i][0] = triangles.at<int>(i, 0);
		model.triangleList[i][1] = triangles.at<int>(i, 1);
		model.triangleList[i][2] = triangles.at<int>(i, 2);
	}

	// Load the landmarks mappings:
	// load the reference-mesh
	representerGroup = h5Model.openGroup(representerGroupName);
	dsMean = representerGroup.openDataSet("./reference-mesh/vertex-coordinates");
	dsMean.getSpace().getSimpleExtentDims(dims, NULL);
	Loggers->getLogger("shapemodels").debug("Dimensions of the reference-mesh vertex-coordinates matrix: " + lexical_cast<string>(dims[0]) + ", " + lexical_cast<string>(dims[1]));
	Mat referenceMesh(dims[0], dims[1], CV_32FC1);
	dsMean.read(referenceMesh.ptr<float>(0), H5::PredType::NATIVE_FLOAT);
	dsMean.close();
	representerGroup.close();

	// convert to 3 vectors with the x, y and z coordinates for easy searching
	vector<float> refx(referenceMesh.col(0).clone());
	vector<float> refy(referenceMesh.col(1).clone());
	vector<float> refz(referenceMesh.col(2).clone());

	// load the landmarks info (mapping name <-> reference (x, y, z)-coords)
	H5::Group landmarksGroup = h5Model.openGroup("/metadata/landmarks");
	dsMean = landmarksGroup.openDataSet("./text");
	
	H5std_string outputString;
	Loggers->getLogger("shapemodels").debug("Reading landmark information from the model.");
	dsMean.read(outputString, dsMean.getStrType());
	dsMean.close();
	landmarksGroup.close();
	vector<string> landmarkLines;
	boost::split(landmarkLines, outputString, boost::is_any_of("\n"), boost::token_compress_on);
	for (const auto& l : landmarkLines) {
		if (l == "") {
			continue;
		}
		vector<string> line;
		boost::split(line, l, boost::is_any_of(" "), boost::token_compress_on);
		string name = line[0];
		int visibility = lexical_cast<int>(line[1]);
		float x = lexical_cast<float>(line[2]);
		float y = lexical_cast<float>(line[3]);
		float z = lexical_cast<float>(line[4]);
		// Find the x, y and z values in the reference
		const auto ivx = std::find(begin(refx), end(refx), x);
		const auto ivy = std::find(begin(refy), end(refy), y);
		const auto ivz = std::find(begin(refz), end(refz), z);
		// TODO Check for .end()!
		const auto vertexIdX = std::distance(begin(refx), ivx);
		const auto vertexIdY = std::distance(begin(refy), ivy);
		const auto vertexIdZ = std::distance(begin(refz), ivz);
		// assert vx=vy=vz
		// Hmm this is not perfect. If there's another vertex where 1 or 2 coords are the same, it fails.
		// We should do the search differently: Find _all_ the vertices that are equal, then take the one that has the right x, y and z.
		model.landmarkVertexMap.insert(make_pair(name, vertexIdX));
	
	}

	h5Model.close();
	return model;
}
예제 #27
0
/**
 * Default version of a function to check if we need any special
 * pipeline stages, or whether prims/verts can go through untouched.
 * Don't test for bypass clipping or vs modes, this function is just
 * about the primitive pipeline stages.
 *
 * This can be overridden by the driver.
 */
boolean
draw_need_pipeline(const struct draw_context *draw,
                   const struct pipe_rasterizer_state *rasterizer,
                   unsigned int prim )
{
   /* If the driver has overridden this, use that version: 
    */
   if (draw->render &&
       draw->render->need_pipeline) 
   {
      return draw->render->need_pipeline( draw->render,
                                          rasterizer,
                                          prim );
   }

   /* Don't have to worry about triangles turning into lines/points
    * and triggering the pipeline, because we have to trigger the
    * pipeline *anyway* if unfilled mode is active.
    */
   if (lines(prim)) 
   {
      /* line stipple */
      if (rasterizer->line_stipple_enable && draw->pipeline.line_stipple)
         return TRUE;

      /* wide lines */
      if (rasterizer->line_width > draw->pipeline.wide_line_threshold)
         return TRUE;

      /* AA lines */
      if (rasterizer->line_smooth && draw->pipeline.aaline)
         return TRUE;
   }

   if (points(prim))
   {
      /* large points */
      if (rasterizer->point_size > draw->pipeline.wide_point_threshold)
         return TRUE;

      /* AA points */
      if (rasterizer->point_smooth && draw->pipeline.aapoint)
         return TRUE;

      /* point sprites */
      if (rasterizer->point_sprite && draw->pipeline.point_sprite)
         return TRUE;
   }


   if (triangles(prim)) 
   {
      /* polygon stipple */
      if (rasterizer->poly_stipple_enable && draw->pipeline.pstipple)
         return TRUE;

      /* unfilled polygons */
      if (rasterizer->fill_cw != PIPE_POLYGON_MODE_FILL ||
          rasterizer->fill_ccw != PIPE_POLYGON_MODE_FILL)
         return TRUE;
      
      /* polygon offset */
      if (rasterizer->offset_cw || rasterizer->offset_ccw)
         return TRUE;

      /* two-side lighting */
      if (rasterizer->light_twoside)
         return TRUE;
   }

   /* polygon cull - this is difficult - hardware can cull just fine
    * most of the time (though sometimes CULL_NEITHER is unsupported.
    * 
    * Generally this isn't a reason to require the pipeline, though.
    *
   if (rasterizer->cull_mode)
      return TRUE;
    */

   return FALSE;
}
예제 #28
0
void ReducedPolyDataReader::computeLevelSet(vtkUnstructuredGrid* m_Grid, vtkPolyData* poly)
{
  // create triangles
  poly->BuildCells();
  QVector<Triangle> triangles(poly->GetNumberOfPolys());
  for (vtkIdType id_poly = 0; id_poly < poly->GetNumberOfPolys(); ++id_poly) {
    vtkIdType Npts, *pts;
    poly->GetCellPoints(id_poly, Npts, pts);
    if (Npts == 3) {
      poly->GetPoint(pts[0], triangles[id_poly].a.data());
      poly->GetPoint(pts[1], triangles[id_poly].b.data());
      poly->GetPoint(pts[2], triangles[id_poly].c.data());
      triangles[id_poly].id_a = pts[0];
      triangles[id_poly].id_b = pts[1];
      triangles[id_poly].id_c = pts[2];
      triangles[id_poly].g1 = triangles[id_poly].b - triangles[id_poly].a;
      triangles[id_poly].g2 = triangles[id_poly].c - triangles[id_poly].a;
      triangles[id_poly].g3 = triangles[id_poly].g1.cross(triangles[id_poly].g2);
      triangles[id_poly].A  = 0.5*triangles[id_poly].g3.abs();
      triangles[id_poly].g3.normalise();
      triangles[id_poly].G.column(0, triangles[id_poly].g1);
      triangles[id_poly].G.column(1, triangles[id_poly].g2);
      triangles[id_poly].G.column(2, triangles[id_poly].g3);
      triangles[id_poly].GI = triangles[id_poly].G.inverse();
      triangles[id_poly].smallest_length = (triangles[id_poly].b - triangles[id_poly].a).abs();
      triangles[id_poly].smallest_length = min(triangles[id_poly].smallest_length, (triangles[id_poly].c - triangles[id_poly].b).abs());
      triangles[id_poly].smallest_length = min(triangles[id_poly].smallest_length, (triangles[id_poly].a - triangles[id_poly].c).abs());
    } else {
      EG_BUG;
    }
  }

  //vtkDoubleArray *scalars = vtkDoubleArray::New();
  EG_VTKSP(vtkDoubleArray, scalars);
  scalars->SetNumberOfComponents(1);
  scalars->SetName("g");
  scalars->Allocate(m_Grid->GetNumberOfPoints());

  QProgressDialog progress("Reducing triangulation", "Abort", 0, m_Grid->GetNumberOfPoints());
  progress.setWindowModality(Qt::ApplicationModal);
  for (vtkIdType id_node = 0; id_node < m_Grid->GetNumberOfPoints(); ++id_node) {
    progress.setValue(id_node);
    QApplication::processEvents();
    if (progress.wasCanceled()) {
      EG_ERR_RETURN("interrupted by user");
    }
    double g_levelset = 1e99;
    vec3_t xp;
    m_Grid->GetPoint(id_node, xp.data());
    foreach (Triangle T, triangles) {
      vec3_t xi(1e99,1e99,1e99);
      vec3_t ri;
      double scal = (xp - T.a)*T.g3;
      vec3_t x1, x2;
      if (scal > 0) {
        x1 = xp + T.g3;
        x2 = xp - scal*T.g3 - T.g3;
      } else {
        x1 = xp - T.g3;
        x2 = xp - scal*T.g3 + T.g3;
      }
      double d = 1e99;

      bool intersects_face = GeometryTools::intersectEdgeAndTriangle(T.a, T.b, T.c, x1, x2, xi, ri);
      if (intersects_face) {
        vec3_t dx = xp - xi;
        d = fabs(dx*T.g3);
      } else {
        double kab = GeometryTools::intersection(T.a, T.b - T.a, xp, T.b - T.a);
        double kac = GeometryTools::intersection(T.a, T.c - T.a, xp, T.c - T.a);
        double kbc = GeometryTools::intersection(T.b, T.c - T.b, xp, T.c - T.b);
        double dab = (T.a + kab*(T.b-T.a) - xp).abs();
        double dac = (T.a + kac*(T.c-T.a) - xp).abs();
        double dbc = (T.b + kbc*(T.c-T.b) - xp).abs();
        bool set = false;
        if ((kab >= 0) && (kab <= 1)) {
          if (dab < d) {
            xi = T.a + kab*(T.b-T.a);
            d = dab;
            set = true;
          }
        }
        if ((kac >= 0) && (kac <= 1)) {
          if (dac < d) {
            xi = T.a + kac*(T.c-T.a);
            d = dac;
            set = true;
          }
        }
        if ((kbc >= 0) && (kbc <= 1)) {
          if (dbc < d) {
            xi = T.b + kbc*(T.c-T.b);
            d = dbc;
            set = true;
          }
        }
        double da = (T.a - xp).abs();
        double db = (T.b - xp).abs();
        double dc = (T.c - xp).abs();
        if (da < d) {
          xi = T.a;
          d = da;
          set = true;
        }
        if (db < d) {
          xi = T.b;
          d = db;
        }
        if (dc < d) {
          xi = T.c;
          d = dc;
          set = true;
        }
        if (!set) {
          EG_BUG;
        }
      }
      if (xi[0] > 1e98) {
        EG_BUG;
      }
      vec3_t dx = xp - xi;
      if (d < fabs(g_levelset)) {
        if (dx*T.g3 > 0) {
          g_levelset = d;
        } else {
          g_levelset = -d;
        }
      }
    }
    scalars->InsertTuple1(id_node, g_levelset);
  }
예제 #29
0
void WorldDownloadManager::extractMeshWorker(kinfu_msgs::KinfuTsdfRequestConstPtr req)
{
  ROS_INFO("kinfu: Extract Mesh Worker started.");

  // prepare with same header
  kinfu_msgs::KinfuTsdfResponsePtr resp(new kinfu_msgs::KinfuTsdfResponse());
  resp->tsdf_header = req->tsdf_header;
  resp->reference_frame_id = m_reference_frame_name;

  ROS_INFO("kinfu: Locking kinfu...");
  if (!lockKinfu())
    return; // shutting down or synchronization error

  ROS_INFO("kinfu: Locked.");
  pcl::PointCloud<pcl::PointXYZI>::Ptr kinfu_cloud = req->request_reset ?
    m_kinfu->extractWorldAndReset() : m_kinfu->extractWorld();

  unlockKinfu();

  Eigen::Affine3f transformation = m_reverse_initial_transformation;

  std::vector<Mesh::Ptr> meshes;

  ROS_INFO("kinfu: Marching cubes...");
  if (!marchingCubes(kinfu_cloud,meshes))
    return; // ERROR

  kinfu_cloud->clear(); // save some memory

  std::vector<PointCloud::Ptr> clouds;
  std::vector<TrianglesPtr> clouds_triangles;

  ROS_INFO("kinfu: Divide triangles and points...");
  for (uint i = 0; i < meshes.size(); i++)
  {
    clouds.push_back(PointCloud::Ptr(new PointCloud()));
    clouds_triangles.push_back(TrianglesPtr(new Triangles()));

    separateMesh(meshes[i],clouds[i],clouds_triangles[i]);
  }
  meshes.clear(); // save some memory

  TrianglesPtr triangles(new Triangles());
  PointCloud::Ptr cloud(new PointCloud());

  ROS_INFO("kinfu: Merging points...");
  mergePointCloudsAndMesh(clouds,cloud,&clouds_triangles,&(*triangles));

  // if needed, transform
  if (req->request_transformation)
  {
    ROS_INFO("kinfu: A custom transformation will be applied.");
    Eigen::Affine3f tr = toEigenAffine(req->transformation_linear,req->transformation_translation);
    transformation = tr * transformation;
  }

  ROS_INFO("kinfu: Applying transformation...");
  pcl::transformPointCloud(*cloud,*cloud,transformation);

  // if needed, crop
  if (req->request_bounding_box)
  {
    ROS_INFO("kinfu: Cropping...");
    TrianglesPtr out_triangles(new Triangles());
    PointCloud::Ptr out_cloud(new PointCloud());
    cropMesh(req->bounding_box_min,req->bounding_box_max,cloud,triangles,out_cloud,out_triangles);
    cloud = out_cloud;
    triangles = out_triangles;
  }

  ROS_INFO("kinfu: Publishing...");
  pclPointCloudToMessage(cloud,resp->point_cloud);
  resp->triangles.swap(*triangles);

  m_pub.publish(resp);
  ROS_INFO("kinfu: Extract Mesh Worker complete.");
}
예제 #30
0
void mgTLData::draw_texture(
	const MGTextureImages& timages
)const{
	const mgTLTriangles& tris=triangles();
	draw_texture(timages,tris.begin(),tris.end());
}