def MakeSectionPreview(line, size): arrow = []# 目印を格納するリスト for i in range(len(line)): vec_x = rs.VectorCreate(rs.CurveStartPoint(line[i]), rs.CurveEndPoint(line[i])) vec_y = rs.VectorUnitize(rs.VectorCrossProduct(vec_x, [0,0,1])) pt3 = rs.DivideCurve(line[i], size) seglen = rs.Distance(pt3[0], pt3[1]) tri_s = [rs.AddPoint(pt3[i]) for i in range(3)] tri_e = [rs.AddPoint(pt3[len(pt3) - i]) for i in range(1, 4)] rs.MoveObject(tri_s[1], vec_y * (seglen * sqrt(3))) rs.MoveObject(tri_e[1], vec_y * (seglen * sqrt(3))) arrow.append(rs.AddInterpCurve(rs.coerce3dpointlist(tri_s), 1)) arrow.append(rs.AddInterpCurve(rs.coerce3dpointlist(tri_e), 1)) return arrow
def mesh_pull_to_surface(mesh,brep,max_srf_dis,tolerance): pts = [] key_index = {} count = 0 for k, a in mesh.vertices_iter(True): # if k in fixed: # continue pts.append((a['x'], a['y'], a['z'])) key_index[k] = count count += 1 if pts: points = rs.coerce3dpointlist(pts, True) points = brep.Faces[0].PullPointsToFace(points, tolerance) if len(pts) == len(points): #print "Yes" for key in key_index: index = key_index[key] if distance(points[index],pts[index])> max_srf_dis: vec = subtract_vectors(pts[index],points[index]) vec = normalize(vec) vec = scale(vec,max_srf_dis) x,y,z = add_vectors(points[index],vec) mesh.vertex[key]['x'] = x mesh.vertex[key]['y'] = y mesh.vertex[key]['z'] = z else: print "No" pass
def AddPolyline(points, layer, replace_id=None): """Adds a polyline curve to the current model Parameters: points = list of 3D points. Duplicate, consecutive points found in the array will be removed. The array must contain at least two points. If the array contains less than four points, then the first point and the last point must be different. replace_id[opt] = If set to the id of an existing object, the object will be replaced by this polyline Returns: id of the new curve object if successful """ points = rs.coerce3dpointlist(points, True) if replace_id: replace_id = rs.coerceguid(replace_id, True) rc = System.Guid.Empty if replace_id: pl = Rhino.Geometry.Polyline(points) if scriptcontext.doc.Objects.Replace(replace_id, pl): rc = replace_id else: rc = scriptcontext.doc.Objects.AddPolyline(points) if rc == System.Guid.Empty: raise Exception("Unable to add polyline to document") rs.ObjectName(rc, 'Layer: ' + str(layer)) return rc
def draw(dp,frameCnt,bboxes): # print("frameCnt = {}".format(frameCnt)) for box in boxes: corners = rs.coerce3dpointlist(box.corners, True) brep = Rhino.Geometry.Brep.CreateFromBox(corners) bbox = brep.GetBoundingBox(True) bboxes.append(bbox) mat = Rhino.Display.DisplayMaterial() mat.Diffuse = rs.CreateColor(box.color) mat.Transparency = 0.2 dp.DrawBrepShaded(brep, mat)
def mesh_max_deviation(mesh): max_distances = [] for fkey in mesh.faces_iter(): keys = mesh.face_vertices(fkey,ordered=True) points = [mesh.vertex_coordinates(key) for key in keys] points = rs.coerce3dpointlist(points, True) rc, plane = Rhino.Geometry.Plane.FitPlaneToPoints(points) points_planar = [plane.ClosestPoint(pt) for pt in points] distances = [distance(pt1,pt2) for pt1,pt2 in zip(points,points_planar)] max_distances.append(max(distances)) return max(max_distances)
def vert3_to_points(self, vert3): # print(vert3) points = [] for i in xrange(len(vert3)): vert = vert3[i] # print(vert) p = rs.AddPoint(vert) points.append(p) points_geo = rs.coerce3dpointlist(points) return points_geo
def ConvexHull(pointIds): points = rs.coerce3dpointlist(pointIds) points = sorted(points, key=lambda p: p[0]) hull = [] ptCount = len(points) indices = list(range(0, ptCount)) + list(range(ptCount - 1, -1, -1)) for i in indices: curPt = points[i] if curPt in hull: continue hull = SafeExtend(hull, curPt) hull = SafeExtend(hull, hull[0]) return hull
def AddPolyline(points, layer, replace_id=None, objColor=(0, 0, 0), segment=''): """Adds a polyline to the current CAD scene Parameters: points = list of 3D points. Duplicate, consecutive points found in the array will be removed. The array must contain at least two points. If the array contains less than four points, then the first point and the last point must be different. replace_id[opt] = If set to the id of an existing object, the object will be replaced by this polyline Returns: id of the new curve object if successful """ points = rs.coerce3dpointlist(points, True) if replace_id: replace_id = rs.coerceguid(replace_id, True) rc = System.Guid.Empty if replace_id: pl = Rhino.Geometry.Polyline(points) plColor = Rhino.Input.Custom.GetObject.Color if scriptcontext.doc.Objects.Replace(replace_id, pl): rc = replace_id else: rc = Polyline(points) attributes = ObjectAttributes() attributes.ObjectColor = ColorTranslator.FromOle(getIfromRGB(objColor)) attributes.ColorSource = ObjectColorSource.ColorFromObject zero_str = '000000' objName = 'Layer: ' + zero_str[:-len(str(layer))] + str( layer) + ' ' + segment # str(layer) attributes.Name = objName lIdx = scriptcontext.doc.Layers.Find('MW 3D Printer Perimeter', 1) attributes.LayerIndex = lIdx doc.Objects.AddPolyline(rc, attributes) if rc == System.Guid.Empty: raise Exception("Unable to add polyline to document") return rc
def user_func(mesh,i): pts = [] key_index = {} count = 0 for k, a in mesh.vertices_iter(True): if k in boundary: continue pts.append((a['x'], a['y'], a['z'])) key_index[k] = count count += 1 if pts: points = rs.coerce3dpointlist(pts, True) points = mesh_rhino_obj.PullPointsToMesh(points) if len(pts) == len(points): #print "Yes" for key in key_index: index = key_index[key] mesh.vertex[key]['x'] = points[index][0] mesh.vertex[key]['y'] = points[index][1] mesh.vertex[key]['z'] = points[index][2] else: print "No" pass mesh_smooth_boundary(mesh,fixed,crvs, k=1, d=0.5) if vis: if i%vis==0: rs.Prompt(str(i)) draw_light(mesh,temp = True) Rhino.RhinoApp.Wait()
def user_func(mesh,i): #dict((k, i) for i, k in self.vertices_enum()) pts = [] key_index = {} count = 0 for k, a in mesh.vertices_iter(True): if k in fixed: continue pts.append((a['x'], a['y'], a['z'])) key_index[k] = count count += 1 if pts: points = rs.coerce3dpointlist(pts, True) points = brep.Faces[0].PullPointsToFace(points, tolerance) if len(pts) == len(points): #print "Yes" for key in key_index: index = key_index[key] mesh.vertex[key]['x'] = points[index][0] mesh.vertex[key]['y'] = points[index][1] mesh.vertex[key]['z'] = points[index][2] else: print "No" pass if vis: if i%vis==0: rs.Prompt(str(i)) draw_light(mesh,temp = True) Rhino.RhinoApp.Wait()
def draw(mesh, dev_threshold): srfs = [] for u, v in mesh.edges(): pts = [] pts.append(mesh.vertex_coordinates(u)) pts.append(mesh.vertex_coordinates(v)) pts.append( (mesh.vertex[u]['x2'], mesh.vertex[u]['y2'], mesh.vertex[u]['z2'])) pts.append( (mesh.vertex[v]['x2'], mesh.vertex[v]['y2'], mesh.vertex[v]['z2'])) srfs.append(rs.AddSrfPt(pts)) points = rs.coerce3dpointlist(pts, True) rc, plane = Rhino.Geometry.Plane.FitPlaneToPoints(points) pt3, pt4 = [plane.ClosestPoint(pt) for pt in points[2:]] distance_max = max( [distance(pt1, pt2) for pt1, pt2 in zip(points[2:], [pt3, pt4])]) if distance_max > dev_threshold: rs.ObjectColor(srfs[-1], [255, 0, 0]) rs.AddObjectsToGroup(srfs, rs.AddGroup()) return srfs
pt.append((int(cube_dim),0,int(cube_dim))) cube_pts = rs.AddPoints(pt) cube_range = range(int(cube_dim) , int(cube_num * cube_dim) , int(cube_dim)) xdir = [rs.CopyObject(i, (r , 0 , 0)) for r in cube_range for i in cube_pts] xdir = cube_pts + xdir ydir=[rs.CopyObject(x , (0 , r , 0)) for r in cube_range for x in xdir] zdir=[rs.CopyObject(x , (0 , 0 , r)) for r in cube_range for x in xdir] + \ [rs.CopyObject(y , (0 , 0 , r)) for r in cube_range for y in ydir] all_cube_pts = rs.coerce3dpointlist(xdir + ydir + zdir) index = [rs.PointArrayClosestPoint(point_cloud, pt) for pt in all_cube_pts] mesh_pts = [point_cloud[i] for i in index] dist = [rs.Distance(c,p) for c,p in zip(all_cube_pts,mesh_pts)] cubes = create_set(all_cube_pts) dist = create_set(dist) triangles = [polygonise(d,c,isolevel) for d,c in zip(dist,cubes)] point1=[i[0] for tri in triangles for t in tri for i in t] point2=[i[1] for tri in triangles for t in tri for i in t] point3=[i[2] for tri in triangles for t in tri for i in t]
all(is_in_circle(c, r) for r in points): result = c if result is not None: return result # This optimization is not mathematically proven # Try all unique triples for i in range(len(points)): p = points[i] for j in range(i + 1, len(points)): q = points[j] for k in range(j + 1, len(points)): r = points[k] c = make_circumcircle(p, q, r) if c is not None and (result is None or c[2] < result[2]) and \ all(is_in_circle(c, s) for s in points): result = c if result is None: raise AssertionError() return result if __name__ == "__main__": pts = rs.AllObjects() ptsList = rs.coerce3dpointlist(pts) ptCoords = [] for pt in ptsList: ptCoords.append([pt.X, pt.Y]) results = _smallest_enclosing_circle_naive(ptCoords) rs.AddCircle((results[0], results[1], 0), results[2])
def main(sourceSrfs, gridSizeOrPoints, sunVectors, context, numOfBounce, firstBounceLen, lastBounceLen): # import the classes if sc.sticky.has_key('ladybug_release'): try: if not sc.sticky['ladybug_release'].isCompatible(ghenv.Component): return -1 if sc.sticky['ladybug_release'].isInputMissing(ghenv.Component): return -1 except: warning = "You need a newer version of Ladybug to use this compoent." + \ "Use updateLadybug component to update userObjects.\n" + \ "If you have already updated userObjects drag Ladybug_Ladybug component " + \ "into canvas and try again." w = gh.GH_RuntimeMessageLevel.Warning ghenv.Component.AddRuntimeMessage(w, warning) return -1 lb_preparation = sc.sticky["ladybug_Preparation"]() lb_mesh = sc.sticky["ladybug_Mesh"]() lb_runStudy_GH = sc.sticky["ladybug_RunAnalysis"]() lb_visualization = sc.sticky["ladybug_ResultVisualization"]() else: print "You should first let the Ladybug fly..." w = gh.GH_RuntimeMessageLevel.Warning ghenv.Component.AddRuntimeMessage(w, "You should first let the Ladybug fly...") return -1 # Check the geometry if len(context)==0: context = sourceSrfs else: context = context + sourceSrfs ## clean the geometry and bring them to rhinoCommon separated as mesh and Brep contextMesh, contextBrep = lb_preparation.cleanAndCoerceList(context) ## mesh Brep contextMeshedBrep = lb_mesh.parallel_makeContextMesh(contextBrep) ## Flatten the list of surfaces contextMeshedBrep = lb_preparation.flattenList(contextMeshedBrep) contextSrfs = contextMesh + contextMeshedBrep joinedContext = lb_mesh.joinMesh(contextSrfs) # Get rid of trimmed parts cleanBrep = rc.Geometry.Brep.CreateFromMesh(joinedContext, False) try: gridSize = float(gridSizeOrPoints[0]) basedOnGrid = True except: basedOnGrid = False initialTestPoints = rs.coerce3dpointlist(gridSizeOrPoints) ptsNormals = [cleanBrep.ClosestPoint(intPt, sc.doc.ModelAbsoluteTolerance)[5] for intPt in initialTestPoints] # generate the test points if basedOnGrid: ## mesh Brep analysisMesh, analysisBrep = lb_preparation.cleanAndCoerceList(sourceSrfs) analysisMeshedBrep = lb_mesh.parallel_makeSurfaceMesh(analysisBrep, float(gridSize)) ## Flatten the list of surfaces analysisMeshedBrep = lb_preparation.flattenList(analysisMeshedBrep) analysisSrfs = analysisMesh + analysisMeshedBrep initialTestPoints, ptsNormals, meshSrfAreas = lb_mesh.parallel_testPointCalculator(analysisSrfs, 0, False) initialTestPoints = lb_preparation.flattenList(initialTestPoints) ptsNormals = lb_preparation.flattenList(ptsNormals) # find the distance for moving the points backward try: firstBounceLen = float(firstBounceLen) except: maxPt =joinedContext.GetBoundingBox(True).Max minPt = joinedContext.GetBoundingBox(True).Min firstBounceLen = maxPt.DistanceTo(minPt) rays = [] for ptCount, testPt in enumerate(initialTestPoints): for vector in sunVectors: vector.Unitize() testPt = rc.Geometry.Point3d.Add(testPt, -vector * firstBounceLen) ray = rc.Geometry.Ray3d(testPt, vector) if numOfBounce>0 and rc.Geometry.Vector3d.VectorAngle(vector, ptsNormals[ptCount]) < math.pi/2: intPts = rc.Geometry.Intersect.Intersection.RayShoot(ray, [cleanBrep], numOfBounce) #print intPts if intPts: ptList = [testPt] ptList.extend(intPts) ray = rc.Geometry.Polyline(ptList).ToNurbsCurve() try: # create last ray # calculate plane at intersection intNormal = cleanBrep.ClosestPoint(intPts[-1], sc.doc.ModelAbsoluteTolerance)[5] lastVector = rc.Geometry.Vector3d(ptList[-2] - ptList[-1]) lastVector.Unitize() crossProductNormal = rc.Geometry.Vector3d.CrossProduct(intNormal, lastVector) plane = rc.Geometry.Plane(intPts[-1], intNormal, crossProductNormal) mirrorT = rc.Geometry.Transform.Mirror(intPts[-1], plane.Normal) lastRay = rc.Geometry.Line(intPts[-1], lastBounceLen * lastVector).ToNurbsCurve() lastRay.Transform(mirrorT) ray = rc.Geometry.Curve.JoinCurves([ray, lastRay])[0] except: pass rays.append(ray) else: # no bounce so let's just create a line form the point firstRay = rc.Geometry.Line(testPt, lastBounceLen * vector).ToNurbsCurve() rays.append(firstRay) else: rays.append(None) return rays, initialTestPoints
#print divResult for pt in divResult[2]: points.append(pt) dblError = abs(leftovers[0]-leftovers[1]) print "Deviation: " + str(dblError) print "leftover0: " + str(leftovers[0]) print "leftover1: " + str(leftovers[1]) if leftovers[0]>leftovers[1] and dblError > tolerance: dblMax = dblCheck counter += 1 #print dblMax elif leftovers[0]<leftovers[1] and dblError > tolerance: dblMin = dblCheck counter += 1 #print dblMax elif counter > maxSteps or dblError <= tolerance: t = dblCheck pts = rs.coerce3dpointlist(points) break dblCheck = (dblMax+dblMin)/2 #t = result i = counter
for j in xrange(len(points) - 1): if j < (len(points) - 2): vertex_ = [(c_index, int(j), int(j) + 1, int(j) + 1)] # print(vertex_) m = rs.AddMesh(points, vertex_) meshes.append(m) else: vertex_ = [(c_index, int(j), 0, 0)] # print(vertex_) m = rs.AddMesh(points, vertex_) meshes.append(m) mesh_joined = rs.JoinMeshes(meshes) return mesh_joined points = point_polyline(CURVE) # print(points) point_cp_0 = rs.coerce3dpointlist(rs.CopyObjects(points)) point_cp_1 = rs.coerce3dpointlist(rs.CopyObjects(points)) step = construct_mesh_step(point_cp_0) center = construct_mesh_center(point_cp_1) POINTS_ = points MESH_STEP_ = step MESH_CENTER_ = center
for k in range(kmax): if 1 == 1: max_dev_step = mesh_max_deviation(mesh) nodes_dict = {key: [] for key in mesh.vertices()} dots = [] for fkey in mesh.faces_iter(): keys = mesh.face_vertices(fkey,ordered=True) points = [mesh.vertex_coordinates(key) for key in keys] points = rs.coerce3dpointlist(points, True) rc, plane = Rhino.Geometry.Plane.FitPlaneToPoints(points) points = [plane.ClosestPoint(pt) for pt in points] # dis1_min, dis1_max,dis2_min,dis2_max= diagonal[fkey] if 1==1: dis1_step = distance(points[0],points[2]) dis2_step = distance(points[1],points[3]) if dis1_step > dis2_step: if (dis1_step-dis2_step)/dis1_step > diagonal_prop: trg_dis = -dis2_step/(diagonal_prop-1) points[0],points[2] = space_points(points[0],points[2],trg_dis) #rs.AddLine(points[0],points[2]) else:
def relax_mesh_on_surface(): polylines = rs.ObjectsByLayer("re_02_polys") pts_objs = rs.ObjectsByLayer("re_03_points") vis = 5 kmax = 2000 dis = 0.3 dev_threshold = 0.003 angle_max = 30 pts = get_points_coordinates(pts_objs) mesh = Mesh() for i, pt in enumerate(pts): mesh.add_vertex(str(i), {'x': pt[0], 'y': pt[1], 'z': pt[2]}) polys = get_polyline_points(polylines) tris = get_faces_from_polylines(polys, pts) for tri in tris: mesh.add_face(tri) rs.EnableRedraw(False) pts = [] for key, a in mesh.vertices_iter(True): pt1 = (a['x'], a['y'], a['z']) pts.append(pt1) vec = mesh.vertex_normal(key) vec = scale(normalize(vec), dis) pt2 = add_vectors(pt1, vec) pt2 = add_vectors(pt1, vec) a['x2'] = pt2[0] a['y2'] = pt2[1] a['z2'] = pt2[2] a['normal'] = vec #rs.AddLine(pt1,pt2) faces_1 = draw(mesh, dev_threshold) rs.HideObjects(faces_1) for k in range(kmax): nodes_top_dict = {key: [] for key in mesh.vertices()} polys = [] max_distances = [] for u, v in mesh.edges(): pt1 = mesh.vertex_coordinates(u) pt2 = mesh.vertex_coordinates(v) pt3 = mesh.vertex[u]['x2'], mesh.vertex[u]['y2'], mesh.vertex[u][ 'z2'] pt4 = mesh.vertex[v]['x2'], mesh.vertex[v]['y2'], mesh.vertex[v][ 'z2'] points = [pt1, pt2, pt3, pt4] points = rs.coerce3dpointlist(points, True) rc, plane = Rhino.Geometry.Plane.FitPlaneToPoints(points) pt3, pt4 = [plane.ClosestPoint(pt) for pt in points[2:]] vec = scale(normalize(subtract_vectors(pt3, pt1)), dis) pt3 = add_vectors(pt1, vec) vec = scale(normalize(subtract_vectors(pt4, pt2)), dis) pt4 = add_vectors(pt2, vec) nodes_top_dict[u].append(pt3) nodes_top_dict[v].append(pt4) distances = [ distance(pt1, pt2) for pt1, pt2 in zip(points[2:], [pt3, pt4]) ] max_distances.append(max(distances)) for key, a in mesh.vertices_iter(True): cent = centroid(nodes_top_dict[key]) pt = mesh.vertex_coordinates(key) vec = subtract_vectors(cent, pt) norm = a['normal'] if angle_smallest(vec, norm) < angle_max: a['x2'] = cent[0] a['y2'] = cent[1] a['z2'] = cent[2] if k % vis == 0: rs.Prompt( "Iteration {0} of {1} with with deviation sum {2}".format( k, kmax, round(sum(max_distances), 4))) draw_light(mesh, temp=True) if max(max_distances) < dev_threshold or k == kmax: print "Iteration {0} of {1} with deviation sum {2}".format( k, kmax, round(sum(max_distances), 4)) break dfaces_2 = draw(mesh, dev_threshold) rs.ShowObjects(faces_1) rs.EnableRedraw(True) print max(max_distances)