Esempio n. 1
0
	def solve_triangular_faces(self):
		"""Modify the decomposition mesh from polylines to make it a quad mesh by converting the degenerated quad faces that appear as triangular faces.

		"""

		mesh = self.mesh

		for fkey in list(mesh.faces()):
			if len(mesh.face_vertices(fkey)) == 3:

				boundary_vertices = [vkey for vkey in mesh.face_vertices(fkey) if mesh.is_vertex_on_boundary(vkey)]
				case = sum(mesh.is_vertex_on_boundary(vkey) for vkey in mesh.face_vertices(fkey))

				if case == 1:
					#convert triangular face to quad by duplicating the boundary vertex
					#due to compas_singular face vertices at the same location
					u = boundary_vertices[0]
					v = mesh.add_vertex(attr_dict = {attr: xyz for attr, xyz in zip(['x', 'y', 'z'], mesh.vertex_coordinates(u))})

					# modify adjacent faces
					vertex_faces = mesh.vertex_faces(u, ordered = True)
					mesh_substitute_vertex_in_faces(mesh, u, v, vertex_faces[: vertex_faces.index(fkey)])

					# modify triangular face
					mesh_insert_vertex_on_edge(mesh, u, mesh.face_vertex_ancestor(fkey, u), v)

				elif case == 2:
					# remove triangular face and merge the two boundary vertices
					# due to singularities at the same location
					polyline = Polyline(self.decomposition_polyline(*map(lambda x: geometric_key(mesh.vertex_coordinates(x)), boundary_vertices)))
					point = polyline.point(t = .5, snap = True)
					new_vkey = mesh.add_vertex(attr_dict = {'x': point.x, 'y': point.y , 'z': point.z})

					# modify triangular face
					mesh.delete_face(fkey)

					# modify adjacent faces
					for old_vkey in boundary_vertices:
						mesh_substitute_vertex_in_faces(mesh, old_vkey, new_vkey, mesh.vertex_faces(old_vkey))
						mesh.delete_vertex(old_vkey)

		to_move = {}
		# give some length to the new edge
		for edge in mesh.edges():
			threshold = 1e-6
			if mesh.edge_length(*edge) < threshold:
				for vkey in edge:
					xyz = centroid_points([mesh.vertex_coordinates(nbr) for nbr in mesh.vertex_neighbors(vkey)])
					xyz0 = mesh.vertex_coordinates(vkey)
					to_move[vkey] = [0.1 * (a - a0) for a, a0 in zip(xyz, xyz0)]

		for vkey, xyz in to_move.items():
			attr = mesh.vertex[vkey]
			attr['x'] += xyz[0]
			attr['y'] += xyz[1]
			attr['z'] += xyz[2]
Esempio n. 2
0
 def test_data():
     p = Polyline([
         Point(random.random(), random.random(), random.random())
         for i in range(10)
     ])
     assert p.data == p.validate_data()
     o = Polyline.from_data(p.data)
     assert p == o
     assert not (p is o)
     assert o.data == o.validate_data()
Esempio n. 3
0
def test_equality():
    points1 = [[0, 0, x] for x in range(5)]
    polyline1 = Polyline(points1)
    points2 = [[0, 0, x] for x in range(6)]
    polyline2 = Polyline(points2)
    assert polyline1 == polyline1
    assert polyline1 == points1
    assert points1 == polyline1
    assert polyline1 != polyline2
    assert polyline2 != polyline1
    assert polyline1 != points2
    assert points2 != polyline1
    assert polyline1 != 1
Esempio n. 4
0
def select_quad_mesh_strip(mesh, text='key'):
	"""Select quad mesh strip.

	Parameters
	----------
	mesh : QuadMesh, CoarseQuadMesh
		The quad mesh or coarse quad mesh.
	text : str
		Optional argument to show the strip key or density. The key by default.

	Returns
	-------
	hashable
		The strip key.
	"""
	
	n = mesh.number_of_strips()

	# different colors per strip
	strip_to_color = {skey: scale_vector([float(i), 0, n - 1 - float(i)], 255 / (n - 1)) for i, skey in enumerate(mesh.strips())}

	rs.EnableRedraw(False)

	# add strip polylines with colors and arrows
	guids_to_strip = {rs.AddPolyline(mesh.strip_edge_midpoint_polyline(skey)): skey for skey in mesh.strips()}
	for guid, skey in guids_to_strip.items():
		rs.ObjectColor(guid, strip_to_color[skey])
		rs.CurveArrows(guid, arrow_style = 3)

	# show strip key or density
	if text == 'key' or text == 'density':
		if text == 'key':
			guids_to_dot = {guid: rs.AddTextDot(skey, Polyline(mesh.strip_edge_midpoint_polyline(skey)).point(t = .5)) for guid, skey in guids_to_strip.items()}
		elif text == 'density':
			guids_to_dot = {guid: rs.AddTextDot(mesh.get_strip_density(skey), Polyline(mesh.strip_edge_midpoint_polyline(skey)).point(t = .5)) for guid, skey in guids_to_strip.items()}
		for guid, dot in guids_to_dot.items():
			rs.ObjectColor(dot, rs.ObjectColor(guid))

	# return polyline strip
	rs.EnableRedraw(True)
	skey = guids_to_strip.get(rs.GetObject('Get strip.', filter = 4), None)
	rs.EnableRedraw(False)

	# delete objects
	rs.DeleteObjects(guids_to_strip.keys())
	if text == 'key' or text == 'density':
		rs.DeleteObjects(guids_to_dot.values())
	
	return skey
Esempio n. 5
0
def test___getitem__():
    points = [[0, 0, x] for x in range(5)]
    polyline = Polyline(points)
    for x in range(5):
        assert polyline[x] == [0, 0, x]
    with pytest.raises(IndexError):
        polyline[6] = [0, 0, 6]
Esempio n. 6
0
    def to_compas(self):
        """Convert the curve to an equivalent geometry object.

        Returns
        -------
        :class:`compas.geometry.Line`
            If the curve is a line (if it is a linear segment between two points).
        :class:`compas.geometry.Polyline`
            If the curve is a polyline (if it is comprised of multiple line segments).
        :class:`compas.geometry.Circle`
            If the curve is a circle.

        """
        if self.is_line():
            return Line(self.start, self.end)
        if self.is_polyline():
            return Polyline(self.points)
        if self.is_circle():
            success, circle = self.geometry.TryGetCircle()
            if not success:
                raise Exception("not a circle")
            plane = circle.Plane
            center = plane.Origin
            normal = plane.Normal
            radius = circle.Radius
            return Circle([center, normal], radius)
Esempio n. 7
0
    def visualize_on_viewer(self,
                            viewer,
                            visualize_mesh=False,
                            visualize_paths=True):
        """Visualizes slicing result using compas.viewers.

        Parameters
        ----------
        viewer: :class:`compas_view2.app.App`
            An instance of the App viewer class.
        visualize_mesh: bool, optional
            True to visualize mesh, False to not.
        visualize_paths: bool, optional
            True to visualize paths, False to not.
        """

        if visualize_mesh:
            viewer.add(self.mesh, show_points=False, hide_coplanaredges=False)

        if visualize_paths:
            for i, layer in enumerate(self.layers):
                for j, path in enumerate(layer.paths):
                    pts = copy.deepcopy(path.points)
                    if path.is_closed:
                        pts.append(pts[0])
                    polyline = Polyline(pts)
                    viewer.add(polyline,
                               show_points=True,
                               pointcolor=(0, 0, 1),
                               linecolor=(1, 0, 0),
                               linewidth=2)
Esempio n. 8
0
def test___setitem__():
    points = [[0, 0, x] for x in range(5)]
    polyline = Polyline(points)
    point = [1, 1, 4]
    polyline[4] = point
    assert polyline[4] == point
    assert isinstance(polyline[4], Point)
    assert polyline.lines[-1].end == point
Esempio n. 9
0
def add_vertex_edge_for_load_support(network, sup_dic, load_dic, bars_len, key_removed_dic):
    """
    Post-Processing Function:
    Adds vertices and edges in accordance with supports and loads
    returns the cured network
    """
    if not key_removed_dic:
        load_sup_dic=merge_two_dicts(sup_dic, load_dic)
    else:
        load_dic_2=load_dic.copy()
        for key in key_removed_dic:
            load_dic_2.pop(key)
            load_dic_2=merge_two_dicts(load_dic_2, key_removed_dic[key])
        load_sup_dic=merge_two_dicts(sup_dic, load_dic_2)
    # define arbitrary r to be added to get leaf vertex coordinates
    max_len=max(bars_len)
    r=max_len/3.0
    
    # make a polygon and polyline from outer vertices of network
    points = network.to_points()
    cycles = network_find_cycles(network)
    mesh = Mesh.from_vertices_and_faces(points, cycles)

    if 0 in mesh.face and len(mesh.face)>1:
        mesh.delete_face(0)
    if len(mesh.face)==1:  
        ver_lis=[key for key in mesh.vertices()]
    else:
        ver_lis=mesh.vertices_on_boundary(ordered=True)
     
    ver_lis_plyln=ver_lis[:]
    ver_lis_plyln.append(ver_lis[0])
    pt_lis_plygn=[mesh.vertex_coordinates(key) for key in ver_lis]
    pt_lis_plyln=[mesh.vertex_coordinates(key) for key in ver_lis_plyln]
    plygn=Polygon(pt_lis_plygn)
    plyln=Polyline(pt_lis_plyln)

    # add leaf vertices
    for key in load_sup_dic:
        if load_sup_dic[key][0]!=0.0:
            pt_1=add_vectors(network.node_coordinates(key), (+r, 0.0, 0.0))
            plyln_bln=is_point_on_polyline(pt_1, plyln.points, tol=0.001)
            plygn_bln=is_point_in_polygon_xy(pt_1, plygn.points)
            if plyln_bln or plygn_bln:
                pt_1=add_vectors(network.node_coordinates(key), (-r, 0.0, 0.0))
            key_2=network.add_node(x=np.asscalar(pt_1[0]), y=pt_1[1], z=0.0)
            network.add_edge(key, key_2)
        if load_sup_dic[key][1]!=0.0:
            pt_2=add_vectors(network.node_coordinates(key), (0.0,+r, 0.0))
            plyln_bln=is_point_on_polyline(pt_2, plyln.points, tol=0.001)
            plygn_bln=is_point_in_polygon_xy(pt_2, plygn.points)
            if plyln_bln or plygn_bln:
                pt_2=add_vectors(network.node_coordinates(key), (0.0,-r, 0.0))
            key_2=network.add_node(x=pt_2[0], y=np.asscalar(pt_2[1]), z=0.0)
            network.add_edge(key, key_2)
    
    return network, plygn, plyln
def automated_smoothing_constraints(mesh, points = None, curves = None, surface = None, mesh2 = None):
	"""Apply automatically point, curve and surface constraints to the vertices of a mesh to smooth.

	Parameters
	----------
	mesh : Mesh
		The mesh to apply the constraints to for smoothing.
	points : list
		List of XYZ coordinates on which to constrain mesh vertices. Default is None.
	curves : list
		List of Rhino curve guids on which to constrain mesh vertices. Default is None.
	surface : Rhino surface guid
		A Rhino surface guid on which to constrain mesh vertices. Default is None.
	mesh2 : Rhino mesh guid
		A Rhino mesh guid on which to constrain mesh vertices. Default is None.

	Returns
	-------
	constraints : dict
		A dictionary of mesh constraints for smoothing as vertex keys pointing to point, curve or surface objects.

	"""

	if surface:
		surface = RhinoSurface.from_guid(surface)
	if curves:
		curves = [RhinoCurve.from_guid(curve) for curve in curves]
	if mesh2:
		mesh2 = RhinoMesh.from_guid(mesh2)

	constraints = {}
	constrained_vertices = {}

	vertices = list(mesh.vertices())
	vertex_coordinates = [mesh.vertex_coordinates(vkey) for vkey in mesh.vertices()]
	
	if points is not None and len(points) != 0:
		constrained_vertices.update({vertices[closest_point_in_cloud(rs.PointCoordinates(point), vertex_coordinates)[2]]: point for point in points})

	if mesh2 is not None:
		constraints.update({vkey: mesh2.guid for vkey in mesh.vertices()})

	if surface is not None:
		constraints.update({vkey: surface.guid for vkey in mesh.vertices()})
	
	if curves is not None and len(curves) != 0:
		boundaries = [split_boundary for boundary in mesh.boundaries() for split_boundary in list_split(boundary, [boundary.index(vkey) for vkey in constrained_vertices.keys() if vkey in boundary])]
		boundary_midpoints = [Polyline([mesh.vertex_coordinates(vkey) for vkey in boundary]).point(t = .5) for boundary in boundaries]
		curve_midpoints = [rs.EvaluateCurve(curve, rs.CurveParameter(curve, .5)) for curve in curves]
		midpoint_map = {i: closest_point_in_cloud(boundary_midpoint, curve_midpoints)[2] for i, boundary_midpoint in enumerate(boundary_midpoints)}
		constraints.update({vkey: curves[midpoint_map[i]].guid for i, boundary in enumerate(boundaries) for vkey in boundary})
	
	if points is not None:
		constraints.update(constrained_vertices)

	return constraints
Esempio n. 11
0
    def resample_curve_compas(self, length):
        try:
            # rs_poly = rs.AddPolyline(self.polyline.points)
            polyline = Polyline(self.polyline.points)

            if length <= self.polyline.length:
                points = polyline.divide_polyline_by_length(length)
                tangents = [
                    polyline.tangent_at_point_on_polyline(p) for p in points
                ]

                points = [(p.x, p.y, p.z) for p in points]
                tangents = [(t.x, t.y, t.z) for t in tangents]

                return points, tangents

        except Exception:
            print('Interpolated Curve could not be resampled.')
            return None, None
Esempio n. 12
0
def calculate_circle_centre_and_radius_from_three_pts(three_pts_list):
    """
    points is compas Point
    """
    A = three_pts_list[0]
    B = three_pts_list[1]
    C = three_pts_list[2]
    vBA = B - A
    vBC = C - B
    normVec = vBA.cross(vBC)
    midBA = (B + A) / 2
    midBC = (B + C) / 2
    vec_BA = vBA.cross(normVec)
    vec_BC = vBC.cross(normVec)
    poly_0 = Polyline([midBA + vec_BA * 10, midBA - vec_BA * 10])
    poly_1 = Polyline([midBC - vec_BC * 10, midBC + vec_BC * 10])
    centrePt = get_intersection_pts_two_polyline(poly_0, poly_1, touch=True)

    radius = round(centrePt.distance_to_point(B), 3)

    return centrePt, radius
Esempio n. 13
0
def polyline_to_compas(polyline):
    """Convert a Rhino polyline to a COMPAS polyline.

    Parameters
    ----------
    polyline : :class:`Rhino.Geometry.Polyline`

    Returns
    -------
    :class:`compas.geometry.Polyline`
    """
    return Polyline([point_to_compas(point) for point in polyline])
Esempio n. 14
0
    def get_layer_ppts(self, layer, base_boundary):
        """ Creates the PrintPoints of a single layer."""
        max_layer_height = get_param(self.parameters,
                                     key='max_layer_height',
                                     defaults_type='layers')
        min_layer_height = get_param(self.parameters,
                                     key='min_layer_height',
                                     defaults_type='layers')
        avg_layer_height = get_param(self.parameters, 'avg_layer_height',
                                     'layers')

        all_pts = [pt for path in layer.paths for pt in path.points]
        closest_fks, projected_pts = utils.pull_pts_to_mesh_faces(
            self.slicer.mesh, all_pts)
        normals = [
            Vector(*self.slicer.mesh.face_normal(fkey)) for fkey in closest_fks
        ]

        count = 0
        crv_to_check = Path(
            base_boundary.points,
            True)  # creation of fake path for the lower boundary

        layer_ppts = {}
        for i, path in enumerate(layer.paths):
            layer_ppts['path_%d' % i] = []

            for p in path.points:
                cp = closest_point_on_polyline(p,
                                               Polyline(crv_to_check.points))
                d = distance_point_point(cp, p)

                ppt = PrintPoint(pt=p,
                                 layer_height=avg_layer_height,
                                 mesh_normal=normals[count])

                ppt.closest_support_pt = Point(*cp)
                ppt.distance_to_support = d
                ppt.layer_height = max(min(d, max_layer_height),
                                       min_layer_height)
                ppt.up_vector = Vector(
                    *normalize_vector(Vector.from_start_end(cp, p)))
                ppt.frame = ppt.get_frame()

                layer_ppts['path_%d' % i].append(ppt)
                count += 1

            crv_to_check = path

        return layer_ppts
Esempio n. 15
0
 def to_compas(self):
     if self.is_line():
         return Line(self.start, self.end)
     if self.is_polyline():
         return Polyline(self.points)
     if self.is_circle():
         success, circle = self.geometry.TryGetCircle()
         if not success:
             raise Exception("not a circle")
         plane = circle.Plane
         center = plane.Origin
         normal = plane.Normal
         radius = circle.Radius
         return Circle([center, normal], radius)
Esempio n. 16
0
def test_slicer():

    FILE = os.path.join(HERE, '../..', 'data', '3DBenchy.stl')

    # ==============================================================================
    # Get benchy and construct a mesh
    # ==============================================================================

    benchy = Mesh.from_stl(FILE)

    # ==============================================================================
    # Create planes
    # ==============================================================================

    # replace by planes along a curve

    bbox = benchy.bounding_box()

    x, y, z = zip(*bbox)
    zmin, zmax = min(z), max(z)

    normal = Vector(0, 0, 1)
    planes = []
    for i in np.linspace(zmin, zmax, 50):
        plane = Plane(Point(0, 0, i), normal)
        planes.append(plane)

    # ==============================================================================
    # Slice
    # ==============================================================================

    M = benchy.to_vertices_and_faces()

    pointsets = slice_mesh(M, planes)

    # ==============================================================================
    # Process output
    # ==============================================================================

    polylines = []
    for points in pointsets:
        points = [Point(*point) for point in points]
        polyline = Polyline(points)
        polylines.append(polyline)
Esempio n. 17
0
def create_pair_point_list_between_boundaries(pts_list_00, pts_list_01):
    """
    these point list have compas point data
    """
    pts_00 = [pt for pt in pts_list_00]
    pts_01 = [pt for pt in pts_list_01]

    pair_lines = []
    pairs = []
    num = len(pts_00)
    pts_exis_00 = []
    pts_exis_01 = []
    for k in range(num):
        for pt_00 in pts_00:
            skip = []
            for i in range(len(pts_01)):
                closestPt_01 = select_closest_pt_from_list(pt_00, pts_01, skip)
                skip_pts = []
                closest_pt_00_check = select_closest_pt_from_list(closestPt_01, pts_00, skip_pts)
                if closest_pt_00_check == pt_00:
                    closestPt = closestPt_01
                    pts_exis_01.append(closestPt)
                    pts_exis_00.append(pt_00)
                    pair = [pt_00, closestPt]
                    pairs.append(pair)
                    pair_line = Polyline(pair)
                    pair_lines.append(pair_line)
                    break
        id_00 = pts_00.index(pts_exis_00[-1])
        id_01 = pts_01.index(pts_exis_01[-1])
        pts_00.pop(id_00)
        pts_01.pop(id_01)
    ## array lines ##
    pairs_arrayed = []
    pts_00 = [pt for pt in pts_list_00]
    for pt_00 in pts_00:
        for pair in pairs:
            if pt_00 in pair and pair not in pairs_arrayed:
                pairs_arrayed.append(pair)

    return pairs_arrayed, pair_lines
    def visualize_on_viewer(self, viewer, visualize_printpoints):
        """Visualize printpoints on the compas_viewer.

        Parameters
        ----------
        viewer: :class:`compas_view2.app.App`
            An instance of the App viewer class.
        visualize_printpoints: bool
        """
        all_pts = []
        for layer_key in self.printpoints_dict:
            for path_key in self.printpoints_dict[layer_key]:
                for printpoint in self.printpoints_dict[layer_key][path_key]:
                    all_pts.append(printpoint.pt)

        polyline = Polyline(all_pts)
        viewer.add(polyline,
                   show_points=visualize_printpoints,
                   pointcolor=(0, 0, 1),
                   linecolor=(1, 0, 1),
                   linewidth=1)
Esempio n. 19
0
from compas_occ.geometry import OCCNurbsCurve
from compas_view2.app import App

pointsA = [Point(0, 0, 0), Point(3, 6, 0), Point(6, -3, 3), Point(10, 0, 0)]
curveA = OCCNurbsCurve.from_points(pointsA)

curveA.segment(u=0.2, v=0.5)

print(curveA.domain)

pointsB = [Point(0, -1, 0), Point(3, 5, 0), Point(6, -4, 3), Point(10, -1, 0)]
curveB = OCCNurbsCurve.from_points(pointsB)

segment = curveB.segmented(u=0.2, v=0.5)

print(curveB.domain)
print(segment.domain)

# ==============================================================================
# Visualisation
# ==============================================================================

view = App()

view.add(Polyline(curveA.locus()), linewidth=4, linecolor=(1, 0, 0))

view.add(Polyline(curveB.locus()), linewidth=1, linecolor=(0, 0, 0))
view.add(Polyline(segment.locus()), linewidth=4, linecolor=(0, 1, 0))

view.run()
Esempio n. 20
0
def bezier_curve_from_two_vectors(start_end_pts,
                                  start_end_vectors,
                                  resolutionNum=10,
                                  degree=0.5,
                                  is_node=False):
    """
    create a bezier curve points from two vectors on the start point and end point

    direction of the vectors is the same with the flow of the bezier curve points
    """
    ## control points ##
    if is_node:
        flip_vec = 1
    else:
        flip_vec = -1
    distance = start_end_pts[0].distance_to_point(start_end_pts[1])
    start_vector = start_end_vectors[0].unitized()
    start_vector = start_vector * distance * degree * (1)
    end_vector = start_end_vectors[1].unitized()
    end_vector = end_vector * distance * degree * (flip_vec)
    control_pt_0 = start_end_pts[0] + start_vector
    control_pt_1 = start_end_pts[1] + end_vector

    pts = [start_end_pts[0], control_pt_0, control_pt_1, start_end_pts[1]]

    ############################################################################
    bezier_pts = []

    pts_list = []
    for i in range(len(pts) - 2):
        pts_sub = pts[i:3 + i]
        pts_list.append(pts_sub)

    for pts in pts_list:
        lines_second = []
        for j in range(resolutionNum + 1):
            control_linestring = zip(pts[:-1], pts[1:])
            time = j / resolutionNum
            pts_new = []
            for pt1, pt2 in control_linestring:
                pt = pt1 * (1 - time) + pt2 * (time)
                pts_new.append(pt)
            line = Polyline(pts_new)
            lines_second.append(line)

        bezier_pts_sub = []
        control_string = zip(lines_second[:-1], lines_second[1:])
        for line1, line2 in control_string:
            # print("line1 :", line1)
            # print("line2 ;", line2)
            intersecPts = get_intersection_pts_two_polyline(line1,
                                                            line2,
                                                            touch=True)
            bezier_pts_sub.append(intersecPts)

        bezier_pts.append(bezier_pts_sub)
    first_half = bezier_pts[0]
    second_half = bezier_pts[1]
    bezier = []
    number = len(first_half)
    for i in range(number):
        t = (i / (number - 1))
        pt_first_half = first_half[i]
        pt_second_half = second_half[i]
        pt = pt_first_half * (1 - t) + pt_second_half * (t)
        bezier.append(pt)
    bezier.insert(0, start_end_pts[0])
    bezier.append(start_end_pts[1])

    return bezier
Esempio n. 21
0
surface.transform(R * T)

# ==============================================================================
# AABB
# ==============================================================================

box = surface.aabb()

# ==============================================================================
# Visualisation
# ==============================================================================

view = App()

for row in surface.points:
    view.add(Polyline(row),
             show_points=True,
             pointsize=20,
             pointcolor=(1, 0, 0),
             linewidth=2,
             linecolor=(1.0, 0, 0))

for col in zip(*surface.points):
    view.add(Polyline(col), linewidth=2, linecolor=(0, 1.0, 0))

view.add(surface.to_mesh(), show_edges=False)
view.add(box, show_faces=False)

view.run()
Esempio n. 22
0
from compas.geometry import Vector, Point, Plane
from compas.geometry import Polyline
from compas.geometry import Circle
from compas_occ.geometry import OCCNurbsCurve
from compas_view2.app import App

circle = Circle(Plane(Point(0, 0, 0), Vector(0, 0, 1)), 1.0)
curve = OCCNurbsCurve.from_circle(circle)

# ==============================================================================
# Visualisation
# ==============================================================================

view = App()

view.add(Polyline(curve.locus()), linewidth=3)
view.add(Polyline(curve.points),
         show_points=True,
         pointsize=20,
         pointcolor=(1, 0, 0),
         linewidth=1,
         linecolor=(0.3, 0.3, 0.3))

view.run()
Esempio n. 23
0
isolines = igl.groupsort_isolines(vertices, edges)

# ==============================================================================
# Visualisation
# ==============================================================================

viewer = ObjectViewer()

viewer.add(mesh,
           settings={
               'color': '#ffffff',
               'vertices.on': False,
               'edges.on': False
           })

cmap = Colormap(scalars, 'rgb')
for value, paths in isolines:
    for path in paths:
        points = [vertices[path[0][0]]]
        for i, j in path:
            points.append(vertices[j])
        viewer.add(Polyline(points),
                   settings={
                       'edges.color': rgb_to_hex(cmap(value)),
                       'edges.width': 5,
                       'vertices.on': False
                   })

viewer.update()
viewer.show()
Esempio n. 24
0
from compas.geometry import Point
from compas.geometry import Polyline
from compas.geometry import NurbsCurve
from compas.artists import Artist
from compas.colors import Color


points = [Point(0, 0, 0), Point(3, 6, 0), Point(6, -3, 3), Point(10, 0, 0)]

curve = NurbsCurve.from_points(points)

# ==============================================================================
# Visualisation
# ==============================================================================

Artist.clear()

Artist(curve).draw(color=Color.green())
Artist(Polyline(curve.points)).draw(show_points=True)

Artist.redraw()
Esempio n. 25
0
# ==============================================================================
# Compute the intersections
# ==============================================================================

proxy.package = 'compas_cgal.intersections'

pointsets = proxy.intersection_mesh_mesh(A, B)

# ==============================================================================
# Process output
# ==============================================================================

polylines = []
for points in pointsets:
    points = [Point(*point) for point in points]
    polyline = Polyline(points)
    polylines.append(polyline)

# ==============================================================================
# Visualize
# ==============================================================================

meshartist = MeshArtist(None)

meshartist.mesh = Mesh.from_vertices_and_faces(*A)
meshartist.layer = "CGAL::Intersections::A"
meshartist.clear_layer()
meshartist.draw_faces(join_faces=True, color=hex_to_rgb('#222222'))

meshartist.mesh = Mesh.from_vertices_and_faces(*B)
meshartist.layer = "CGAL::Intersections::B"
Esempio n. 26
0
# ==============================================================================
# JSON Data
# ==============================================================================

string = surface.to_jsonstring(pretty=True)

print(string)

other = NurbsSurface.from_jsonstring(string)

# print(surface == other)

# ==============================================================================
# Visualisation
# ==============================================================================

Artist.clear()

u = surface.u_isocurve(0.5 * sum(surface.u_domain))
v = surface.v_isocurve(0.5 * sum(surface.v_domain))

Artist(Polyline(u.locus())).draw()
Artist(Polyline(v.locus())).draw()

# for curve in surface.boundary():
#     Artist(Polyline(curve.locus())).draw()

Artist(other).draw()

Artist.redraw()
Esempio n. 27
0
from compas.geometry import Bezier
from compas.geometry import Point, Polyline, Vector
from compas.geometry import offset_polyline
from compas.utilities import linspace

from compas_plotters import GeometryPlotter

controlpoints = [
    Point(0, 0, 0),
    Point(4, 2.5, 0),
    Point(6, -2.5, 0),
    Point(10, 0, 0)
]
controlpoly = Polyline(controlpoints)

curve = Bezier(controlpoints)
poly = Polyline(curve.locus())
poly1 = Polyline(offset_polyline(poly, +0.15))
poly2 = Polyline(offset_polyline(poly, -0.15))

points = [curve.point(t) for t in linspace(0, 1, 20)]
tangents = [curve.tangent(t) for t in linspace(0, 1, 20)]
normals = [Vector(0, 0, 1).cross(t) for t in tangents]

# ==============================================================================
# Visualization
# ==============================================================================

plotter = GeometryPlotter(figsize=(16, 9))

plotter.add(controlpoly,
Esempio n. 28
0
def fix_boundaries(mesh, polyline_points, t=0):
    polyline = Polyline(polyline_points)
    n = len(mesh.vertices_on_boundary())
    for i, vkey in enumerate(mesh.boundaries()[0]):
        xyz = polyline.point((t + i / n) % 1.0)
        mesh_move_vertex_to(mesh, xyz, vkey)
Esempio n. 29
0
    for j, (u, v) in enumerate(zip(U, V)):
        if i == 0 or i == 5 or j == 0 or j == 8:
            z = 0.0
        elif i < 2 or i > 3:
            z = -1.0
        else:
            if j < 2 or j > 6:
                z = -1.0
            else:
                z = Z
        row.append(Point(u, v, z))
    points.append(row)

surface = NurbsSurface.from_points(points=points)

# ==============================================================================
# Visualisation
# ==============================================================================

Artist.clear()

for row in surface.points:
    Artist(Polyline(row)).draw()

for col in zip(*list(surface.points)):
    Artist(Polyline(col)).draw()

Artist(surface).draw()

Artist.redraw()
Esempio n. 30
0
for line in zip(left_points, right_points):
    left_x = intersection_line_plane(line, left_plane)
    right_x = intersection_line_plane(line, right_plane)

    left_intersections.append(left_x)
    right_intersections.append(right_x)

left_intersections.append(left_intersections[1])
right_intersections.append(right_intersections[1])

left_intersections.append(left_intersections[0])
right_intersections.append(right_intersections[0])

# polylines

left_poly = Polyline(left_intersections)
right_poly = Polyline(right_intersections)

# ==============================================================================
# Export
# ==============================================================================

block.attributes['sides'] = {'left': left, 'right': right}
block.attributes['cut1'] = {'left': left_poly, 'right': right_poly}

block.to_json(FILE_O)

# ==============================================================================
# Visualization
# ==============================================================================