Ejemplo n.º 1
0
def xdraw_frame(frame):
    """Draw frame.
    """
    pt = Point3d(*iter(frame.point))
    xaxis = Vector3d(*iter(frame.xaxis))
    yaxis = Vector3d(*iter(frame.yaxis))
    return Plane(pt, xaxis, yaxis)
Ejemplo n.º 2
0
 def __init__(self):
     self.position = Point3d(random.randint(box.x[0], b_x),
                             random.randint(box.y[0], b_y),
                             random.randint(box.z[0], b_z))
     self.velocity = Vector3d(random.random(), random.random(),
                              random.random())
     self.acceleration = Vector3d(0, 0, 0)
     self.max_speed = 3
     self.max_force = 0.3
     self.trail = []
Ejemplo n.º 3
0
def rhino_volmesh_vertex_lift(volmesh):
    """Rhino wrapper for the vertex lift operation.
    """

    vertex = VolMeshSelector.select_vertex(volmesh)

    vertex_hfkeys = []
    for hfkey in volmesh.vertex_halffaces(vertex):
        if volmesh.is_halfface_on_boundary(hfkey):
            vertex_hfkeys.append(hfkey)

    xyz = volmesh.vertex_coordinates(vertex)
    normal = volmesh.vertex_normal(vertex)

    def OnDynamicDraw(sender, e):
        cp = e.CurrentPoint
        for hfkey in vertex_hfkeys:
            for vertex in volmesh.halfface_vertices(hfkey):
                sp = volmesh.vertex_coordinates(vertex)
                e.Display.DrawLine(Point3d(*sp), cp, black, 2)

    ip = Point3d(*xyz)
    axis = Rhino.Geometry.Line(ip, ip + Vector3d(*normal))
    gp = get_target_point(axis, OnDynamicDraw)

    volmesh_vertex_lift(volmesh, vertex, gp, vertex_hfkeys)

    volmesh.draw()
Ejemplo n.º 4
0
def draw_circles(circles, **kwargs):
    guids = []
    for data in iter(circles):
        point, normal = data['plane']
        radius = data['radius']
        name = data.get('name', '')
        color = data.get('color')
        layer = data.get('layer')
        circle = Circle(Plane(Point3d(*point), Vector3d(*normal)), radius)
        guid = add_circle(circle)
        if not guid:
            continue
        obj = find_object(guid)
        if not obj:
            continue
        attr = obj.Attributes
        if color:
            attr.ObjectColor = FromArgb(*color)
            attr.ColorSource = ColorFromObject
        else:
            attr.ColorSource = ColorFromLayer
        if layer and find_layer_by_fullpath:
            index = find_layer_by_fullpath(layer, True)
            if index >= 0:
                attr.LayerIndex = index
        attr.Name = name
        attr.WireDensity = -1
        obj.CommitChanges()
        guids.append(guid)
    return guids
Ejemplo n.º 5
0
def draw_circles(circles):
    """Draw circles in Grasshopper.

    Parameters
    ----------
    circles : list of dict
        The circle definitions.

    Returns
    -------
    list of :class:`Rhino.Geometry.Circle`

    Notes
    -----
    .. code-block:: python

        Schema({
            'plane': lambda x: len(x[0]) == 3 and len(x[1]) == 3,
            'radius': And(Or(int, float), lambda x: x > 0)
        })

    """
    rg_circles = []
    for c in iter(circles):
        point, normal = c['plane']
        radius = c['radius']
        rg_circles.append(
            Circle(Plane(Point3d(*point), Vector3d(*normal)), radius))
    return rg_circles
Ejemplo n.º 6
0
 def alignment(self, boids, radius=5, angle=10):
     neighbors = self.get_neighbors(boids, radius, angle)
     if len(neighbors) > 0:
         n_neighbors = len(neighbors)
         pox = 0
         poy = 0
         poz = 0
         for i in neighbors:
             pox += i.velocity.X
             poy += i.velocity.Y
             poz += i.velocity.Z
         center = Vector3d(pox / n_neighbors, poy / n_neighbors,
                           poz / n_neighbors)
         return center - self.velocity
     else:
         return Vector3d(0, 0, 0)
Ejemplo n.º 7
0
    def set_values(self, values, boundaries=[]):
        try:
            v = values[0][2]
            self.is_tensor_field = True
        except:
            self.is_tensor_field = False

        pts_count = 0

        if len(values) > 0:
            for z in range(0, self.z_count):
                self.vals.append([])
                for y in range(0, self.y_count):
                    self.vals[z].append([])
                    for x in range(0, self.x_count):
                        if len(boundaries) > 0:
                            inside = False
                            for bou in boundaries:
                                if bou.IsPointInside(self.pts[pts_count],
                                                     global_tolerance,
                                                     True) == True:
                                    self.vals[z][y].append(values[pts_count])
                                    inside = True
                                    break
                            if inside == False:
                                if self.is_tensor_field:
                                    self.vals[z][y].append(Vector3d(0, 0, 0))
                                else:
                                    self.vals[z][y].append(0.0)
                        else:
                            self.vals[z][y].append(values[pts_count])
                        pts_count += 1
Ejemplo n.º 8
0
def draw_circles(circles):
    """Draw circles in Grasshopper.
    """
    rg_circles = []
    for c in iter(circles):
        point, normal = c['plane']
        radius = c['radius']
        rg_circles.append(Circle(Plane(Point3d(*point), Vector3d(*normal)), radius))
    return rg_circles
Ejemplo n.º 9
0
def draw_circles(circles, **kwargs):
    """Draw circles and optionally set individual name, color, and layer properties.

    Parameters
    ----------
    circles : list[dict]
        A list of circle dictionaries.
        See Notes, for more information about the structure of the dict.

    Returns
    -------
    list[System.Guid]

    Notes
    -----
    A circle dict has the following schema:

    .. code-block:: python

        Schema({
            'plane': lambda x: len(x[0]) == 3 and len(x[1]) == 3,
            'radius': And(Or(int, float), lambda x: x > 0),
            Optional('name', default=''): str,
            Optional('color', default=None): And(lambda x: len(x) == 3, all(0 <= y <= 255 for y in x)),
            Optional('layer', default=None): str
        })

    """
    guids = []
    for data in iter(circles):
        point, normal = data['plane']
        radius = data['radius']
        name = data.get('name', '')
        color = data.get('color')
        layer = data.get('layer')
        circle = Circle(Plane(Point3d(*point), Vector3d(*normal)), radius)
        guid = add_circle(circle)
        if not guid:
            continue
        obj = find_object(guid)
        if not obj:
            continue
        attr = obj.Attributes
        if color:
            attr.ObjectColor = FromArgb(*color)
            attr.ColorSource = ColorFromObject
        else:
            attr.ColorSource = ColorFromLayer
        if layer and find_layer_by_fullpath:
            index = find_layer_by_fullpath(layer, True)
            if index >= 0:
                attr.LayerIndex = index
        attr.Name = name
        attr.WireDensity = -1
        obj.CommitChanges()
        guids.append(guid)
    return guids
Ejemplo n.º 10
0
def smartPointProject(smartPoints, brep, vector=Vector3d(0.0,0.0,1.0), tolerance=0.001):
    resultSet = []
    # project everything
    for smartPt in smartPoints:
        result = Rhino.Geometry.Intersect.Intersection.ProjectPointsToBreps([brep],
                [smartPt.geom],
                vector, tolerance)
        if len(result) > 0:
            smartPt.geom = result[0]
            resultSet.append(smartPt)
    return resultSet
Ejemplo n.º 11
0
def vector_to_rhino(vector):
    """Convert a COMPAS vector to a Rhino vector.

    Parameters
    ----------
    vector : :class:`compas.geometry.Vector`

    Returns
    -------
    :class:`Rhino.Geometry.Vector3d`
    """
    return Vector3d(vector[0], vector[1], vector[2])
Ejemplo n.º 12
0
 def align(self, others):
     #generate list of other Boid headings
     headings = [other.heading for other in others]
     #empty vector creation
     uberVector = Vector3d(0.0, 0.0, 0.0)
     #add up all headings
     for heading in headings:
         uberVector = Vector3d.Add(uberVector, heading)
     #remove magnitude from sum of all headings
     uberVector = Vector3d.Divide(uberVector, uberVector.Length)
     #set Boids heading to aligned vector
     self.heading = uberVector
Ejemplo n.º 13
0
    def __init__(self,
                 name,
                 boundaries,
                 pts,
                 count_vec,
                 resolution,
                 values=[]):

        self.name = name
        self.resolution = resolution

        self.boundaries = boundaries
        self.pts = pts
        self.bbox = BoundingBox(pts)

        self.x_count = int(count_vec.X)
        self.y_count = int(count_vec.Y)
        self.z_count = int(count_vec.Z)

        self.vals = []
        pts_count = 0

        self.is_tensor_field = False
        try:
            v = values[0][2]
            self.is_tensor_field = True
        except:
            pass

        if len(values) > 0:
            for z in range(0, self.z_count):
                self.vals.append([])
                for y in range(0, self.y_count):
                    self.vals[z].append([])
                    for x in range(0, self.x_count):
                        if len(self.boundaries) > 0:
                            inside = False
                            for bou in self.boundaries:
                                if bou.IsPointInside(self.pts[pts_count],
                                                     global_tolerance,
                                                     True) == True:
                                    self.vals[z][y].append(values[pts_count])
                                    inside = True
                                    break
                            if inside == False:
                                if self.is_tensor_field:
                                    self.vals[z][y].append(Vector3d(0, 0, 0))
                                else:
                                    self.vals[z][y].append(0.0)
                        else:
                            self.vals[z][y].append(values[pts_count])
                        pts_count += 1
Ejemplo n.º 14
0
def trimesh_slice(mesh, planes):
    """Slice a mesh by a list of planes.

    Parameters
    ----------
    mesh : tuple of vertices and faces
        The mesh to slice.
    planes : list of (point, normal) tuples or compas.geometry.Plane
        The slicing planes.

    Returns
    -------
    list of arrays
        The points defining the slice polylines.

    Examples
    --------
    >>> from compas.geometry import Sphere, Plane, Point, Vector
    >>> sphere = Sphere([1, 1, 1], 1)
    >>> sphere = sphere.to_vertices_and_faces(u=30, v=30)
    >>> P1 = Plane(Point(0, 0, 0), Vector(0, -1, 0))
    >>> P2 = Plane(Point(0, 0, 0), Vector(0.87, -0.5, 0))
    >>> planes = [P1, P2]
    >>> points = trimesh_slice(sphere, planes)

    """
    # (0) see if input is already Rhino.Geometry.Mesh
    M = Rhino.Geometry.Mesh()
    if not isinstance(mesh, Rhino.Geometry.Mesh):
        for x, y, z in mesh[0]:
            M.Vertices.Add(x, y, z)
        for face in mesh[1]:
            M.Faces.AddFace(*face)
    else:
        M = mesh
    # (1) parse to Rhino.Geometry.Plane
    P = []
    for plane in planes:
        point = Point3d(plane[0][0], plane[0][1], plane[0][2])
        normal = Vector3d(plane[1][0], plane[1][1], plane[1][2])
        P.append(Plane(point, normal))
    # (2) Slice
    polylines = MeshPlane(M, P)
    # (3) Return points in a list of arrays
    polyline_pts = []
    for polyline in polylines:
        pts = []
        for i in range(polyline.Count):
            pts.append([polyline.X[i], polyline.Y[i], polyline.Z[i]])
        polyline_pts.append(pts)

    return polyline_pts
Ejemplo n.º 15
0
def contourBrepInZ(brep, stepSize):
    # get the upper and lower limits
    bbox = brep.GetBoundingBox(True)
    zMin, zMax = bbox.Min.Z, bbox.Max.Z
    zRange = zMax-zMin
    vect = Vector3d(0.0,0.0,1.0)
    # the next line is dense
    planes = [Plane(Point3d(0.0, 0.0, z), vect) for z in RangeTools.drange(zMin,zMax, 0.5)]
    resultList = []
    for plane in planes:
        curves = brep.CreateContourCurves(brep, plane)
        resultList.append(curves)
    return resultList
Ejemplo n.º 16
0
    def __init__(self, _plane, _type, _part, _id):

        self.pln = _plane

        flip_pln_Y = Vector3d(self.pln.YAxis)
        flip_pln_Y.Reverse()
        self.flip_pln = Plane(self.pln.Origin, self.pln.XAxis, flip_pln_Y)

        self.type = _type
        self.part = _part
        self.id = _id

        self.rules_table = []
        self.active_rules = []
Ejemplo n.º 17
0
    def fromJSON(cls, filePath):
        with open(filePath, 'r') as file:
            parsed = json.load(file)
            system = cls(Point3d(0, 0, 0))

            for data in parsed['bodies']:
                body = Body(data['name'], data['mass'], data['radius'])
                body.position = Point3d(*data['position'])
                body.velocity = Vector3d(*data['velocity'])
                body.color = Color.FromArgb(*data['color'])
                body.pendown()
                system.add(body)

            return system
Ejemplo n.º 18
0
def _egi_sort_v_nbrs(egi):
    """ By default, the sorting should be ccw, since the circle is typically drawn
    ccw around the local plane's z-axis...
    """
    xyz = dict((key, [attr[_] for _ in 'xyz']) for key, attr in egi.vertices(True))
    for vkey in egi.vertex:
        nbrs    = egi.vertex[vkey]['nbrs']
        plane   = Plane(Point3d(*xyz[vkey]),
                        Vector3d(*[axis for axis in egi.vertex[vkey]['normal']]))
        circle  = Circle(plane, 1)
        p_list  = []
        for nbr_vkey in nbrs:
            boolean, parameter = ArcCurve(circle).ClosestPoint(Point3d(*xyz[nbr_vkey]))
            p_list.append(parameter)
        sorted_nbrs = [key for (param, key) in sorted(zip(p_list, nbrs))]
        egi.vertex[vkey]['sorted_nbrs'] = sorted_nbrs
Ejemplo n.º 19
0
 def separation(self, boids, radius=3, angle=10):
     neighbors = self.get_neighbors(boids, radius, angle)
     pox = 0
     poy = 0
     poz = 0
     if len(neighbors) > 0:
         n_neighbors = len(neighbors)
         for i in neighbors:
             pox += i.position.X
             poy += i.position.Y
             poz += i.position.Z
         center = Point3d(pox / n_neighbors, poy / n_neighbors,
                          poz / n_neighbors)
         return (center - self.position) * -1
     else:
         return Vector3d(0, 0, 0)
Ejemplo n.º 20
0
def interpolatePointsToTerrainMesh(points, terrainMesh):
    out = []
    for pt in points:
        pts = [pt]
        meshes = [terrainMesh]
        vect = Vector3d(0.0,0.0, 1.0)
        tol = 0.001
        intResult = Rhino.Geometry.Intersect.Intersection.ProjectPointsToMeshes(meshes, pts, vect, tol)
        if len(intResult) == 1: # it hit, and just once
            out.append(intResult[0]) # add the result
        elif len(intResult) < 1: # it missed
            # approximate the z value
            line = Rhino.Geometry.Line(pt, vect)
            closPt = terrainMesh.ClosestPoint(pt)
            roughPt = line.ClosestPoint(closPt, False)
            closestTerrain = terrainMesh.ClosestPoint(roughPt)
            roughPt.Z = closestTerrain.Z
            out.append(roughPt)
        else: # it hit twice??!!
            # this appears to happen often.
            out.append(intResult[0]) # use the first intersection anyway
    return out
Ejemplo n.º 21
0
def smartCurveLayerProject(curveLayerName, surfaceLayerName,
        objectAttributes=None, vector=Vector3d(0.0,0.0,1.0),
        tolerance=0.001):
    '''Project a layer contining only curves onto a layer containing a surface,
    and maintain UserString associations between the original and projected curves.
    ObjectAttributes can be passed in to predetermine a layer or other data. Returns
    a list of (Geometry, ObjAttributes) pairs, with user keys set. If anything fails,
    should print an error message and return an empty set.'''
    # get the curves
    objs = scriptcontext.doc.Objects.FindByLayer(curveLayerName)
    if len(objs) == 0:
        print 'No Curves found on that layer'
        return []
    # get the surface(s)
    srfObjs = scriptcontext.doc.Objects.FindByLayer(surfaceLayerName)
    if len(srfObjs) == 0:
        print 'no surfaces found on that layer'
        return []
    else:
        srf = srfObjs[0].Geometry
    # deal with ObjectAttributes
    if objectAttributes:
        att = objectAttributes
    else:
        att = Rhino.DocObjects.ObjectAttributes()
    resultSet = []
    # project everything
    for crvObj in objs:
        smartCurve = SmartFeature(crvObj)
        smartAtt = smartCurve.objAttributes(att)
        projCurves = smartCurve.geom.ProjectToBrep(smartCurve.geom,
                                                srf,
                                                vector,
                                                tolerance)
        for crv in projCurves:
            smartPair = (crv, smartAtt)
            resultSet.append(smartPair)

    return resultSet
Ejemplo n.º 22
0
def RunCommand():
    # select a surface
    srfid = rs.GetObject("select serface",
                         rs.filter.surface | rs.filter.polysurface)
    if not srfid: return
    # get the brep
    brep = rs.coercebrep(srfid)
    if not brep: return

    x = rs.GetReal("value of x", 0)
    y = rs.GetReal("value of y", 0)

    pts = [(abs(point.Z), point.Z)
           for point in Intersect.Intersection.ProjectPointsToBreps(
               [brep], [Point3d(x, y, 0)], Vector3d(
                   0, 0, 1), doc.ModelAbsoluteTolerance)]

    pts.sort(reverse=True)

    if pts == []:
        print "no Z for given X, Y"
    else:
        rs.AddPoint(Point3d(x, y, pts[0][1]))
Ejemplo n.º 23
0
def smartPointLayerProject(pointLayerName, surfaceLayerName,
        objectAttributes=None, vector=Vector3d(0.0,0.0,1.0),
        tolerance=0.001):
    '''Project a layer contining only points onto a layer containing a surface,
    and maintain UserString associations between the original and projected points.
    ObjectAttributes can be passed in to predetermine a layer or other data. Returns
    a list of (Geometry, ObjAttributes) pairs, with user keys set. If anything fails,
    should print an error message and return an empty set.'''
    objs = scriptcontext.doc.Objects.FindByLayer(pointLayerName)
    if len(objs) == 0:
        print 'No Curves found on %s' % pointLayerName
        return []
    # get the surface(s)
    srfObjs = scriptcontext.doc.Objects.FindByLayer(surfaceLayerName)
    if len(srfObjs) == 0:
        print 'No Surfaces found on %s' % surfaceLayerName
        return []
    else:
        srf = srfObjs[0].Geometry
    # deal with ObjectAttributes
    if objectAttributes:
        att = objectAttributes
    else:
        att = Rhino.DocObjects.ObjectAttributes()
    resultSet = []
    # project everything
    for ptObj in objs:
        smartPt = SmartFeature(ptObj)
        smartAtt = smartPt.objAttributes(att)
        projPoints = Rhino.Geometry.Intersect.Intersection.ProjectPointsToBreps([srf],
                [smartPt.geom],
                vector,
                tolerance)
        for pt in projPoints:
            smartPair = (pt, smartAtt)
            resultSet.append(smartPair)
    return resultSet
Ejemplo n.º 24
0
 def __init__(self):
     self.position = Point3d(random.randint(box.x[0], b_x),random.randint(box.y[0], b_y),random.randint(box.z[0], b_z))
     self.velocity = Vector3d(random.random(),random.random(),random.random())
     self.trail = []
Ejemplo n.º 25
0
def rhino_volmesh_pull_halffaces(volmesh, hfkey, uniform=False):

    # # --------------------------------------------------------------------------
    # #  1. display boundary halffaces
    # # --------------------------------------------------------------------------
    # boundary_halffaces = volmesh.halffaces_on_boundaries()

    # volmesh.clear()
    # volmesh.draw_edges()
    # volmesh.draw_faces(faces=boundary_halffaces)

    # rs.EnableRedraw(True)

    # # --------------------------------------------------------------------------
    # #  2. select halfface and its dependents
    # # --------------------------------------------------------------------------
    # hf_inspector = VolmeshHalffaceInspector(volmesh,
    #                                         hfkeys=boundary_halffaces,
    #                                         dependents=True)
    # hf_inspector.enable()

    # hfkey = mesh_select_face(volmesh)

    # hf_inspector.disable()

    # del hf_inspector

    # hf dependent hfs

    dep_hfkeys = volmesh.halfface_manifold_neighborhood(hfkey, ring=50)

    # --------------------------------------------------------------------------
    #  3. move face
    # --------------------------------------------------------------------------
    ckey = volmesh.halfface_cell(hfkey)
    cell_vkeys = volmesh.cell_vertices(ckey)

    hf_vkeys = volmesh.halfface_vertices(hfkey)
    hf_normal = volmesh.halfface_normal(hfkey)
    hf_center = volmesh.halfface_center(hfkey)

    edges = {}
    for u in hf_vkeys:
        u_nbrs = volmesh.vertex_neighbors(u)
        for v in u_nbrs:
            if v in cell_vkeys:
                if v not in hf_vkeys:
                    edges[u] = v

    xyz_dict = {}
    for vkey in cell_vkeys:
        xyz_dict[vkey] = volmesh.vertex_coordinates(vkey)

    if uniform:
        hfkeys = dep_hfkeys + [hfkey]
        target_normal = _halffaces_avg_normals(volmesh, hfkeys)
    else:
        target_normal = None

    # dynamic draw -------------------------------------------------------------

    def OnDynamicDraw(sender, e):
        cp = e.CurrentPoint

        xyz = _volmesh_compute_dependent_face_intersections(
            volmesh, hfkey, cp, target_normal)

        seen = set()

        for fkey in dep_hfkeys + [hfkey]:
            hf_edges = volmesh.halfface_halfedges(fkey)
            for edge in hf_edges:
                u = edge[0]
                v = edge[1]
                pair = frozenset([u, v])
                if pair not in seen:
                    init_u = volmesh.vertex_coordinates(u)
                    init_u_xyz = Point3d(*init_u)
                    u_xyz = Point3d(*xyz[u])
                    v_xyz = Point3d(*xyz[v])
                    e.Display.DrawLine(Line(u_xyz, v_xyz), black, 4)
                    e.Display.DrawArrow(Line(init_u_xyz, u_xyz), arrow_color,
                                        12, 0)
                    # e.Display.DrawDottedLine(init_u_xyz, u_xyz, feedback_color)

                    seen.add(pair)

        for u, v in volmesh.edges_iter():
            if frozenset([u, v]) not in seen:
                sp = volmesh.vertex_coordinates(u)
                ep = volmesh.vertex_coordinates(v)
                if u in xyz:
                    sp = xyz[u]
                if v in xyz:
                    ep = xyz[v]
                e.Display.DrawLine(Line(Point3d(*sp), Point3d(*ep)), black, 2)

    # --------------------------------------------------------------------------
    #  4. new face location
    # --------------------------------------------------------------------------
    ip = Point3d(*hf_center)
    line = Rhino.Geometry.Line(ip, ip + Vector3d(*hf_normal))
    gp = get_target_point(line, OnDynamicDraw)

    # --------------------------------------------------------------------------
    #  5. update halfface and its dependents
    # --------------------------------------------------------------------------
    new_xyz = _volmesh_compute_dependent_face_intersections(
        volmesh, hfkey, gp, target_normal)

    for key in new_xyz:
        coordinates = new_xyz[key]
        volmesh.vertex_update_xyz(key, coordinates, constrained=False)
Ejemplo n.º 26
0
from __future__ import absolute_import
Ejemplo n.º 27
0
def alingBlock(block_a, block_b, model_inside):
    """
    Scale box to the correct dimentions
    Align box a and what is inside to box b
    The dimention of the box is expected to be equal lenght
    :param block_a:
    :param block_b: block to align block_a to
    :param model_inside: models inside block_a
    """

    # Find center of box_a
    exp_a = rs.ExplodePolysurfaces(block_a)
    cen_a = Vector3d(0, 0, 0)
    for exp in exp_a:
        cen_a += rs.SurfaceAreaCentroid(exp)[0]
    cen_a /= 6.0

    # Find center of box_b
    exp_b = rs.ExplodePolysurfaces(block_b)
    cen_b = Vector3d(0, 0, 0)
    for exp in exp_b:
        cen_b += rs.SurfaceAreaCentroid(exp)[0]
    cen_b /= 6.0

    # Find side Lenght
    c = rs.DuplicateEdgeCurves(exp_a[0])
    L = float(rs.CurveLength(c[0]))

    def sqrt_length(a, b, c):
        return math.sqrt(a * a + b * b + c * c)

    def create_matrix(a, b, c, d):
        M = [[a[0], a[1], a[2], d[0]], [b[0], b[1], b[2], d[1]],
             [c[0], c[1], c[2], d[2]], [0, 0, 0, 1]]
        return M

    # find basic function of box_a
    basic_0 = cen_a - rs.SurfaceAreaCentroid(exp_a[0])[0]
    basic_0 /= sqrt_length(basic_0[0], basic_0[1], basic_0[2])

    basic_1 = rs.SurfaceAreaCentroid(exp_a[1])[0] - cen_a
    basic_1 /= sqrt_length(basic_1[0], basic_1[1], basic_1[2])

    basic_2 = cen_a - rs.SurfaceAreaCentroid(exp_a[4])[0]
    basic_2 /= sqrt_length(basic_2[0], basic_2[1], basic_2[2])

    # create tranformation matrix
    M = create_matrix(basic_0, basic_1, basic_2, [0, 0, 0])

    # scale
    rs.ScaleObjects([block_a] + model_inside, cen_a,
                    [200 / L, 200 / L, 200 / L])

    # move to [0,0,0]
    rs.MoveObjects([block_a] + model_inside, -cen_a)

    # rotate
    rs.TransformObjects([block_a] + model_inside, M)

    # move to object
    rs.MoveObjects([block_a] + model_inside, cen_b)

    rs.DeleteObjects(exp_a)
    rs.DeleteObjects(exp_b)

    rs.DeleteObjects(c)
Ejemplo n.º 28
0
def rhino_cell_face_pull(cell):

    # --------------------------------------------------------------------------
    #  1. pick face
    # --------------------------------------------------------------------------
    cell.draw()
    face = mesh_select_face(cell)
    cell_split_indet_face_vertices(cell, face)
    cell.clear()

    # --------------------------------------------------------------------------
    #  2. face data
    # --------------------------------------------------------------------------
    f_normal = cell.face_normal(face)
    f_center = cell.face_center(face)
    f_area = cell.face_area(face)
    f_vkeys = cell.face_vertices(face)

    # --------------------------------------------------------------------------
    #  3. get neighbor edges and vertex coordinates
    # --------------------------------------------------------------------------
    edges = {}
    for u in f_vkeys:
        u_nbrs = cell.vertex_neighbors(u)
        for v in u_nbrs:
            if v not in f_vkeys:
                edges[u] = v

    xyz_dict = {}
    for vkey in cell.vertex:
        if vkey not in f_vkeys:
            xyz_dict[vkey] = cell.vertex_coordinates(vkey)

    # --------------------------------------------------------------------------
    #  4. dynamic draw
    # --------------------------------------------------------------------------
    rs.EnableRedraw(True)

    def OnDynamicDraw(sender, e):

        cp = e.CurrentPoint
        plane = (cp, f_normal)
        new_pt_list = []

        for u in f_vkeys:
            v = edges[u]
            u_xyz = cell.vertex_coordinates(u)
            v_xyz = cell.vertex_coordinates(v)
            line = (u_xyz, v_xyz)
            it = intersection_line_plane(line, plane)
            xyz_dict[u] = it
            new_pt_list.append(it)

            e.Display.DrawDottedLine(Point3d(*u_xyz), Point3d(*it), black)

        for vkey in cell.vertex:
            xyz = cell.vertex_coordinates(vkey)
            e.Display.DrawPoint(Point3d(*xyz), 0, 5, black)

        # old normal and area --------------------------------------------------
        e.Display.DrawDot(Point3d(*f_center), str(round(f_area, 3)), gray,
                          white)

        # draw original face ---------------------------------------------------
        for i in range(-1, len(f_vkeys) - 1):
            vkey1 = f_vkeys[i]
            vkey2 = f_vkeys[i + 1]
            sp = Point3d(*cell.vertex_coordinates(vkey1))
            np = Point3d(*cell.vertex_coordinates(vkey2))

            e.Display.DrawDottedLine(sp, np, black)

        # get current face info ------------------------------------------------
        areas = {}
        normals = {}
        for fkey in cell.faces():
            face_coordinates = [
                xyz_dict[vkey] for vkey in cell.face_vertices(fkey)
            ]
            areas[fkey] = polygon_area_oriented(face_coordinates)
            normals[fkey] = polygon_normal_oriented(face_coordinates)

        # draw new face areas / vectors ----------------------------------------
        for fkey in cell.faces():
            area = areas[fkey]
            normal = normals[fkey]
            value = area / max(areas.values())
            color = i_to_rgb(value)
            color = FromArgb(*color)

            # draw vectors -----------------------------------------------------
            scale = 0.25
            center = datastructure_centroid(cell)
            sp = Point3d(*center)
            vector = scale_vector(normal, area * scale)
            ep = Point3d(*add_vectors(center, vector))

            e.Display.DrawArrow(Line(sp, ep), color, 20, 0)

            # draw face --------------------------------------------------------
            face_coordinates = [
                xyz_dict[vkey] for vkey in cell.face_vertices(fkey)
            ]
            face_coordinates.append(face_coordinates[0])
            polygon_xyz = [Point3d(*xyz) for xyz in face_coordinates]

            e.Display.DrawPolyline(polygon_xyz, black, 2)

            if fkey == face:
                e.Display.DrawPolyline(polygon_xyz, black, 4)
                e.Display.DrawPolygon(polygon_xyz, color, filled=True)

            # display force magnitudes -----------------------------------------
            vector = add_vectors(vector,
                                 scale_vector(normalize_vector(normal), 0.75))
            xyz = add_vectors(center, vector)
            if fkey == face:
                color = black

            e.Display.DrawDot(Point3d(*xyz), str(round(area, 2)), color, white)

    # --------------------------------------------------------------------------
    #  5. input point
    # --------------------------------------------------------------------------
    ip = Point3d(*f_center)
    line = Rhino.Geometry.Line(ip, ip + Vector3d(*f_normal))
    gp = get_target_point(line, OnDynamicDraw)

    # --------------------------------------------------------------------------
    #  6. update cell coordinates
    # --------------------------------------------------------------------------
    cell_relocate_face(cell, face, gp, f_normal)

    cell.draw()
Ejemplo n.º 29
0
    def aggregate_field(self, num):

        added = 0
        loops = 0
        while added < num:
            ## avoid endless loops
            loops += 1
            if loops > num * 100:
                break

            ## if no part is present in the aggregation, add first random part
            if len(self.aggregated_parts) == 0 and self.prev_num == 0:
                first_part = self.parts[random.choice(self.parts.keys())]
                start_point = None
                if self.multiple_fields:
                    f_name = first_part.field
                    if (self.mode == 2 or self.mode
                            == 3) and len(self.global_constraints) > 0:
                        start_point = self.field[f_name].return_highest_pt(
                            constraints=self.global_constraints)
                    else:
                        start_point = self.field[f_name].return_highest_pt()
                else:
                    if (self.mode == 2 or self.mode
                            == 3) and len(self.global_constraints) > 0:
                        start_point = self.field.return_highest_pt(
                            constraints=self.global_constraints)
                    else:
                        start_point = self.field.return_highest_pt()

                mov_vec = Vector3d.Subtract(Vector3d(start_point),
                                            Vector3d(first_part.center))
                move_transform = Transform.Translation(mov_vec.X, mov_vec.Y,
                                                       mov_vec.Z)
                first_part_trans = first_part.transform(move_transform)

                for conn in first_part_trans.connections:
                    conn.generate_rules_table(self.rules)

                first_part_trans.id = 0
                self.aggregated_parts.append(first_part_trans)

                ## compute all possible next parts and append to list
                self.compute_next_w_field(first_part_trans)
                added += 1

            else:
                ## if no part is available, exit the aggregation routine and return an error message
                if self.queue_count == 0:
                    msg = "Could not place " + str(num - added) + " parts"
                    return msg

                next_data = self.aggregation_queue[self.queue_count - 1]
                next_part = self.parts[next_data[0]]
                next_center = Point3d(next_part.center)
                orientTransform = next_data[2]

                global_check, coll_check, add_coll_check, missing_sup_check, global_const_check = self.check_all_constraints(
                    next_part, orientTransform)

                if not global_check:
                    next_part_trans = next_part.transform(orientTransform)
                    next_part_trans.reset_part(self.rules)

                    for conn in next_part_trans.connections:
                        conn.generate_rules_table(self.rules)

                    next_part_trans.id = len(self.aggregated_parts)
                    self.aggregated_parts[next_data[1]].children.append(
                        next_part_trans.id)
                    next_part_trans.parent = self.aggregated_parts[
                        next_data[1]].id
                    self.aggregated_parts.append(next_part_trans)

                    ## compute all possible next parts and append to list
                    self.compute_next_w_field(next_part_trans)
                    added += 1

                ## TO FIX --> do not remove rules when only caused by missing supports
                self.aggregation_queue.pop()
                self.queue_values.pop()
                self.queue_count -= 1
Ejemplo n.º 30
0
def rhino_volmesh_halfface_pinch(volmesh):
    hfkeys = _select_boundary_halffaces(volmesh)

    key = hfkeys[0]

    center = volmesh.halfface_center(key)
    normal = volmesh.halfface_oriented_normal(key)
    line = (center, add_vectors(center, normal))

    # --------------------------------------------------------------------------
    #  dynamic draw
    # --------------------------------------------------------------------------
    rs.EnableRedraw(True)

    def OnDynamicDraw(sender, e):

        cp = e.CurrentPoint
        plane = (cp, normal)
        line = (center, add_vectors(center, normal))
        it = intersection_line_plane(line, plane)

        translation = subtract_vectors(it, center)
        dot = dot_vectors(normal, translation)
        dot = dot / abs(dot)

        dist = distance_point_point(center, it) * dot

        for hfkey in hfkeys:
            hf_center = volmesh.halfface_center(hfkey)
            hf_normal = volmesh.halfface_oriented_normal(hfkey)
            ep = add_vectors(hf_center, scale_vector(hf_normal, dist))
            e.Display.DrawDottedLine(Point3d(*hf_center), Point3d(*ep),
                                     feedback_color)
            e.Display.DrawPoint(Point3d(*ep), 0, 4, black)
            for vkey in volmesh.halfface_vertices(hfkey):
                sp = volmesh.vertex_coordinates(vkey)
                e.Display.DrawLine(Point3d(*sp), Point3d(*ep), black, 2)

    # --------------------------------------------------------------------------
    #  input point
    # --------------------------------------------------------------------------
    ip = Point3d(*center)
    axis = Rhino.Geometry.Line(ip, ip + Vector3d(*normal))
    gp = get_target_point(axis, OnDynamicDraw)

    plane = (gp, normal)
    it = intersection_line_plane(line, plane)

    translation = subtract_vectors(it, center)
    dot = dot_vectors(normal, translation)
    dot = dot / abs(dot)

    rise = distance_point_point(center, it) * dot

    for hfkey in hfkeys:
        hf_center = volmesh.halfface_center(hfkey)
        hf_normal = volmesh.halfface_oriented_normal(hfkey)
        ep = add_vectors(hf_center, scale_vector(hf_normal, rise))

        volmesh_halfface_pinch(volmesh, hfkey, ep)

    volmesh.draw()

    return volmesh