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)
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 = []
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
def cohere(self, others): #find average point of all other Boids centerPoint = others.pop(0).position for other in others: centerPoint = Point3d.Add(centerPoint, other.position) centerPoint = Point3d.Divide(centerPoint, numBoids - 1) #find direction from Boid to average point of all other Boids direction = Point3d.Subtract(centerPoint, self.position) #remove magnitude from average-seeking vector direction = Vector3d.Divide(direction, direction.Length) #adapt heading to new direction self.heading = Vector3d.Add(direction, self.heading)
def update(self, eddies, crv): self.gettarget_2d(eddies) self.getorient(eddies) self.getacc_z() self.boundarycheck() self.getvel() self.loc = PVector.Add(self.loc, self.vel)
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
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
def lowerlimit(vct, speed): if vct.Length >= speed: pass else: vct.Unitize() vct = PVector.Multiply(vct, speed) return vct
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()
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)
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
def inradius(self, eddy): dist = PVector.Subtract(self.loc, eddy.loc) dist2d = PVector(dist.X, dist.Y, 0).Length if dist2d >= eddy.buffer: return 0 elif dist2d <= eddy.core: return -1 else: return dist2d
def gettarget_2d(self, eddies): target_2d = PVector(0, 0, 0) for i in xrange(len(eddies)): v = PVector.Subtract(eddies[i].loc, self.loc) v2d = PVector( v.X, v.Y, 0) # 2d planer target, X Y are the most important factors dist2d = v2d.Length # compute the sum of the arraction vector / distance v2d.Unitize() v2d = PVector.Multiply(v2d, float(eddies[i].gravity / pow(dist2d, 1.0))) # add vector to attraction vector collection target_2d = PVector.Add(target_2d, v2d) #Limit the target length target_2d = toplimit(target_2d, self.toplimit) target_2d = lowerlimit(target_2d, self.lowerlimit) self.target = target_2d
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
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
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
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])
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
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
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
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
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 = []
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
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)
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
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
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]))
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
def getvel(self): self.vel = PVector.Add(self.vel, self.orient) self.vel = toplimit(self.vel, self.toplimit) self.vel = PVector.Add(self.vel, self.acc)
gravity = gravityinput[i] oricharge = orichargeinput[i] affrange = affrangeinput[i] eddyconfig.append(Eddy_config(loc, gravity, oricharge, affrange, i)) eddycollection.append(Eddy(eddyconfig[i])) #generate flow particles crv = sc.doc.Objects.AddCurve(sitecrv) j = -1 for i in xrange(n_flow): u = random.uniform(0.0, 1.0) v = random.uniform(0.0, 1.0) a = sitesrf.PointAt(u, v) vel = PVector(random.uniform(0.0, 1.0), random.uniform(0.0, 1.0), 0) particle = PVector(a.X, a.Y, a.Z) if rs.PointInPlanarClosedCurve(a, crv) == 0: pass else: flowconfig.append( Flow_config(particle, PVector(0, 0, 0), PVector(0, 0, 0))) for config in flowconfig: flowcollection.append(Flow(config)) #=================================# #Draw #=================================# for i in xrange(100): for particle in flowcollection: particle.run(eddycollection, crv)