def drawBox( side, location, angle_degrees1, angle_degrees2): """画一个2D方块 参数: side(double): 方块的长度, double locaiton(tuple(double, double,double)): 方块中心的位置 angle_degrees1(double): xy平面旋转角度degree1 angle_degrees2(double): 到达位置后继续朝z轴方向旋转角度degree2 Returns: guid """ corners = [] corners.append((-side/2,-side/2,0)) corners.append(( side/2,-side/2,0)) corners.append((side/2,side/2,0)) corners.append((-side/2,side/2,0)) corners.append((-side/2,-side/2,side)) corners.append((side/2,-side/2,side)) corners.append((side/2,side/2,side)) corners.append((-side/2,side/2,side)) obj = rs.AddBox(corners) xform = rs.XformRotation2(angle_degrees1, (0,0,1), (0,0,0)) obj = rs.TransformObject( obj, xform, False ) vectorR1 = rs.VectorRotate( (1,0,0), angle_degrees1, (0,0,0)) vectorR2 = rs.VectorCrossProduct(vectorR1, (0,0,1)) xform = rs.XformRotation2(angle_degrees1, vectorR2, (0,0,0)) obj = rs.TransformObject( obj, xform, False ) xform = rs.XformTranslation( location) obj = rs.TransformObject( obj, xform, False ) return obj
def drawRect( side, location, angle_degrees ): """画一个2D方块 参数: side(double): 方块的长度, double locaiton(tuple(double, double,double)): 方块中心的位置 angle_degrees(double): 旋转角度degree Returns: guid """ p0 = (-side/2,-side/2,0) p1 = (side/2,-side/2,0) p2 = (side/2,side/2,0) p3 = (-side/2,side/2,0) obj = rs.AddPolyline([p0,p1,p2,p3,p0]) xform = rs.XformRotation2(angle_degrees, (0,0,1), (0,0,0)) obj = rs.TransformObject( obj, xform, False ) xform = rs.XformTranslation( location) obj = rs.TransformObject( obj, xform, False ) return obj
def transf_t(t, r, s): plane = rh.CurvePerpFrame(path, rh.CurveParameter(path, t)) xform = rh.XformChangeBasis(plane, geo.Plane.WorldXY) xform = rh.XformMultiply(xform, rh.XformScale(s)) xform = rh.XformMultiply( xform, geo.Transform.Rotation(r, geo.Vector3d(0, 0, 1), rawu0)) return rh.TransformObject(profile, xform, True)
def main(): print 'test' objs = rs.GetObjects() vec_x = [10,0,0] # restore viewport Cplane p1 = rs.WorldXYPlane() rs.ViewCPlane(None, p1) for obj in objs: if rs.IsBlockInstance(obj) and rs.BlockInstanceName(strObject): xform1 = rs.BlockInstanceXform(obj) crv = rs.AddCurve([ [0,0,0], [0,300,0] ]) xfrom1_inv = rs.TransformObject( crv, (xform1) ) rs.SelectObject(crv) vec1 = rs.CurveEndPoint(crv) - rs.CurveStartPoint(crv) print vec1, math.degrees(calcAngle(vec1, vec_x)) if __name__ == "__main__": main();
def tool_visualization(origin_coords, mesh, planes, i): """ Visualize example tool motion. """ i = min(i, len(planes) - 1) # make sure i doesn't go beyond available number of planes passed_path = None assert planes[0], 'The planes you have provided are invalid.' origin = [ float(origin_coords[0]), float(origin_coords[1]), float(origin_coords[2]) ] o = rg.Point3d(origin[0], origin[1], origin[2]) x = rg.Vector3d(1, 0, 0) y = rg.Vector3d(0, -1, 0) # z = rg.Vector3d(0, 0, -1) ee_frame = rg.Plane(o, x, y) target_frame = planes[i] T = rg.Transform.PlaneToPlane(ee_frame, target_frame) mesh = rs.TransformObject(rs.CopyObject(mesh), T) passed_path = rs.AddPolyline([plane.Origin for plane in planes[:i + 1]]) return mesh, passed_path
def pre_process(): # delete all previous user text all_objs = rs.AllObjects() for obj in all_objs: rh_obj = rs.coercerhinoobject(obj) rh_obj.Attributes.DeleteAllUserStrings() # remove all blocks for block in rs.BlockNames(): rs.DeleteBlock(block) # set current layer rs.CurrentLayer(relevant_layers_dict["buildings"]) # remove redundant layers for layer_name in rs.LayerNames(): if layer_name not in relevant_layers_dict.values(): rs.PurgeLayer(layer_name) # get all objects in building layer building_objs = rs.ObjectsByLayer(relevant_layers_dict["buildings"]) for building_obj in building_objs: if rs.IsCurve(building_obj) and rs.IsCurveClosed(building_obj): # flatten curve to XY plane matrix = rs.XformPlanarProjection(rg.Plane.WorldXY) rs.TransformObject(building_obj, matrix, copy=False) # delete all object with a surface grater or smaller from MIN_BUILDING_AREA_SQ by TOLERANCE or just smaller than MIN_BUILDING_AREA_SQ TOLERANCE = 2 if rs.CurveArea(building_obj)[0] < MIN_BUILDING_AREA_SQM or abs( rs.CurveArea(building_obj)[0] - MIN_BUILDING_AREA_SQM) < TOLERANCE: rs.DeleteObject(building_obj)
def TransformProfile(object, pt1, pt2): normal = rs.VectorSubtract(pt1, pt2) normal = rs.VectorUnitize(normal) plane = rs.PlaneFromNormal(pt1, normal) transformation = rs.XformRotation1((rs.WorldXYPlane), normal) profiletras = rs.TransformObject(object, transformation, True)
def render_path_visualization(points, mesh_normals, layer_heights, up_vectors, extruder_toggles, cross_section, planar_printing): """ Visualize print paths with simple loft surfaces. """ # check input assert len(points) == len(mesh_normals) == len(layer_heights) == len(up_vectors) == len(extruder_toggles), \ 'Wrong length of input lists' loft_surfaces = [] travel_path_lines = [] if points[0] and mesh_normals[0] and layer_heights[0] and up_vectors[ 0]: # check if any of the values are None if planar_printing: # then make sure that all normals lie on the xy plane for n in mesh_normals: n[2] = 0 # transform and scale cross sections accordingly cen = rs.CurveAreaCentroid(cross_section)[0] origin_plane = rg.Plane(cen, rg.Vector3d(1, 0, 0), rg.Vector3d(0, 0, 1)) target_planes = [] for i, pt in enumerate(points): target_plane = rg.Plane(pt, mesh_normals[i], up_vectors[i]) target_planes.append(target_plane) cross_sections = [] for h, target_plane in zip(layer_heights, target_planes): section = rs.ScaleObject(rs.CopyObject(cross_section), origin=cen, scale=[0.9 * h, 1, 0.9 * h]) T = rg.Transform.PlaneToPlane(origin_plane, target_plane) rs.TransformObject(section, T) cross_sections.append(section) loft_surfaces = [] travel_path_lines = [] for i in range(len(points) - 1): if extruder_toggles[i]: loft = rs.AddLoftSrf( [cross_sections[i], cross_sections[i + 1]]) if loft: loft_surfaces.append(loft[0]) else: line = rg.Curve.CreateControlPointCurve( [points[i], points[i + 1]]) travel_path_lines.append(line) # add to travel path list else: print( 'At least one of the inputs that you have provided are invalid. ') return loft_surfaces, travel_path_lines
def mirror(shape, plane_position=u0(), plane_normal=vz(), copy=True): p = Pt(plane_position) v = Vt(plane_normal) xform = rh.XformMirror(p, v) ref = shape.realize() new_ref = ref.map(lambda r: native_ref(rh.TransformObject(r, xform, copy))) if not copy: shape.mark_deleted() return new_ref
def checkblkplane(blkid): xform = rs.BlockInstanceXform(blkid) plane = rs.PlaneTransform(rs.WorldXYPlane(), xform) normal = plane.ZAxis.Z print normal if normal < 0: newxform = rs.XformMirror(plane.Origin, plane.Normal) return rs.TransformObject(blkid, newxform) else: return
def MirrorObjectXZ(ObjectId): # Mirrors an object with respect to the XoZ plane # Argument: the object to be mirrored. # Returns: the ID of the object if succesful TransMat = [] TransMat.append([1, 0, 0, 0]) TransMat.append([0, -1, 0, 0]) TransMat.append([0, 0, 1, 0]) TransMat.append([0, 0, 0, 1]) TransObjId = rs.TransformObject(ObjectId, TransMat, True) return TransObjId
def GetAllBlockObjectsInPosition(obj): """Recursively get all objects from a block (and blocks in blocks) inputs: obj (block instance) returns: objs (list guids): Geometry is a copy of the instance geometry """ blockObjs = rs.BlockObjects(rs.BlockInstanceName(obj)) xform = rs.BlockInstanceXform(obj) objList = [] for eachblockObj in blockObjs: if rs.IsBlockInstance(eachblockObj): thisBlockObjects = GetAllBlockObjectsInPosition(eachblockObj) for eachObject in thisBlockObjects: transformedObj = rs.TransformObject(eachObject, xform, False) objList.append(transformedObj) else: transformedObj = rs.TransformObject(eachblockObj, xform, True) objList.append(transformedObj) return objList
def MakeBlockUnique(block, newName): """ Explodes a block and makes a new one with 'newName' """ xform = rs.BlockInstanceXform(block) insertPt = rs.BlockInstanceInsertPoint(block) objs = rs.ExplodeBlockInstance(block, False) rs.TransformObjects(objs, rs.XformInverse(xform)) pt = rs.TransformObject(insertPt, rs.XformInverse(xform)) rs.AddBlock(objs, insertPt, newName, True) newBlock = rs.InsertBlock2(newName, xform) rs.DeleteObject(pt) return newBlock
def IntersectGeo(obj, level): tolerance = rs.UnitAbsoluteTolerance() plane = rc.Geometry.Plane(rs.coerce3dpoint((0, 0, level)), rs.coerce3dvector((0, 0, 1))) finalCurves = [] #BLOCKS if rs.IsBlockInstance(obj): matrix = rs.BlockInstanceXform(obj) blockObjs = rs.BlockObjects(rs.BlockInstanceName(obj)) for eachBlockObj in blockObjs: newCopy = rs.CopyObject(eachBlockObj) xformedObj = rs.TransformObject(newCopy, matrix) #EXTRUSIONS if isinstance(xformedObj, rc.Geometry.Extrusion): temp = sc.doc.Objects.AddBrep(xformedObj.ToBrep(False)) xformedObj = rs.coercebrep(temp) rs.DeleteObject(temp) #BREPS IN BLOCK result = IntersectBrepPlane(xformedObj, plane) if result is None: continue for each in result: if each is not None: finalCurves.append(each) rs.DeleteObject(xformedObj) #MESHES IN BLOCK <---This code might not be necessary result = IntersectMeshPlane(xformedObj, plane) if result is None: continue for each in result: if each is not None: finalCurves.append(each) rs.DeleteObject(xformedObj) #BREPS elif rs.IsBrep(obj): result = IntersectBrepPlane(obj, plane) if result is None: return None for each in result: if each is not None: finalCurves.append(each) #MESHES elif rs.IsMesh(obj): result = IntersectMeshPlane(obj, plane) if result is None: return None for each in result: if each is not None: finalCurves.append(each) return finalCurves
def blkFace(obj): cameraPos = rs.ViewCamera() cameraPos.Z = 0 xform = rs.BlockInstanceXform(obj) plane = rs.PlaneTransform(rs.WorldXYPlane(), xform) viewdir = rs.VectorUnitize(cameraPos - plane.Origin) angle = rs.VectorAngle(viewdir, plane.YAxis) newXform = rs.XformRotation3(plane.YAxis, viewdir, plane.Origin) rs.TransformObject(obj, newXform)
def blkFace(obj): cameraPos = rs.ViewCamera() cameraPos.Z = 0 plane = rs.WorldXYPlane() if rs.IsBlockInstance(obj): plane = blkPlane(obj) elif rs.IsSurface(obj): plane = srfPlane(obj) targetpos = plane.Origin targetpos.Z = 0 viewdir = rs.VectorUnitize(cameraPos - targetpos) angle = rs.VectorAngle(viewdir, plane.YAxis) newXform = rs.XformRotation3(plane.YAxis, viewdir, plane.Origin) rs.TransformObject(obj, newXform)
def ResetBlockScale(): try: blocks = rs.GetObjects("Select blocks to reset", rs.filter.instance, preselect=True) if blocks is None: return points = [ rg.Point3d(0, 0, 0), rg.Point3d(1, 0, 0), rg.Point3d(0, 1, 0), rg.Point3d(0, 0, 1) ] for block in blocks: xform = rs.BlockInstanceXform(block) namne = rs.BlockInstanceName(block) pts = rg.Polyline(points) pts.Transform(xform) finalOrigin = pts[1] finalXaxis = rs.VectorSubtract(pts[1], pts[0]) finalYaxis = rs.VectorSubtract(pts[2], pts[0]) finalPlane = rg.Plane(finalOrigin, finalXaxis, finalYaxis) xFac = 1 / rs.Distance(pts[1], pts[0]) yFac = 1 / rs.Distance(pts[2], pts[0]) zFac = 1 / rs.Distance(pts[3], pts[0]) newXForm = rg.Transform.Scale(finalPlane, xFac, yFac, zFac) rs.TransformObject(block, newXForm) return True except: return False
# set current layer rs.CurrentLayer(relevant_layers_dict["buildings"]) # remove redundant layers for layer_name in rs.LayerNames(): if layer_name not in relevant_layers_dict.values(): rs.PurgeLayer(layer_name) # get all objects in building layer building_objs = rs.ObjectsByLayer(relevant_layers_dict["buildings"]) for building_obj in building_objs: if rs.IsCurve(building_obj) and rs.IsCurveClosed(building_obj): # flatten curve to XY plane matrix = rs.XformPlanarProjection(rg.Plane.WorldXY) rs.TransformObject(building_obj, matrix, copy=False) ########################################################################################################################################## # set current working dir os.chdir(working_dir_path) # Add attributes to buildings with open(proc_attributes_path, "r") as input_handle: rdr = csv.reader(input_handle) # read attribure labels (first row) attribute_labels_list = next(rdr) # get x, y, z attributes indices x_idx, y_idx, z_idx = attribute_labels_list.index(
def RunCommand(is_interactive): if sc.escape_test(False): print "script cancelled" #do something print "Making unique..." #******* Get blocks ***************** #************************************ objectIds = rs.GetObjects("Pick some blocks", 4096, preselect=True) if not objectIds: print "No objects" return False #pause viewport redraw rs.EnableRedraw(False) #******* Sort blocks by type ******** #************************************ blockTypes = {} for id in objectIds: blockName = rs.BlockInstanceName(id) if blockName not in blockTypes: blockTypes[blockName] = [] blockTypes[blockName].append(id) #***** Define new block and add ***** #************************************ #Get block names blockNames = rs.BlockNames() #gather all new objects when done finalObjs = [] for blockType in blockTypes: for id in blockTypes[blockType]: #Get the block transformation matrix and name blockXForm = rs.BlockInstanceXform(id) blockName = rs.BlockInstanceName(id) #Insert new block in 0,0,0 newBlock = rs.InsertBlock(blockName, [0, 0, 0]) #Explode the block exObjs = rs.ExplodeBlockInstance(newBlock) #create new block name # if the string ends in digits m will be a Match object, or None otherwise. strippedName = re.sub(r'#[0-9]+$', '', blockName) #test if block name exist and add to the end number if true. x = 0 tryAgain = True while tryAgain: x += 1 newerBlockName = strippedName + "#" + str(x) if newerBlockName not in blockNames: tryAgain = False break #insert exObjs as new block rs.AddBlock(exObjs, [0, 0, 0], newerBlockName, delete_input=True) newerBlock = rs.InsertBlock(newerBlockName, [0, 0, 0]) #match properties from original rs.MatchObjectAttributes(newerBlock, id) #transform new block rs.TransformObject(newerBlock, blockXForm) #append for final selection finalObjs.append(newerBlock) #add name to list of used blocknames. blockNames.append(newerBlockName) #Delete original block rs.DeleteObjects(objectIds) #Select all new objects rs.SelectObjects(finalObjs) rs.EnableRedraw(True) print "...aaand its done." #End RunCommand() #end sane return 0
def ReplaceObject(): """ Have the user orient 1 replacement correctly to one target. get a plane from frame on brep face[0] Get plane-plane transform from target to a plane on the same face on the other targets See if it works for meshes - just pick any face and do the same thing - get the plane from the face verts. """ targId = rs.GetObject("Select the first object to replace", filter=8+16) if not targId:return obj = sc.doc.Objects.Find(targId) geo = obj.Geometry extrusion = False if isinstance(geo, Rhino.Geometry.Extrusion): extrusion = True geo = geo.ToBrep() face = geo.Faces[0] faceCount = geo.Faces.Count faceBrep = face.DuplicateFace(False) area = faceBrep.GetArea() srf = face.UnderlyingSurface() rc, plane = srf.FrameAt(srf.Domain(0).Mid, srf.Domain(1).Mid) if not rc: print "Error finding base plane." return ids = rs.GetObjects("Now select the other objects to replace.") if not ids:return newIds = rs.GetObjects("Select replacement objects") if not newIds: return tol = sc.doc.ModelAbsoluteTolerance rs.EnableRedraw(False) for ID in ids: tempGeo = sc.doc.Objects.Find(ID).Geometry if isinstance(tempGeo, Rhino.Geometry.Extrusion): tempGeo = tempGeo.ToBrep() tempFace = tempGeo.Faces[0] tempFaceBrep = tempFace.DuplicateFace(False) if abs(tempFaceBrep.GetArea() - area) > tol*10 or tempGeo.Faces.Count != faceCount: continue tempSrf = tempFace.UnderlyingSurface() rc, tempPlane = tempSrf.FrameAt(tempSrf.Domain(0).Mid, tempSrf.Domain(1).Mid) xForm = Rhino.Geometry.Transform.PlaneToPlane(plane, tempPlane) for newId in newIds: rs.TransformObject(newId, xForm, True) rs.DeleteObject(ID) rs.DeleteObject(targId) rs.EnableRedraw(True)
plane = rs.WorldXYPlane() #��ȡxy��ԭ��Ϊ���ĵIJο�ƽ�� rectangle = rs.AddRectangle(plane,40,40) dpointsCoordinate = rs.DivideCurve(rectangle,10) #�ȷ�10���� dpoints = rs.AddPoints(dpointsCoordinate) #���ӵȷֵ� print(dpoints) format = "point_%s" #��ʽ���ַ�����ģʽ dpointe = [] i = 0 for i in range(len(dpoints)): dpointe.append(format % str(i)) #��ʽ���ַ�������һ�ӵ��б� print(dpointe) dpointx = list(range(len(dpoints))) #�����ȷֵ����� print(dpointx) #��Ƭ���������� selepoints = dpoints[x:y] cubes = [] print(selepoints) for i in range(len(selepoints)): sphere = rs.AddSphere(selepoints[i],3) #��ȡ[y](Բ�ģ��뾶) cube = rs.AddBox(rs.BoundingBox(sphere)) #�����壬plane�� # id = rs.GetObject(sphere) # if id: rs.DeleteObject() xform = rs.XformTranslation([i,i*5,i*5]) #x������ƶ����� trancube = rs.TransformObject(cube,xform) #�ƶ����� cubes.append(trancube) print(cubes)
n = 12 a = 4 m = 6 sh = 10 sr = 0.5 curve = rs.GetObject("Select a curve", 4) #Draw ridge curves ridges = [] dphi = 360.0 / n for k in range(0, n): phi = k * dphi xform = rs.XformRotation2(phi, [0, 0, 1], [0, 0, 0]) ridges.append(rs.TransformObject(curve, xform, True)) #Draw cactus body domain = rs.CurveDomain(curve) sections = [] dt = (domain[1] - domain[0]) / 10 for i in range(0, 10): t = domain[0] + i * dt points = [] xyz = rs.EvaluateCurve(curve, t) R = xyz[0] z = xyz[2] dphi = 2 * ma.pi / 100 for k in range(0, 101): phi = k * dphi x = (R + a * (ma.cos(n * phi) - 1)) * ma.cos(phi)
def make_hinge(num_knuckles, knuckle_height, knuckle_radius, thickness, leaf_length, gap, add_vents): origin = [0, 0, 0] hinge_height = num_knuckles * knuckle_height ###################################################################### # Make pin with caps cap_radius = knuckle_radius - 0.5 * thickness - gap cap_height = thickness cap_bottom = rs.AddCylinder(origin, cap_height, cap_radius) cap_top = rs.AddCylinder([0, 0, hinge_height - cap_height], cap_height, cap_radius) pin_radius = knuckle_radius - (gap + thickness) pin = rs.AddCylinder(origin, hinge_height, pin_radius) pin = rs.BooleanUnion([pin, cap_bottom, cap_top]) ###################################################################### # Make knuckle and holes right_knuckle = rs.AddCylinder(origin, hinge_height, knuckle_radius) knuckle_pin_hole = rs.AddCylinder(origin, hinge_height, knuckle_radius - thickness) knuckle_bottom_hole = rs.AddCylinder(origin, cap_height + gap, cap_radius + gap) knuckle_top_hole = rs.AddCylinder([0, 0, hinge_height - cap_height - gap], cap_height + gap, cap_radius + gap) ###################################################################### # Make leaves right_p0 = (0, knuckle_radius, 0) right_p1 = (leaf_length, knuckle_radius - thickness, hinge_height) right_leaf = rs.AddBox(mz.box_verts_from_corners(right_p0, right_p1)) right_leaf = rs.BooleanUnion([right_knuckle, right_leaf]) right_leaf, = rs.BooleanDifference( [right_leaf], [knuckle_pin_hole, knuckle_bottom_hole, knuckle_top_hole]) mirror_leaf = rs.XformMirror(origin, (1, 0, 0)) left_leaf = rs.TransformObject(right_leaf, mirror_leaf, True) ###################################################################### # Cut out alternating knuckles z0 = 0 sz = knuckle_radius + gap left_boxes = [] right_boxes = [] vent_height = knuckle_height - 4 * thickness for stage in range(num_knuckles): z1 = z0 + knuckle_height if stage == 0: cur_z0 = z0 else: cur_z0 = z0 - 0.5 * gap if stage == num_knuckles - 1: cur_z1 = z1 else: cur_z1 = z1 + 0.5 * gap knuckle_box = rs.AddBox( mz.box_verts_from_corners((-sz, -sz, cur_z0), (sz, sz, cur_z1))) if stage % 2 == 0: left_boxes.append(knuckle_box) else: right_boxes.append(knuckle_box) if add_vents: zmid = z0 + 0.5 * knuckle_height za = zmid - 0.5 * vent_height zb = zmid + 0.5 * vent_height mid_box = rs.AddBox( mz.box_verts_from_corners((-sz, -pin_radius - gap, za), (sz, pin_radius + gap, zb))) if stage % 2 == 0: right_boxes.append(mid_box) else: left_boxes.append(mid_box) z0 += knuckle_height left_leaf, = rs.BooleanDifference([left_leaf], left_boxes) right_leaf, = rs.BooleanDifference([right_leaf], right_boxes) rs.SelectObjects([left_leaf, right_leaf, pin]) rs.Command('MergeAllFaces')
def rotateXZ(theta): rotation = [[math.cos(theta),0, -math.sin(theta),0], [0,1,0,0], [math.sin(theta),0, math.cos(theta),0], [0,0,0,1]] return rotation def stretch(x, y, z): stc = [[x,0,0,0], [0,y,0,0], [0,0,z,0], [0,0,0,1]] return stc phi = 1.61803398875 turn = rotateXY((2*math.pi)/phi) xyRotation = turn copies = 45 for i in range(copies): t = float(i)/float(copies - 1) xzAngle = t*t*(math.pi*9.0/24.0) + math.pi*1.0/24.0 xzRotation = rotateXZ(xzAngle) widen = stretch(1, 1 + t*t*2.5, 1) tsfm = rhino.XformMultiply(xyRotation, xzRotation) tsfm = rhino.XformMultiply(tsfm, widen) new_obj = rhino.TransformObject(obj, tsfm, copy=True) xyRotation = rhino.XformMultiply(xyRotation, turn)
randomRotate = math.acos(random()*math.pi)/2.0 fwdVctr = RhinoScript.VectorTransform(fwdVctr, rotateAroundVector(Rhino.Geometry.Vector3d.CrossProduct(fwdVctr,nodeNormal),randomRotate)) elif c == 'F': #find rotation matrix from old forward vector orthVctr = orthVector(fwdVctr) relativeRotation = RhinoScript.XformMultiply(rotateAroundVector(fwdVctr,turtleRelOr[0]), rotateAroundVector(orthVctr,turtleRelOr[1])) rotationMatrix = RhinoScript.XformMultiply(relativeRotation, rotationMatrix) rotationMatrix = verticalRotate(rotationMatrix, verticality) #find new forward vector from rotation matrix and scale fwdVctr = RhinoScript.VectorTransform(upVctr, rotationMatrix) fwdVctr = RhinoScript.VectorUnitize(fwdVctr) scaleMatrix = ID for i in range(depth): fwdVctr = RhinoScript.VectorScale(fwdVctr, scaleValue) scaleMatrix = RhinoScript.XformMultiply(scaleMatrix, scale(scaleValue)) #add data to transformation stack amalgam = RhinoScript.XformMultiply(translate(turtlePos[0],turtlePos[1],turtlePos[2]), rotationMatrix) amalgam = RhinoScript.XformMultiply(amalgam, scaleMatrix) tsfmStack.append(amalgam) #move turtle forward turtlePos = [turtlePos[0] + fwdVctr.X*length, turtlePos[1] + fwdVctr.Y*length, turtlePos[2] + fwdVctr.Z*length] turtleRelOr = [0,0] #Copy branches into rhino for matrix in tsfmStack: RhinoScript.TransformObject(obj, matrix, True)
def RunCommand( is_interactive ): if sc.escape_test(False): print "script cancelled" #do something print "Resetting..." #******* Get blocks ***********''**** #************************************ objectIds = rs.GetObjects("Pick some blocks", 4096, preselect=True) if not objectIds: print "No objects" return False rs.EnableRedraw(False) #******* Ref Geometry *************** #************************************ points = [ G.Point3d(0,0,0), G.Point3d(1,0,0), G.Point3d(0,1,0), G.Point3d(0,0,1) ] #gather all new objects when done finalObjs = [] for id in objectIds: #Get the block transformation matrix and name blockXForm = rs.BlockInstanceXform(id) blockName = rs.BlockInstanceName(id) #Add reference geometry pts = G.Polyline(points) #Apply block transformation matrix to ref geometry pts.Transform(blockXForm) #create final plane finalOrigin = pts[1] finalXaxis = rs.VectorSubtract( pts[1], pts[0] ) finalYaxis = rs.VectorSubtract( pts[2], pts[0] ) finalPlane = G.Plane(finalOrigin, finalXaxis, finalYaxis) #create scaling factors xFac = 1 / rs.Distance(pts[1],pts[0]) yFac = 1 / rs.Distance(pts[2],pts[0]) zFac = 1 / rs.Distance(pts[3],pts[0]) #Scale block newXForm = G.Transform.Scale(finalPlane, xFac, yFac, zFac) rs.TransformObject(id,newXForm) #Select all new objects rs.SelectObjects(objectIds) rs.EnableRedraw(True) print "...aaand its done." #End RunCommand() #end sane return 0
import rhinoscriptsyntax as rs from Rhino.Geometry import Point3d, Vector3d #lines = rs.GetObjects("Select lines", filter=4) lines = rs.AllObjects() for i in range(len(lines)): p = Point3d(i, 0, 0) v = p - rs.CurveStartPoint(lines[i]) rs.TransformObject(lines[i], rs.XformTranslation(v)) a = rs.Angle(rs.CurveStartPoint(lines[i]), rs.CurveEndPoint(lines[i]))[0] rs.TransformObject(lines[i], rs.XformRotation2(90 - a, Vector3d.ZAxis, p)) start = 1 while start < len(lines): current = start while current > 0 and rs.CurveLength(lines[current - 1]) > rs.CurveLength( lines[current]): rs.TransformObject(lines[current], rs.XformTranslation((-1, 0, 0))) rs.TransformObject(lines[current - 1], rs.XformTranslation((1, 0, 0))) lines[current], lines[current - 1] = lines[current - 1], lines[current] current -= 1 rs.Sleep(500) start += 1
import rhinoscriptsyntax as rs import math as ma n = 12 a = 4 m = 6 sh = 10 sr = 0.5 curve = rs.GetObject("Select a curve", 4) ridges = [] dphi = 360.0 / n for k in range(0, n): phi = k * dphi xform = rs.XformRotation2(phi, [0, 0, 1], [0, 0, 0]) ridges.append(rs.TransformObject(curve, xform, True))
def main(): # get our curves profile, cross = get_two_curves() if profile is None or cross is None: return ################################################## # get bounding box for cross section cross_bbox = rs.BoundingBox([cross]) cmin, cmax = box_to_points(cross_bbox) cz_range = cmax[2] - cmin[2] cz = 0.5 * (cmax[2] + cmin[2]) c_ctr, _ = rs.CurveAreaCentroid(cross) # make sure it's planar in XY if cz_range > 1e-9: print 'cross section curve should be planar in XY plane' return ################################################## # get bounding box for profile profile_bbox = rs.BoundingBox([profile]) # make sure it's planar in in YZ pmin, pmax = box_to_points(profile_bbox) px_range = pmax[0] - pmin[0] if px_range > 1e-9: print 'profile curve should be planar in YZ plane' return ################################################## # get the point closest to the center for the # cross-section curve r, pc = get_inscribed_radius(cross, c_ctr) ################################################## # get the range of z-values for the profile curve _, _, z0 = pmin _, _, z1 = pmax ################################################## # build list of rings and list of points points = [] ring_pipes = [] # for each level for i in range(num_levels): # get the Z value of the ith plane u = float(i) / (num_levels-1) z = z0 + u*(z1 - z0) # build the i'th plane plane = rs.PlaneFromNormal([0, 0, z], [0, 0, 1], [1, 0, 0]) # find out where the plane intersects the profile curve intersect = rs.PlaneCurveIntersection(plane, profile) # there should be exactly one intersection of type 1 (point) if intersect is None or len(intersect) > 1 or intersect[0][0] != 1: print 'bad intersection' return # get the intersection point pi = intersect[0][1] # get the desired XY radius at this z value ri = abs(pi[1]) # we need to set up some transformations: # translate cross section curve down to z=0 T1 = rs.XformTranslation(mz.vec_mul(list(c_ctr), -1.0)) # scale it along XY by the ratio of radii S1 = rs.XformScale([ri/r, ri/r, 1.0]) # scale a piped cross section along Z by a vertical scale factor S2 = rs.XformScale([1.0, 1.0, ring_vscale]) # translate piped cross section up to our desired z value T2 = rs.XformTranslation([0, 0, z]) # scale and translate cross section curve ci = rs.TransformObject(cross, rs.XformMultiply(S1, T1), copy=True) # pipe it ring = rs.AddPipe(ci, [0, 1], [ring_rad, ring_rad]) # scale vertically and transform up ring = rs.TransformObject(ring, rs.XformMultiply(T2, S2)) # delete the copy of the cross section curve rs.DeleteObject(ci) # add to list of ring pipes ring_pipes.append(ring) # create a rotation by the i'th angle angle_i_deg = i*360.0/num_sides Ri = rs.XformRotation2(angle_i_deg, [0, 0, 1], [0, 0, 0]) # transform the closest point by rotation and scale pci = rs.PointTransform(pc, rs.XformMultiply(rs.XformMultiply(Ri, T2), S1)) # add to list of points points.append(pci) # we have built up a list of points for a single spiral of struts to connect, # now we need to pipe them all together and do the ArrayPolar thing around # the z axis # first build a single spiral of struts strut_pipes = [] for i0 in range(num_levels-1): i1 = i0+1 p0 = points[i0] p1 = points[i1] l01 = rs.AddLine(p0, p1) pipe = rs.AddPipe(l01, [0, 1], [strut_rad, strut_rad], cap=2) rs.DeleteObject(l01) strut_pipes.append(pipe) # then array polar around Z axis all_strut_pipes = [] all_strut_pipes += strut_pipes for j in range(1, num_sides): angle_j_deg = j*360.0/num_sides Rj = rs.XformRotation2(angle_j_deg, [0, 0, 1], [0, 0, 0]) all_strut_pipes += rs.TransformObjects(strut_pipes, Rj, copy=True) # now just select all the objects we created rs.SelectObjects(ring_pipes + all_strut_pipes) # done! print 'yay'
import time import rhinoscriptsyntax as rs import scriptcontext as sc import compas_rhino guids = compas_rhino.get_objects() compas_rhino.delete_objects(guids, True) result = rs.AddBox([[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0], [0, 0, 1], [1, 0, 1], [1, 1, 1], [0, 1, 1]]) obj = sc.doc.Objects.Find(result) xform = rs.XformTranslation([0.5, 0, 0]) rs.Redraw() for i in range(10): time.sleep(0.5) rs.TransformObject(obj, xform) rs.Redraw()