def checkIntersection(seg, AS, tolerance): surface_intersection, P, uv, N, t, T = ghc.SurfaceXCurve(AS, seg) if surface_intersection != None: intersect_length = ghc.Length(surface_intersection) original_length = ghc.Length(seg) if (intersect_length > original_length - tolerance) and ( intersect_length < original_length + tolerance): return 1 return 0
def get_footprint(_surfaces): # Finds the 'footprint' of the building for 'Primary Energy Renewable' reference # 1) Re-build the Opaque Surfaces # 2) Join all the surface Breps into a single brep # 3) Find the 'box' for the single joined brep # 4) Find the lowest Z points on the box, offset another 10 units 'down' # 5) Make a new Plane at this new location # 6) Projects the brep edges onto the new Plane # 7) Split a surface using the edges, combine back into a single surface Footprint = namedtuple('Footprint', ['Footprint_surface', 'Footprint_area']) #----- Build brep surfaces = (from_face3d(surface.Srfc) for surface in _surfaces) bldg_mass = ghc.BrepJoin(surfaces).breps bldg_mass = ghc.BoundaryVolume(bldg_mass) if not bldg_mass: return Footprint(None, None) #------- Find Corners, Find 'bottom' (lowest Z) bldg_mass_corners = [v for v in ghc.BoxCorners(bldg_mass)] bldg_mass_corners.sort(reverse=False, key=lambda point3D: point3D.Z) rect_pts = bldg_mass_corners[0:3] #------- Projection Plane projection_plane1 = ghc.Plane3Pt(rect_pts[0], rect_pts[1], rect_pts[2]) projection_plane2 = ghc.Move(projection_plane1, ghc.UnitZ(-10)).geometry matrix = rs.XformPlanarProjection(projection_plane2) #------- Project Edges onto Projection Plane projected_edges = [] for edge in ghc.DeconstructBrep(bldg_mass).edges: projected_edges.append(ghc.Transform(edge, matrix)) #------- Split the projection surface using the curves l1 = ghc.Line(rect_pts[0], rect_pts[1]) l2 = ghc.Line(rect_pts[0], rect_pts[2]) max_length = max(ghc.Length(l1), ghc.Length(l2)) projection_surface = ghc.Polygon(projection_plane2, max_length * 100, 4, 0).polygon projected_surfaces = ghc.SurfaceSplit(projection_surface, projected_edges) #------- Remove the biggest surface from the set(the background srfc) projected_surfaces.sort(key=lambda x: x.GetArea()) projected_surfaces.pop(-1) #------- Join the new srfcs back together into a single one unioned_NURB = ghc.RegionUnion(projected_surfaces) unioned_surface = ghc.BoundarySurfaces(unioned_NURB) return Footprint(unioned_surface, unioned_surface.GetArea())
def RunScript(self, AS, CL): # Initialize outputs S = [] TS = CL W = [] CS = [] # Set defaults if no values are provided D = 1000 # Iterate over each test segment for seg in CL: # Extend line to threshold width midpt, TT, t = ghc.EvaluateLength(seg, 0.5, True) SS, E = ghc.EndPoints(seg) V, L = ghc.Vector2Pt(midpt, SS, False) vect = ghc.Amplitude(V, D/2) G1, X = ghc.Move(midpt, vect) G2, X = ghc.Move(midpt, -vect) test_line = ghc.Line(G1, G2) # Rotate test line 90 degrees test_line, X = ghc.Rotate(test_line, math.pi/2, midpt) # Check for intersection srf_intersection = checkIntersection(test_line, AS, midpt, D) # Store results CS.append(srf_intersection) W.append(ghc.Length(srf_intersection)) # Return outputs return TS, W, CS
def _get_param_values_from_rhino(self, _rhino_objects): """ Looks at Rhino scene to try get Param values from UserText """ if not self._ghdoc: return l, w, t, c = [], [], [], [] with LBT2PH.helpers.context_rh_doc(self._ghdoc): for rhino_obj in _rhino_objects: try: l.append(float(ghc.Length(rhino_obj))) w.append( float( self.get_UserText_with_default( rhino_obj, 'ductWidth', self._duct_width))) t.append( float( self.get_UserText_with_default( rhino_obj, 'insulThickness', self._insulation_thickness))) c.append( float( self.get_UserText_with_default( rhino_obj, 'insulConductivity', self._insulation_lambda))) except: self.Warnings.append( 'No param values found in Rhino. Using GH values or defaults.' ) return l, w, t, c
def set_pipe_lengths(self, _input=[], _ghdoc=None, _ghenv=None): """Will try and find the lengths of the things input Arguments: _input: (float: curve:) If input is number, uses that. Otherwise gets curve from Rhino _ghdoc: (ghdoc) _ghenv: (ghenv) """ output = [] with context_rh_doc( _ghdoc ): for geom_input in _input: try: output.append( float(convert_value_to_metric(geom_input, 'M')) ) except AttributeError as e: crv = rs.coercecurve(geom_input) if crv: pipeLen = ghc.Length(crv) else: pipeLen = False if not pipeLen: crvWarning = "Something went wrong getting the Pipe Geometry length?\n"\ "Please ensure you are passing in only curves / polyline objects or numeric values.?" _ghenv.Component.AddRuntimeMessage(ghK.GH_RuntimeMessageLevel.Warning, crvWarning) else: output.append(pipeLen) self.length = output
def CalcRevealDims(_phpp_window_obj, RevealShaderObjs_input, SideIntersectionSurface, Side_OriginPt, Side_Direction): #Test shading objects for their edge points Side_IntersectionCurve = [] Side_IntersectionPoints = [] for i in range(len(RevealShaderObjs_input)): #This is the list of shading objects to filter if ghc.BrepXBrep(RevealShaderObjs_input[i], SideIntersectionSurface).curves != None: Side_IntersectionCurve.append(ghc.BrepXBrep(RevealShaderObjs_input[i], SideIntersectionSurface).curves) for i in range(len(Side_IntersectionCurve)): for k in range(len(ghc.ControlPoints(Side_IntersectionCurve[i]).points)): Side_IntersectionPoints.append(ghc.ControlPoints(Side_IntersectionCurve[i]).points[k]) #Find the top/closets point for each of the objects that could possibly shade Side_KeyPoints = [] Side_Rays = [] Side_Angles = [] for i in range(len(Side_IntersectionPoints)): if Side_OriginPt != Side_IntersectionPoints[i]: Ray = ghc.Vector2Pt(Side_OriginPt, Side_IntersectionPoints[i], False).vector Angle = math.degrees(ghc.Angle(_phpp_window_obj.surface_normal, Ray).angle) if Angle < 89.9: Side_Rays.append(Ray) Side_Angles.append(float(Angle)) Side_KeyPoints.append(Side_IntersectionPoints[i]) Side_KeyPoint = Side_KeyPoints[Side_Angles.index(min(Side_Angles))] Side_KeyRay = Side_Rays[Side_Angles.index(min(Side_Angles))] #use the Key point found to calculte the Distances for the PHPP Shading Calculator Side_Hypot = ghc.Length(ghc.Line(Side_OriginPt, Side_KeyPoint)) Deg = (ghc.Angle(Side_Direction, Side_KeyRay).angle) #note this is in Radians Side_o_reveal = math.sin(Deg) * Side_Hypot Side_d_reveal = math.sqrt(Side_Hypot**2 - Side_o_reveal**2) Side_CheckLine = ghc.Line(Side_OriginPt, Side_KeyPoint) return [Side_o_reveal, Side_d_reveal, Side_CheckLine]
def TraComp(no, forcePF, forceFG, nome): pontoFG = forceFG.PointAt(.5) movevec = rs.AddLine(rs.CurveEndPoint(forcePF), no) movevec = rs.coerceline(movevec) testeLin = gh.Move(rs.coerceline(forcePF), movevec)[0] dist1 = rs.Distance(testeLin.PointAt(0), pontoFG) dist2 = gh.Length(testeLin) dist2 += (gh.Length(forceFG) / 2) #testando tração if abs(dist1 - dist2) <= Tol: #coloca a nomenclattura do elemento na lista de objetos tracionados Ltrac.append(nome) #retorna 1 para tração return 1 #se compressão else: #coloca a nomenclattura do elemento na lista de objetos comprimidos Lcomp.append(nome) #retorna -1 para compressão return -1
def set_values_by_hb_room(self, _hb_room): """ Finds the Floor-Type face(s) in a Honeybee Room and gets Params Resets self.floor_area and self.floor_U_value based on the values found in the Honeybee Zone. If more than one Floor face is found, creates a weighted U-Value average of all the faces. Args: self: _hb_room: A Single Honeybee Room object Returns: None """ def is_floor(_face): if str(face.type) != 'Floor': return False if str(face.boundary_condition) != 'Ground' and str( face.boundary_condition) != 'Outdoors': return False return True #----------------------------------------------------------------------- # Get all the data from the HB-Room Floor surfaces floor_areas = [] area_weighted_u_values = [] perim_curve_lengths = [] for face in _hb_room: if not is_floor(face): continue u_floor = face.properties.energy.construction.u_factor floor_areas.append(face.area) area_weighted_u_values.append(u_floor * face.area) face_surface = from_face3d(face.geometry) perim_curve = ghc.JoinCurves( list(face_surface.DuplicateEdgeCurves()), False) perim_curve_lengths.append(ghc.Length(perim_curve)) #----------------------------------------------------------------------- # Set the Floor Element params if floor_areas and area_weighted_u_values: self.floor_area = sum(floor_areas) self.floor_U_value = sum(area_weighted_u_values) / sum(floor_areas) self.perim_len = sum(perim_curve_lengths)
def get_params_from_rhino(self, _in): """Got and find any param values in the geometry in the RH Scene Args: _in (Rhino.Geometry.Curve): The Rhino Curve object to look at Returns: (tuple) length, width, thickness, lambda """ with LBT2PH.helpers.context_rh_doc(self.ghdoc): try: l = float(ghc.Length(_in)) w = float(rs.GetUserText(_in, 'ductWidth')) t = float(rs.GetUserText(_in, 'insulThickness')) c = float(rs.GetUserText(_in, 'insulConductivity')) except Exception as e: print('Error getting values from Rhino Scene\n{}'.format(e)) return None, None, None, None return l, w, t, c
def getDuctLength(ductLength_): # Find the Duct length # Takes eiether a list of numbers (panel) # Or a Rhino curve object representing the path of the duct if len(ductLength_) > 0: lengthsList = [] for each in ductLength_: try: # if its a number input, just take that lengthsList.append(float(each)) except: # if it isn't a number, try finding geometry try: crv = rs.coercecurve(each) lengthsList.append(gh.Length(crv)) except: pass lenM = sum(lengthsList) else: lenM = 5 return lenM
def findLength(_inputItem): # takes in an Input object and tries to find the length of it try: length = float(_inputItem) except: try: line = rs.coercecurve(_inputItem) length = ghc.Length(line) except: msgLenError = "Couldn't get the length from the inputs. Please input a Curve or Line for each Thermal Bridge item" ghenv.Component.AddRuntimeMessage( ghK.GH_RuntimeMessageLevel.Warning, msgLenError) return length
def getTotalPipeLength(_branch): temp = [] for geom_input in _branch: try: temp.append(float(geom_input)) except: if isinstance(geom_input, Rhino.Geometry.Curve): crv = rs.coercecurve(geom_input) pipeLen = ghc.Length(crv) else: pipeLen = False if not pipeLen: crvWarning = "Something went wrong getting the Pipe Geometry length?\n"\ "Please ensure you are passing in only curves / polyline objects or numeric values.?" ghenv.Component.AddRuntimeMessage( ghK.GH_RuntimeMessageLevel.Warning, crvWarning) else: temp.append(pipeLen) return temp
crdAux = rs.coerceline(crdAux) pAux2 = pAux pAux = gh.LineXLine(crdAux,vetores[i])[-1] corda = Line(pAux2,pAux) funicular.append(corda) estendeFG(vetores[i],corda,pAux) else: vAux1 = Line(r.PointAt(1),pAux) corda = gh.Move(r,vAux1)[0] corda = rs.coerceline(corda) funicular.append(corda) #testando PF ppara equilíbrio de translação testePF=gh.Length(result) if testePF <= 0.0001: eqtrans = True print "Equilíbrio de Translação" #Testando o Funicular para equilibrio de Rotação #Testando paralelismo das cordas extremas do funicular if testeFunicular(vetores,funicular,0.0001): print "Equilíbrio de Rotação" pAux = gh.LineXLine(funicular[0],vetores[0])[-1] pAux = rs.coerce3dpoint(pAux) funicular[0] = estendeCorda(funicular[0],pAux,0) funicular[-1] = estendeCorda(funicular[-1],pAux,1) else: #Cálculo do Momento
def find_overhang_shading(_phpp_window_obj, _shadingGeom, _extents=99): # Figure out the glass surface (inset a bit) and then # find the origin point for all the subsequent shading calcs (top, middle) glzgCenter = ghc.Area(_phpp_window_obj.glazing_surface).centroid glazingEdges = _phpp_window_obj._get_edges_in_order( _phpp_window_obj.glazing_surface ) glazingTopEdge = from_linesegment3d(glazingEdges.Top) ShadingOrigin = ghc.CurveMiddle(glazingTopEdge) # In order to also work for windows which are not vertical, find the # 'direction' from the glazing origin and the top/middle ege point UpVector = ghc.Vector2Pt(glzgCenter, ShadingOrigin, True).vector #----------------------------------------------------------------------- # First, need to filter the scene to find the objects that are 'above' # the window. Create a 'test plane' that is _extents (99m) tall and 0.5m past the wall surface, test if # any objects intersect that plane. If so, add them to the set of things # test in the next step depth = float(_phpp_window_obj.install_depth) + 0.5 edge1 = ghc.LineSDL(ShadingOrigin, UpVector, _extents) edge2 = ghc.LineSDL(ShadingOrigin, _phpp_window_obj.surface_normal, depth) intersectionTestPlane = ghc.SumSurface(edge1, edge2) OverhangShadingObjs = (x for x in _shadingGeom if ghc.BrepXBrep(intersectionTestPlane, x).curves != None) #----------------------------------------------------------------------- # Using the filtered set of shading objects, find the 'edges' of shading # geom and then decide where the maximums shading point is # Create a new 'test' plane coming off the origin (99m in both directions this time). # Test to find any intersection shading objs and all their crvs/points with this plane HorizontalLine = ghc.LineSDL(ShadingOrigin, _phpp_window_obj.surface_normal, _extents) VerticalLine = ghc.LineSDL(ShadingOrigin, UpVector, _extents) IntersectionSurface = ghc.SumSurface(HorizontalLine, VerticalLine) IntersectionCurves = (ghc.BrepXBrep(obj, IntersectionSurface).curves for obj in OverhangShadingObjs if ghc.BrepXBrep(obj, IntersectionSurface).curves != None) IntersectionPointsList = (ghc.ControlPoints(crv).points for crv in IntersectionCurves) IntersectionPoints = (pt for list_of_pts in IntersectionPointsList for pt in list_of_pts) #----------------------------------------------------------------------- # If there are any intersection Points found, choose the right one to use to calc shading.... # Find the top/closets point for each of the objects that could possibly shade smallest_angle_found = 2 * math.pi key_point = None for pt in IntersectionPoints: if pt == None: continue # Protect against Zero-Length error ray = ghc.Vector2Pt(ShadingOrigin, pt, False).vector if ray.Length < 0.001: continue this_ray_angle = ghc.Angle(_phpp_window_obj.surface_normal , ray).angle if this_ray_angle < 0.001: continue if this_ray_angle <= smallest_angle_found: smallest_angle_found = this_ray_angle key_point = pt #----------------------------------------------------------------------- # Use the 'key point' found to deliver the Height and Distance for the PHPP Shading Calculator if not key_point: d_over = None o_over = None CheckLine = VerticalLine else: d_over = key_point.Z - ShadingOrigin.Z # Vertical distance Hypot = ghc.Length(ghc.Line(ShadingOrigin, key_point)) # Hypot o_over = math.sqrt(Hypot**2 - d_over**2) # Horizontal distance CheckLine = ghc.Line(ShadingOrigin, key_point) return d_over, o_over, CheckLine
def fractal(depth, x1, y1, z1, x2, y2, z2, length, anglerec, angle, lvariation, aran, lran, anglerech, angleh, branches, verticality, gchance, depthstart, radtolen, radchng, mngon, polygon, branch_cluster): #test if depth>0 if depth: #defining random angle variation and length variation arn = random.uniform(-angle / 100 * aran, angle / 100 * aran) lrn = random.uniform(-length / 100 * lran, length / 100 * lran) if hrandom == True: #defining horizontal rotation angles ahor = random.sample(range(0, 360), branches) #removing numbers within tolerance ahr = rs.CullDuplicateNumbers(ahor, angleh) #in a 360 fashion if ahr[0] + 360 - angleh < ahr[-1]: del ahr[0] else: #generating evenly distributed angles ahr = range(0, 360 + 1, 360 // branches)[:-1] #previous branch vector vecst = rg.Point3d(x1, y1, z1) vecend = rg.Point3d(x2, y2, z2) movevec = ghc.Vector2Pt(vecst, vecend, True)[0] #returns vector and it's length #perpendicular vector rotplane3 = ghc.PlaneNormal( vecend, movevec) #creates plane perpendicular to vector plns = ghc.DeconstructPlane(rotplane3) #origin, x, y, z rotplane = ghc.ConstructPlane( plns[2], plns[1], plns[3] ) #constructing new plane switching x and y planes to make perpendicular #generating perpendicular vector vecperp = ghc.Rotate(movevec, radians(90), rotplane)[0] #generating vector amplitudes leny = (length + lrn) * sin( radians((anglerec + arn) * (1 - (verticality**depth)))) lenz = (length + lrn) * cos(radians(anglerec + arn)) ampy = ghc.Amplitude(vecperp, leny) ampz = ghc.Amplitude(movevec, lenz) #changing branch length dependant on branch depth length = length * lvariation #building points endpoint1 = ghc.Move( vecend, ampz)[0] #returns moved object and transformation data endpoint = ghc.Move( endpoint1, ampy)[0] #returns moved object and transformation data #rotating point in a cone fashion rotpoint = ghc.Rotate3D( endpoint, radians(anglerech), vecend, movevec)[0] #returns rotated geometry and transformation data #building line between points linegeo = rg.Line(vecend, rotpoint) #defining recursion depth key = depthstart + 1 - depth #building geometry pln = ghc.PlaneNormal(rotpoint, linegeo) #returns a plane perp to a vector radius = length * (radchng**(key)) / radtolen #reduce details with each branch, but not less than 3 splits = 3 if mngon - key + 1 <= 3 else mngon - key + 1 polygonend = ghc.Polygon(pln, radius, splits, 0)[0] #returns a polygon and its perimeter #aligning curves for loft creation crvst = ghc.EndPoints(polygon)[0] pntcld = ghc.Discontinuity(polygonend, 1) #returns points and point parameters #finind seam point closest_point = ghc.ClosestPoint( crvst, pntcld[0] ) #returns closest point, closest point index, distance between closest points seampnt = pntcld[1][closest_point[1]] polygonend = ghc.Seam(polygonend, seampnt) lcurves = [polygon, polygonend] #building geometry geo = ghc.ExtrudePoint( polygon, rotpoint ) if depth == 1 and splits == 3 else rg.Brep.CreateFromLoft( lcurves, rg.Point3d.Unset, rg.Point3d.Unset, rg.LoftType.Normal, False)[0] #if last branch than make a pyramid #make solid geocapped = ghc.CapHoles(geo) #building a dict of geo with depth as key, and geo as values pgons.update( {branch_cluster: [geocapped]}) if branch_cluster not in pgons.keys( ) else pgons[branch_cluster].append(geocapped) branchesout.append(geocapped) #setting coords for next branch x1 = x2 y1 = y2 z1 = z2 #getting xyz from rotated point x2 = rg.Point3d(rotpoint)[0] y2 = rg.Point3d(rotpoint)[1] z2 = rg.Point3d(rotpoint)[2] #setting base polygon for next branch polygon = polygonend #filling dict with branch clusters cluster.append(cluster[-1] + 1) branch_cluster = cluster[-1] #calling function with different angle parameter for branch splitting, calling as many branches as spread within tolerance if depth != 1: for aa in ahr: if ( (random.randint(40, 99) / 100)**depth ) < gchance or depth == depthstart + 1: #or added to prevent blank trees fractal(depth - 1, x1, y1, z1, x2, y2, z2, length, angle, angle, lvariation, aran, lran, aa, angleh, branches, verticality, gchance, depthstart, radtolen, radchng, mngon, polygon, branch_cluster) #leaf logic if depth <= leavesdepth and leavesperbranch > 0 and maxleaves > 0: #vector for leaf growth spread leafpntvec = ghc.Vector2Pt(vecend, rotpoint, True)[0] #setting leaf growth position on last barnch, leafpnt list lastbranchlength = ghc.Length(linegeo) leaves_list = [lastbranchlength] [ leaves_list.append(lengthparam) for lengthparam in random.sample( range(0, int(lastbranchlength)), leavesperbranch - 1) ] if leavesperbranch > 1 else None for leafpnt in leaves_list: leafamp = ghc.Amplitude(leafpntvec, leafpnt) leafpoint = ghc.Move(vecend, leafamp)[0] #plane for leaf generation linetocenter = ghc.Line(stpntbase, leafpoint) planetocenter = ghc.PlaneNormal(leafpoint, linetocenter) #create an imaginary circle with leaflen radius and populate it with points for random leaf generation leafgenerationcircle = ghc.CircleCNR(leafpoint, linetocenter, leaflen) circlesurf = ghc.BoundarySurfaces(leafgenerationcircle) leafcnt = random.randint(0, maxleaves) if leafcnt > 0: leafendpnts = ghc.PopulateGeometry(circlesurf, leafcnt, random.randint(1, 500)) def leafgenerator(point): #random z move zmove = rg.Vector3d(0, 0, 1) moveamp = random.uniform(-leaflen / 3, leaflen / 5) ampzmove = ghc.Amplitude(zmove, moveamp) llendpnt = ghc.Move(point, ampzmove)[0] #setting a leaf centerline vector leafvector = ghc.Vector2Pt(leafpoint, llendpnt, True)[0] #defining leaf center point as avarage of st and end pnts midpnt = ghc.Average([leafpoint, llendpnt]) #generating perpendicular vector vecperpleaf = ghc.Rotate(leafvector, radians(90), planetocenter)[0] leafperpamp = ghc.Amplitude( vecperpleaf, random.uniform((leafwidth / 2) / 5 * 4, (leafwidth / 2) / 5 * 6)) #moving mid point to both sides midpnt1 = ghc.Move(midpnt, leafperpamp)[0] midpnt2 = ghc.Move(midpnt, -leafperpamp)[0] #leaf geo leafgeo = rg.NurbsSurface.CreateFromCorners( leafpoint, midpnt1, llendpnt, midpnt2) leaves.append(leafgeo) #iterate over random number of generated points if list, else generate for one point [leafgenerator(pp) for pp in leafendpnts] if isinstance( leafendpnts, list) else leafgenerator(leafendpnts)
def getPipe_FromRhino(_pipeObj, _i): # If its a numeric input, just return that as the length and the rest as blank try: return float(_pipeObj), None, None, None, None except: pass # Otherwise, try and pull the required info from the Rhino scene # Note, in order to keep the component's Type-Hint as 'No Type Hint' so that # I can input either crvs or numbers, need to get the Rhino GUID using the # Compo.Params.Input method below. try: rhinoGuid = ghenv.Component.Params.Input[0].VolatileData[0][ _i].ReferenceID.ToString() pipeLen = ghc.Length(rs.coercecurve(_pipeObj)) except: rhinoGuid = None pipeLen = None with rhDoc(): if pipeLen and rhinoGuid: try: conductivity = float( rs.GetUserText(rhinoGuid, 'insulation_conductivity')) reflective = rs.GetUserText(rhinoGuid, 'insulation_reflective') thickness = rs.GetUserText(rhinoGuid, 'insulation_thickness') diam = rs.GetUserText(rhinoGuid, 'pipe_diameter') diam, thickness = cleanPipeDimInputs(diam, thickness) return pipeLen, diam, thickness, conductivity, reflective except: msg = "Note: I could not find any parameters assigned to the pipe geometry in the Rhino Scene.\n"\ "Be sure that you enter parameter information for the diam, thickness, etc... in the component here.\n"\ "------\n"\ "If you did assign information to the curves in the Rhino scene, be sure to use an 'ID' component\n"\ "BEFORE you pass those curves into the 'pipe_geom_' input." ghenv.Component.AddRuntimeMessage( ghK.GH_RuntimeMessageLevel.Remark, msg) return pipeLen, None, None, None, None else: msg = "Something went wrong getting the Curve length?\n"\ "Be sure you are passing in a curve / polyline object or a number to the 'pipe_geom_'?" ghenv.Component.AddRuntimeMessage( ghK.GH_RuntimeMessageLevel.Warning, msg) return None, None, None, None, None
def distParalela(reta1,reta2): pt1 = gh.EndPoints(reta1)[0] pt2 = reta2.ClosestPoint(pt1,False) return gh.Length(Line(pt1,pt2))
def set_perim_edge_values(self, _crv_guids, _ud_psi): """Pulls Rhino Scene parameters for a list of Curve Objects Takes in a list of curve GUIDs and goes to Rhino. Looks in their UserText to get any user applied parameter data. Calculates the sum of all curve lengths (m) in the list, as well as the total Psi-Value * Length (W/m) of all curves in the list. Will return tuple(0, 0) on any trouble getting parameter values or any fails Args: self: _perimCrvs (list): A list of Curve GUIDs to look at in the Rhino Scene Returns: totalLen, psiXlen (tuple): The total length of all curves in the list (m) and the total Psi*Len value (W/m) """ def _getLengthIfNumber(_in, _psi): try: length = float(_in) except: length = None try: psi = float(_psi) except: psi = self.default_perim_psi return length, psi if _crv_guids == None: return None if len(_crv_guids) == 0: return None psiXlen = 0 totalLen = 0 for crvGUID in _crv_guids: # See if its just Numbers passed in. If so, use them and break out length, crvPsiValue = _getLengthIfNumber(crvGUID, _ud_psi) if length and crvPsiValue: totalLen += length psiXlen += (length * crvPsiValue) continue isCrvGeom = rs.coercecurve(crvGUID) isBrepGeom = rs.coercebrep(crvGUID) if isCrvGeom: crvLen = ghc.Length(isCrvGeom) try: crvPsiValue = float(_ud_psi) except: crvPsiValue, warning = self._get_curve_psi_value(crvGUID) totalLen += crvLen psiXlen += (crvLen * crvPsiValue) elif isBrepGeom: srfcEdges = ghc.DeconstructBrep(isBrepGeom).edges srfcPerim = ghc.JoinCurves(srfcEdges, False) crvLen = ghc.Length(srfcPerim) try: crvPsiValue = float(_ud_psi) except: crvPsiValue = self.default_perim_psi # Default 0.05 W/mk warning = 'Note: You passed in a surface without any Psi-Values applied.\n'\ 'I will apply a default {} W/mk Psi-Value to ALL the edges of the\n'\ 'surface passed in.'.format( self.default_perim_psi ) self.ghenv.Component.AddRuntimeMessage( ghK.GH_RuntimeMessageLevel.Warning, warning) totalLen += crvLen psiXlen += (crvLen * crvPsiValue) else: warning = 'Error in GROUND: Input into _exposedPerimCrvs is not a Curve or Surface?\n'\ 'Please ensure inputs are Curve / Polyline or Surface only.' self.ghenv.Component.AddRuntimeMessage( ghK.GH_RuntimeMessageLevel.Warning, warning) self.perim_len = totalLen self.perim_psi_X_len = psiXlen
def getTBfromRhino(_tbEdges, _tbLib, _unames, _ulengths, _uPsiVals): """Looks at the edges passed in and tries to pull relevant params from Rhino Will look for in the Edge's UserText and try and get the 'Typename' and 'Group' will also look for any DocumentUserText TB libraries and get params based on the object's 'Typename' Will also allow for user-override by passing values into the GH Component directly for names, lengths and Psi-Values """ tbGeom_ = [] tbLens_ = [] tbNames_ = [] tbPsiVals_ = [] tbGroups_ = [] tbrfRSIs_ = [] with rhDoc(): for i, edge in enumerate(_tbEdges): # Get the params from the Rhino Object crv = rs.coercecurve(edge) tbLen = ghc.Length(crv) nm = rs.GetUserText(edge, 'Typename') grp = rs.GetUserText(edge, 'Group') if nm not in _tbLib.keys(): msg = "Can not find the values for TB: '{}' in the file library?\n"\ "Check the file's DocumentUserText and make sure the name is correct?".format( nm) ghenv.Component.AddRuntimeMessage( ghK.GH_RuntimeMessageLevel.Warning, msg) # Get the params from the DocUserTxt Library params = _tbLib.get(nm, None) psiVal = params.get('psiValue', 0.01) if params != None else 0.01 fRSI = params.get('fRsi', None) if params != None else None # Get user input params try: nm = _unames[i] except: pass try: tbLen = _ulengths[i] except: pass try: psiVal = _uPsiVals[i] except: pass # Add params to the output lists tbNames_.append(nm if nm != None else 'TB_{:0>2d}'.format(i + 1)) tbLens_.append(tbLen) tbGroups_.append(grp.split(':')[0] if grp != None else 15) # default = 15: Ambient tbGeom_.append(crv if crv != None else edge) tbPsiVals_.append(psiVal) tbrfRSIs_.append(fRSI) return tbNames_, tbLens_, tbPsiVals_, tbGeom_, tbGroups_, tbrfRSIs_
R_v1 = rs.AddLine(pAux, pto_inicial_2) #reação R_V2 no PF pAux3 = dic_2['P0_v2'].PointAt(1) R_v2 = rs.AddLine(pAux3, pAux) #Colocando reações no dicionário do PF dic_2['R_v1'] = rs.coerceline(R_v1) dic_2['R_v2'] = rs.coerceline(R_v2) #Colocando reações na lista de saida resultante_2 resultante_2 += [pAux3, R_v1, R_v2] #movendo reações para o FG vAux1 = rs.AddLine(pto_inicial_2, pto1) vAux2 = rs.AddLine(pAux, pto2) fgR_v1 = gh.Move(rs.coerceline(R_v1), rs.coerceline(vAux1))[0] fgR_v2 = gh.Move(rs.coerceline(R_v2), rs.coerceline(vAux2))[0] #Nomenclatura R_v1 carga1 = gh.Length(fgR_v1) * 1 / Escala p_txt = fgR_v1.PointAt(.5) texto = 'R_v1 = ' + str('%.2f' % carga1) txt_pontos += [p_txt, texto, corcargas] #Nomenclatura R_v2 carga2 = gh.Length(fgR_v2) * 1 / Escala p_txt = fgR_v2.PointAt(.5) texto = 'R_v2 = ' + str('%.2f' % carga2) txt_pontos += [p_txt, texto, corcargas] #Colocando reações na lista de saida do FG FG2.append(fgR_v1) FG2.append(fgR_v2) print '####--------------------V1-----------------------####' dicUp, ptos = Grafo_Viga(v1, carreg_v1, Plano, dic_2, cirDir, Conector[1], fgR_v1, 'v1') txt_pontos += ptos
def find_horizon_shading(_phpp_window_obj, _shadingGeom, _extents=99): """ Arguments: _phpp_winddow_obj: The PHPP_Window object to calcualte the values for _shadingGeom: (list) A list of possible shading objects to test against _extents: (float) A number (m) to limit the shading search to. Default = 99m Returns: h_hori: Distance (m) out from the glazing surface of any horizontal shading objects found d_hori: Distance (m) up from the base of the window to the top of any horizontal shading objects found """ surface_normal = _phpp_window_obj.surface_normal #----------------------------------------------------------------------- # Find Starting Point glazingEdges = _phpp_window_obj._get_edges_in_order( _phpp_window_obj.glazing_surface ) glazingBottomEdge = glazingEdges.Bottom ShadingOrigin = ghc.CurveMiddle( from_linesegment3d(glazingBottomEdge) ) UpVector = ghc.VectorXYZ(0,0,1).vector #----------------------------------------------------------------------- # Find if there are any shading objects and if so put them in a list HorizonShading = [] HorizontalLine = ghc.LineSDL(ShadingOrigin, surface_normal, _extents) VerticalLine = ghc.LineSDL(ShadingOrigin, UpVector, _extents) for shadingObj in _shadingGeom: if ghc.BrepXCurve(shadingObj, HorizontalLine).points != None: HorizonShading.append( shadingObj ) #----------------------------------------------------------------------- # Find any intersection Curves with the shading objects IntersectionSurface = ghc.SumSurface(HorizontalLine, VerticalLine) IntersectionCurve = [] IntersectionPoints = [] for shadingObj in HorizonShading: if ghc.BrepXBrep(shadingObj, IntersectionSurface).curves != None: IntersectionCurve.append(ghc.BrepXBrep(shadingObj, IntersectionSurface)) for pnt in IntersectionCurve: IntersectionPoints.append(ghc.ControlPoints(pnt).points) #----------------------------------------------------------------------- # Run the "Top-Corner-Finder" if there are any intersecting objects... if len(IntersectionPoints) != 0: # Find the top/closets point for each of the objects that could possibly shade KeyPoints = [] for pnt in IntersectionPoints: Rays = [] Angles = [] if pnt: for k in range(len(pnt)): Rays.append(ghc.Vector2Pt(ShadingOrigin,pnt[k], False).vector) Angles.append(ghc.Angle(surface_normal , Rays[k]).angle) KeyPoints.append(pnt[Angles.index(max(Angles))]) # Find the relevant highest / closest point Rays = [] Angles = [] for i in range(len(KeyPoints)): Rays.append(ghc.Vector2Pt(surface_normal, KeyPoints[i], False).vector) Angles.append(ghc.Angle(surface_normal, Rays[i]).angle) KeyPoint = KeyPoints[Angles.index(max(Angles))] # Use the point it finds to deliver the Height and Distance for the PHPP Shading Calculator h_hori = KeyPoint.Z - ShadingOrigin.Z #Vertical distance Hypot = ghc.Length(ghc.Line(ShadingOrigin, KeyPoint)) d_hori = math.sqrt(Hypot**2 - h_hori**2) CheckLine = ghc.Line(ShadingOrigin, KeyPoint) else: h_hori = None d_hori = None CheckLine = HorizontalLine return h_hori, d_hori, CheckLine