Esempio n. 1
0
def CreateCubeStrut(csdname, csdwidth, csdlength, csdheight, csdstart,
                    csdrotation, scdthickness):
    #print(csdname)
    vector = XYZ(0, 0, csdheight * -1)
    pp = Plane.CreateByNormalAndOrigin(vector, csdstart)

    trans = Transform.CreateRotationAtPoint(vector, csdrotation, csdstart)

    point1 = csdstart + XYZ(csdwidth / 2, csdlength / 2, 0)
    point2 = csdstart + XYZ(csdwidth / 2 * -1, csdlength / 2, 0)
    point3 = csdstart + XYZ(csdwidth / 2 * -1, csdlength / 2 * -1, 0)
    point4 = csdstart + XYZ(csdwidth / 2, csdlength / 2 * -1, 0)

    profileorigion = CurveLoop().Create([
        Line.CreateBound(point1, point2),
        Line.CreateBound(point2, point3),
        Line.CreateBound(point3, point4),
        Line.CreateBound(point4, point1)
    ])

    finalProfile = CurveLoop.CreateViaTransform(profileorigion, trans)
    geo = GeometryCreationUtilities.CreateExtrusionGeometry([finalProfile],
                                                            vector, csdheight)
    ele = DirectShape.CreateElement(doc, ElementId(-2000151))
    ele.SetShape([geo])
    ele.SetName(csdname)
    return ele.Id
Esempio n. 2
0
 def lines(self):
     """Создает линии по граням региона"""
     p1, p2, p3, p4 = self.to_xyz(self.corners)
     elem = {
         'top': Line.CreateBound(p1, p2),
         'right': Line.CreateBound(p2, p3),
         'left': Line.CreateBound(p4, p1),
         'bottom': Line.CreateBound(p3, p4)
     }
     return elem
 def create_curveloop(self, points):
     cl = CurveLoop.Create([])
     prev_point = None
     for point in points:
         if prev_point is None:
             cl.Append(Line.CreateBound(points[-1], points[0]))
         else:
             cl.Append(Line.CreateBound(prev_point, point))
         prev_point = point
     return cl
Esempio n. 4
0
 def create_longest_lines(self, lines):
     """Делаем из поданных линий максимально длинную.
     
     """
     all_points = self.all_lines_points(lines)
     p1, p2 = self.max_distance(all_points)
     return Line.CreateBound(p1, p2)
Esempio n. 5
0
def connect_to():
    # Prompt user to select elements and points to connect
    try:
        with forms.WarningBar(title="Pick element to move and connect"):
            reference = uidoc.Selection.PickObject(ObjectType.Element, NoInsulation(), "Pick element to move")
    except Exceptions.OperationCanceledException:
        return False

    try:
        moved_element = doc.GetElement(reference)
        moved_point = reference.GlobalPoint
        with forms.WarningBar(title="Pick element to be connected to"):
            reference = uidoc.Selection.PickObject(ObjectType.Element, NoInsulation(),
                                                   "Pick element to be connected to")
        target_element = doc.GetElement(reference)
        target_point = reference.GlobalPoint
    except Exceptions.OperationCanceledException:
        return True

    # Get associated unused connectors
    moved_connector = get_connector_closest_to(get_connector_manager(moved_element).UnusedConnectors,
                                               moved_point)
    target_connector = get_connector_closest_to(get_connector_manager(target_element).UnusedConnectors,
                                                target_point)
    try:
        if moved_connector.Domain != target_connector.Domain:
            rpw.ui.forms.Alert("You picked 2 connectors of different domain. Please retry.", header="Domain Error")
            return True
    except AttributeError:
        rpw.ui.forms.Alert("It looks like one of the objects have no unused connector", header="AttributeError")
        return True

    # Retrieves connectors direction and catch attribute error like when there is no unused connector available
    try:
        moved_direction = moved_connector.CoordinateSystem.BasisZ
        target_direction = target_connector.CoordinateSystem.BasisZ
    except AttributeError:
        rpw.ui.forms.Alert("It looks like one of the objects have no unused connector", header="AttributeError")
        return True

    # Move and connect
    with rpw.db.Transaction("Connect elements"):
        # If connector direction is same, rotate it
        angle = moved_direction.AngleTo(target_direction)
        if angle != pi:
            if angle == 0:
                vector = moved_connector.CoordinateSystem.BasisY
            else:
                vector = moved_direction.CrossProduct(target_direction)
            try:
                line = Line.CreateBound(moved_point, moved_point+vector)
                moved_element.Location.Rotate(line, angle - pi)
            # Revit don't like angle and distance too close to 0
            except Exceptions.ArgumentsInconsistentException:
                logger.debug("Vector : {} ; Angle : {}".format(vector, angle))
        # Move element in order match connector position
        moved_element.Location.Move(target_connector.Origin - moved_connector.Origin)
        # Connect connectors
        moved_connector.ConnectTo(target_connector)
    return True
Esempio n. 6
0
def create_gird(scoord,
                ecoord,
                name_gird
                ):
    # context-like objects that guard any 
    # changes made to a Revit model
    t = Transaction(doc, "Create grids")

    # Starts the transaction.
    t.Start()

    # create line reference 
    line_ref = Line.CreateBound(scoord, ecoord)

    # create gird  
    grid_ins = Grid.Create(doc, line_ref)

    # retrieve name for gird 
    name = grid_ins.get_Parameter(BuiltInParameter.DATUM_TEXT)

    # set name for gird 
    name.Set(name_gird)

    # Commits all changes made 
    # to the model during the transaction.
    t.Commit()
Esempio n. 7
0
    def create_widnow_for_panel(self, panel_dict, panel_params, panel=None):
        """
        Создать окна в панели.
        """
        for i in panel_dict['components']['componentRefs']:
            window_type = self.all_windows[i["id"]]
            symb = self.window_family[window_type[0]]
            add_point = XYZ(i['point']['x'], i['point']['y'], i['point']['z']) / 304.8
            c_window = self.doc.Create.NewFamilyInstance(
                add_point,
                symb,
                self.default_level,
                StructuralType.Column)
            c_window = Precast_window(c_window, doc=self.doc, panel=panel)
            c_window["Рзм.Ширина"] = i["length"] / 304.8
            new_point = c_window.element.Location.Point
            new_point = new_point + XYZ(i["length"] / 304.8 / 2, 0, 0)
            # new_point = new_point + XYZ(i["length"] / 304.8 / 2, 0, 0)
            c_window.element.Location.Point = new_point
            axis = Line.CreateBound(c_window.element.Location.Point, c_window.element.Location.Point + XYZ(0,0,10))
            c_window.element.Location.Rotate(axis, math.pi)
            if window_type[1] == "left":
                plane = Plane.CreateByNormalAndOrigin(XYZ(1,0,0), c_window.element.Location.Point)
                new_win = ElementTransformUtils.MirrorElement(self.doc, c_window.element.Id, plane)

                self.doc.Delete(c_window.element.Id)
Esempio n. 8
0
    def add_offset(self, lines, offset):
        """Добавляем отступ линии
        
        """
        new_lines = []
        for line in lines:
            points = [line.GetEndPoint(0), line.GetEndPoint(1)]
            for point_pos in range(0, 2):
                point = points[point_pos]
                faces = set()
                for face in self.room_faces:
                    plane = face.GetSurface()
                    project_point = plane.Project(point)
                    # echo(project_point)
                    if project_point:
                        if project_point[1] < self.tollerance:
                            faces.add(face)
                normal_sum = XYZ(0, 0, 0)
                for face in faces:
                    normal_sum += face.ComputeNormal(UV())
                if abs(normal_sum.X) > 0.0001: dev_x = abs(normal_sum.X)
                else: dev_x = 1
                if abs(normal_sum.Y) > 0.0001: dev_y = abs(normal_sum.Y)
                else: dev_y = 1

                normal_sum = XYZ(normal_sum.X / dev_x, normal_sum.Y / dev_y, 0)
                point -= normal_sum * offset
                points[point_pos] = point
            new_lines.append(Line.CreateBound(points[0], points[1]))
        return new_lines
Esempio n. 9
0
def create_dimension(element, point1, point2, reference_names_list, view, direction_to_move=XYZ(0, 0, 0)):
    line = Line.CreateBound(point1, point2)
    refArray = ReferenceArray()
    for ref in reference_names_list:
        refArray.Append(element.GetReferenceByName(ref))
    dim = doc.Create.NewDimension(view, line, refArray)
    ElementTransformUtils.MoveElement(doc, dim.Id, direction_to_move)
    return dim
 def point_intersect_solid(self, point, solid, vect):
     "Проверяет пересекает ли точка по заданному вектору солид."
     # point = self.transform.OfPoint(point)
     line = Line.CreateBound(point + vect * self.height / 3,
                             point - vect * self.height / 3)
     res = solid.element.IntersectWithCurve(line,
                                            SolidCurveIntersectionOptions())
     return res.SegmentCount
Esempio n. 11
0
 def line_z_to_curview(self, line):
     """Обнуляет координату Z у линии."""
     z = curview.Origin.Z
     p1 = line.GetEndPoint(0)
     p2 = line.GetEndPoint(1)
     p1 = XYZ(p1.X, p1.Y, z)
     p2 = XYZ(p2.X, p2.Y, z)
     return Line.CreateBound(p1, p2)
Esempio n. 12
0
def xyz_axis(element_id):
    """Input : Element, Output : xyz axis of the element
    :type element_id: ElementId
    """
    transform = doc.GetElement(element_id).GetTransform()
    axis = [
        Line.CreateBound(transform.Origin,
                         transform.Origin + transform.Basis[i])
        for i in range(3)
    ]
    return axis
Esempio n. 13
0
    def get_line_styles(self):
        """Function to get available LineStyles for DetaiLines."""
        # CREATE TEMP LINE
        t = Transaction(doc, "temp - Create DetailLine")
        t.Start()
        new_line         = Line.CreateBound(XYZ(0,0,0), XYZ(1,1,0))
        random_line      = doc.Create.NewDetailCurve(active_view, new_line)
        line_styles_ids  = random_line.GetLineStyleIds()
        t.RollBack()

        line_styles = [doc.GetElement(line_style) for line_style in line_styles_ids]
        return line_styles
Esempio n. 14
0
def rotate_element(elem, degrees_to_rotate):
    #>>>>>>>>>> GET CENTER POINT
    bounding_box = elem.get_BoundingBox(doc.ActiveView)
    point = (bounding_box.Min + bounding_box.Max) / 2

    #>>>>>>>>>> AXIS LINE
    axis_line = Line.CreateBound(
        point, point + XYZ.BasisZ)  #fixme will not rotate 2D in secitons

    #>>>>>>>>>> ROTATE
    ElementTransformUtils.RotateElement(doc, elem.Id, axis_line,
                                        math.radians(degrees_to_rotate))
Esempio n. 15
0
 def print_line(cls, p1, p2, plane=None, radius=0.3, color='еленая'):
     doc = __revit__.ActiveUIDocument.Document
     active_view = doc.ActiveView
     creDoc = __revit__.ActiveUIDocument.Document.Create
     if not plane:
         vect = p2 - p1
         p3 = p1 + XYZ_multiply(active_view.ViewDirection, vect).Normalize()
         plane = Plane.CreateByThreePoints(p1, p2, p3)
     sketchPlane = SketchPlane.Create(doc, plane)
     new_line = Line.CreateBound(p1, p2)
     m_line = creDoc.NewModelCurve(new_line, sketchPlane)
     m_line.LineStyle = cls.get_line_style(color=color)
     return m_line
Esempio n. 16
0
 def protect(self):
     """Определяет нужен ли защитный слой данному региону."""
     if self._protect is None:
         self._protect = {'top': 0, 'left': 0, 'bottom': 0, 'right': 0}
         if not self.is_hole:
             all_points = self.to_xyz(self.corners)
             pos = {}
             pos['top'] = Line.CreateBound(all_points[0], all_points[1])
             pos['right'] = Line.CreateBound(all_points[1], all_points[2])
             pos['bottom'] = Line.CreateBound(all_points[3], all_points[2])
             pos['left'] = Line.CreateBound(all_points[0], all_points[3])
             for el in pos.keys():
                 done = False
                 for cl in self.face.GetEdgesAsCurveLoops():
                     if done:
                         break
                     for line in cl:
                         res = line.Intersect(pos[el])
                         if res != SetComparisonResult.Disjoint and res != SetComparisonResult.Overlap and res != SetComparisonResult.Subset:
                             self._protect[el] = self.protect_length
                             done = True
                             break
     return self._protect
Esempio n. 17
0
def get_solid_extrusion_from_bbox(bbox):
    solid_opt = SolidOptions(ElementId.InvalidElementId,
                             ElementId.InvalidElementId)
    b1 = XYZ(bbox.Min.X, bbox.Min.Y, bbox.Min.Z)
    b2 = XYZ(bbox.Max.X, bbox.Min.Y, bbox.Min.Z)
    b3 = XYZ(bbox.Max.X, bbox.Max.Y, bbox.Min.Z)
    b4 = XYZ(bbox.Min.X, bbox.Max.Y, bbox.Min.Z)
    bbox_height = bbox.Max.Z - bbox.Min.Z

    lines = List[Curve]()
    lines.Add(Line.CreateBound(b1, b2))
    lines.Add(Line.CreateBound(b2, b3))
    lines.Add(Line.CreateBound(b3, b4))
    lines.Add(Line.CreateBound(b4, b1))
    rectangle = [CurveLoop.Create(lines)]

    extrusion = GeometryCreationUtilities.CreateExtrusionGeometry(
        List[CurveLoop](rectangle),
        XYZ.BasisZ,
        bbox_height,
        solid_opt,
    )
    return extrusion
Esempio n. 18
0
 def line_trimming(self, lines):
     """Обрезка линий, которые выступают друг за друга
     
      формируем линии путем попытки пересечения их.
      Если линии пересекается с другими два раза
      два пересечения и есть точки этой линии
      
      если линия пересекается один раз. То ближняя точка заменяется 
      той, которая пересеклась
      
      если линия не пересекается - оставляем без изменений
     
     """
     new_lines = []
     for line_1 in lines:
         new_points = list()
         p1 = line_1.GetEndPoint(0)
         p2 = line_1.GetEndPoint(1)
         for line_2 in lines:
             intersect_result = StrongBox[IntersectionResultArray]()
             intersect_result_text = line_1.Intersect(
                 line_2, intersect_result)
             intersect_result = intersect_result.Value
             if intersect_result_text == SetComparisonResult.Overlap and intersect_result:
                 for i in intersect_result:
                     new_points.append(i.XYZPoint)
         if len(new_points) == 2:
             new_lines.append(Line.CreateBound(new_points[0],
                                               new_points[1]))
         elif len(new_points) == 1:
             if p1.DistanceTo(new_points[0]) > p2.DistanceTo(new_points[0]):
                 new_lines.append(Line.CreateBound(p1, new_points[0]))
             else:
                 new_lines.append(Line.CreateBound(p2, new_points[0]))
         else:
             new_lines.append(line_1)
     return new_lines
Esempio n. 19
0
    def get_new_line(self, line_1, line_2):

        cp1 = line_1.GetEndPoint(0)
        cp2 = line_1.GetEndPoint(1)
        p1 = line_2.GetEndPoint(0)
        p2 = line_2.GetEndPoint(1)

        line_1_unbound = line_1.Clone()
        line_1_unbound.MakeUnbound()
        line_2_unbound = line_2.Clone()
        line_2_unbound.MakeUnbound()

        inter_res = StrongBox[IntersectionResultArray]()
        inter_res_text = line_1_unbound.Intersect(line_2_unbound, inter_res)
        if inter_res_text == SetComparisonResult.Overlap:
            inter_point = next(iter(inter_res)).XYZPoint
            if cp1.DistanceTo(
                    inter_point) < self.tollerance and cp2.DistanceTo(
                        inter_point) > self.tollerance:
                return Line.CreateBound(cp2, inter_point)
            elif cp2.DistanceTo(
                    inter_point) < self.tollerance and cp1.DistanceTo(
                        inter_point) > self.tollerance:
                return Line.CreateBound(cp1, inter_point)
Esempio n. 20
0
def element_selection():
    try:
        with forms.WarningBar(title="Pick reference element"):
            reference = uidoc.Selection.PickObject(ObjectType.Element,
                                                   "Pick reference element")
    except Exceptions.OperationCanceledException:
        return False

    try:
        element1 = doc.GetElement(reference)
        with forms.WarningBar(title="Pick target element"):
            reference = uidoc.Selection.PickObject(ObjectType.Element,
                                                   "Pick target element")
        element2 = doc.GetElement(reference)

        logger.debug("ELEMENTS \n 1: {} \n 2: {}".format(element1, element2))

        v1 = direction(element1)
        v2 = direction(element2)

        xy_v1 = XYZ(v1.X, v1.Y, 0)  # type: XYZ
        xy_v2 = XYZ(v2.X, v2.Y, 0)  # type: XYZ

        angle = xy_v2.AngleTo(xy_v1)
        if angle > pi / 2:
            angle = angle - pi
        normal = xy_v2.CrossProduct(xy_v1)

        logger.debug("ANGLE : {}".format(angle))
        logger.debug("NORMAL : {}".format(normal))
        logger.debug("DIRECTION \n 1: {} \n 2: {}".format(
            direction(element1), direction(element2)))

        axis = Line.CreateBound(origin(element2), origin(element2) + normal)

        # Need to rotate elevation marker if it is an elevation
        try:
            if get_view_from(element2).ViewType == ViewType.Elevation:
                element2 = get_elevation_marker(element2)
        except AttributeError:
            pass

        with rpw.db.Transaction("Make parallel", doc):
            element2.Location.Rotate(axis, angle)

        return True
    except Exceptions.OperationCanceledException:
        return True
Esempio n. 21
0
 def project_line_on_plane(cls, line, origin=None, normal=None, plane=None):
     p1 = line.GetEndPoint(0)
     p1 = cls.project_on_plane(p1,
                               origin=origin,
                               normal=normal,
                               plane=plane)
     p2 = line.GetEndPoint(1)
     p2 = cls.project_on_plane(p2,
                               origin=origin,
                               normal=normal,
                               plane=plane)
     # echo(p1.IsAlmostEqualTo(p2))
     if not p1.IsAlmostEqualTo(p2):
         try:
             return Line.CreateBound(p1, p2)
         except:
             pass
Esempio n. 22
0
def CreateDimensions(filledRegion, dimensionDirection):
    document = filledRegion.Document
    view = filledRegion.Document.GetElement(filledRegion.OwnerViewId)
    edgesDirection = dimensionDirection.CrossProduct(view.ViewDirection)
    edges = []
    for x in FindRegionEdges(filledRegion):
        if IsEdgeDirectionSatisfied(x, edgesDirection):
            edges.append(x)
    if len(edges) < 2:
        return
    shift = UnitUtils.ConvertToInternalUnits(
        -10 * view.Scale, DisplayUnitType.DUT_MILLIMETERS) * edgesDirection
    dimensionLine = Line.CreateUnbound(
        filledRegion.get_BoundingBox(view).Min + shift, dimensionDirection)
    references = ReferenceArray()
    for edge in edges:
        references.Append(edge.Reference)
    document.Create.NewDimension(view, dimensionLine, references)
Esempio n. 23
0
    def make_loops(self):
        start_x = self.start_x
        start_y = self.start_y
        end_x = start_x + self.width
        end_y = start_y + self.height
        p1 = XYZ(start_x, start_y, 0.0)
        p2 = XYZ(end_x, start_y, 0.0)
        p3 = XYZ(end_x, end_y, 0.0)
        p4 = XYZ(start_x, end_y, 0.0)
        p5 = XYZ(start_x, start_y, 0.0)
        points = [p1, p2, p3, p4, p5]

        profileloop = CurveLoop()
        profileloops = List[CurveLoop]()

        for n, p in enumerate(points):
            try:
                line = Line.CreateBound(points[n], points[n + 1])
            except:
                continue
            else:
                profileloop.Append(line)
        try:
            profileloops.Add(profileloop)
        except Exception as errmsg:
            dialog('Something wrong processing points: {}'.format(self.points))
            # ADD LOGGER
            logger.error('width: {}'.format(self.width))
            logger.error('height: {}'.format(self.height))
            logger.error('start_x: {}'.format(start_x))
            logger.error('start_y: {}'.format(start_y))
            for n, point in enumerate(points):
                logger.error('Point {}:{}'.format(n, point))

        # Defines Location for Label and Value Label
        label_x = start_x - self.label_padding
        label_y = start_y + (self.height / 2)
        value_label_x = start_x + self.width + self.label_padding
        value_label_y = label_y
        self.label_pt = XYZ(label_x, label_y, 0)
        self.value_label_pt = XYZ(value_label_x, value_label_y, 0)

        return profileloops
Esempio n. 24
0
 def filled_Region(self, factor, fill):
     BB = self.element.get_BoundingBox(self.view)
     pt1X = (BB.Min[0] - factor) if BB.Min[1] > 0 else (BB.Min[0] - factor)
     pt1Y = (BB.Min[1] - factor) if BB.Min[1] > 0 else (BB.Min[1] - factor)
     pt3X = (BB.Max[0] + factor) if BB.Max[0] > 0 else (BB.Max[0] + factor)
     pt3Y = (BB.Max[1] + factor) if BB.Max[1] > 0 else (BB.Max[1] + factor)
     #Points
     pt1 = XYZ(pt1X, pt1Y, 0)
     pt2 = XYZ(pt1X, pt3Y, 0)
     pt3 = XYZ(pt3X, pt3Y, 0)
     pt4 = XYZ(pt3X, pt1Y, 0)
     start = [pt1, pt2, pt3, pt4]
     end = [pt2, pt3, pt4, pt1]
     #CurveLoop
     lines = []
     for i, j in zip(start, end):
         L = Line.CreateBound(i, j)
         if L:
             lines.append(L)
     curveloop = CurveLoop.Create(lines)
     outRegion = FilledRegion.Create(doc, fill.Id, self.view.Id,
                                     [curveloop])
Esempio n. 25
0
 def Trace(self, factor, line_style):
     BB = self.element.get_BoundingBox(self.view)
     """Expand Boundry Box by Factor"""
     pt1X = (BB.Min[0] - factor) if BB.Min[1] > 0 else (BB.Min[0] - factor)
     pt1Y = (BB.Min[1] - factor) if BB.Min[1] > 0 else (BB.Min[1] - factor)
     pt3X = (BB.Max[0] + factor) if BB.Max[0] > 0 else (BB.Max[0] + factor)
     pt3Y = (BB.Max[1] + factor) if BB.Max[1] > 0 else (BB.Max[1] + factor)
     """Points"""
     pt1 = XYZ(pt1X, pt1Y, 0)
     pt2 = XYZ(pt1X, pt3Y, 0)
     pt3 = XYZ(pt3X, pt3Y, 0)
     pt4 = XYZ(pt3X, pt1Y, 0)
     if (abs(BB.Max[0]) - abs(BB.Min[0])) > (abs(BB.Max[1]) -
                                             abs(BB.Min[1])):
         start = [pt1, pt2]
         end = [pt4, pt3]
     else:
         start = [pt1, pt3]
         end = [pt2, pt4]
     """Create Line"""
     lines = []
     for i, j in zip(start, end):
         L = Line.CreateBound(i, j)
         doc.Create.NewDetailCurve(self.view, L).LineStyle = line_style
Esempio n. 26
0
                    print('1')
                    t = Transaction(doc, 'Correct Lines 1')
                    t.Start()
                    doc.Delete(line.Id)
                    print('Deletion of excess successful')
                    t.Commit()
# Scenario 2
                elif (CloseNumber(proj_start.X, line_start.X) \
                        and CloseNumber(proj_start.Y, line_start.Y))\
                        and (not CloseNumber(proj_end.X, line_end.X) \
                        or not CloseNumber(proj_end.Y, line_end.Y)):
                    print('2')
                    t = Transaction(doc, 'Correct Lines 2')
                    t.Start()
                    try:
                        newLine = Line.CreateBound(proj_end, line_end)
                        line.SetGeometryCurve(newLine, True)
                        print('Correction Successful')
                    except:
                        print("Wall" + format(outprint.linkify(wall.Id)))
                        print("Line" + format(outprint.linkify(line.Id)))
                    t.Commit()
# Scenario 4
                elif (CloseNumber(proj_end.X, line_end.X) \
                     and CloseNumber(proj_end.Y, line_end.Y)) \
                     and (not CloseNumber(proj_start.X, line_start.X) \
                     or not CloseNumber(proj_start.Y, line_start.Y)):
                    print('3')
                    t = Transaction(doc, 'Correct Lines 3')
                    t.Start()
                    try:
Esempio n. 27
0
doc = revit.doc
uidoc = revit.uidoc

selection = FilteredElementCollector(doc).OfCategory(
    BuiltInCategory.OST_Levels).WhereElementIsNotElementType()

# All reference in reference will be dimensioned
reference_array = ReferenceArray()

options = Options(ComputeReferences=True, IncludeNonVisibleObjects=True)

for element in selection:
    reference_array.Append(Reference(element))

crvs = []

ends = []

for element in selection:
    crvs.extend(
        element.GetCurvesInView(DatumExtentType.ViewSpecific, doc.ActiveView))

for crv in crvs:
    ends.append(crv.GetEndPoint(0))

line = Line.CreateBound(ends[0], ends[-1])

with rpw.db.Transaction("QuickDimensionPipe"):
    # logger.debug([reference for reference in reference_array])
    dim = doc.Create.NewDimension(doc.ActiveView, line, reference_array)
Esempio n. 28
0
def get_intersection(line1, line2):
    results = clr.Reference[IntersectionResultArray]()
    # See ironpython.net/documentation/dotnet for clr.Reference

    result = line1.Intersect(line2, results)
    # http://www.revitapidocs.com/2018/51961478-fb36-e00b-2d1b-7db27b0a09e6.htm

    if result != SetComparisonResult.Overlap:
        print('No Intesection')

    intersection = results.Item[0]
    return intersection.XYZPoint


line1 = Line.CreateBound(XYZ(0, 0, 0), XYZ(10, 0, 0))
line2 = Line.CreateBound(XYZ(5, -5, 0), XYZ(5, 5, 0))
point = get_intersection(line1, line2)
print(point)
# <Autodesk.Revit.DB.XYZ object at 0x00000000000001BA [(5.000000000, 0.000000000, 0.000000000)]>
"""
From this discussion:
https://forum.dynamobim.com/t/translating-to-python/13481

C# Equivalent

private XYZ GetIntersection(
  Line line1,
  Line line2 )
{
  IntersectionResultArray results;
Esempio n. 29
0
from pyrevit import revit, DB

__context__ = 'selection'
__doc__ = 'Randomly rotates selected elements.'

# reference the current open revit model to work with:
doc = __revit__.ActiveUIDocument.Document

# get selected element
selection = revit.get_selection()
elements = selection.elements

degrees_to_rotate = 45.0
# Convert the user input from degrees to radians.
converted_value = float(degrees_to_rotate) * (math.pi / 180.0)

# entering a transaction to modify the revit model database
# start transaction
tx = Transaction(doc, "check type against parameter value")
tx.Start()

for element in elements:
    origin = element.Location.Point
    line_z = Line.CreateBound(origin, XYZ(origin.X, origin.Y, origin.Z + 1))
    ElementTransformUtils.RotateElement(doc, element.Id, line_z,
                                        random.uniform(0, (math.pi * 2)))

# commit the changes to the revit model database
# end transaction
tx.Commit()
Esempio n. 30
0
def SignedDistanceTo(plane, p):
    v = p - plane.Origin
    return plane.Normal.DotProduct(v)

def project_onto(plane, p):
    d = SignedDistanceTo(plane, p)
    q = p - d * plane.Normal
    return q

general_mark = RB_selections.pick_element_by_class(IndependentTag)
taggets = RB_selections.pick_elements_by_class(IndependentTag)
if taggets and general_mark:
    plane = Plane.CreateByNormalAndOrigin(active_view.ViewDirection, active_view.Origin)

    middle = project_onto(plane, general_mark.LeaderElbow)
    head = project_onto(plane, general_mark.TagHeadPosition)
    point = project_onto(plane, general_mark.LeaderEnd)

    vect = (point - middle).Normalize()
    l1 = Line.CreateUnbound(head, (middle - head).Normalize())
    with Transaction(doc, "Выровнять марки") as t:
        t.Start()
        for i in taggets:
            tag_point = project_onto(plane, i.LeaderEnd)
            l2 = Line.CreateUnbound(tag_point, vect)
            inter = StrongBox[IntersectionResultArray]()
            l1.Intersect(l2, inter)
            new_middle = list(inter.Value)[0].XYZPoint
            i.LeaderElbow = new_middle
            i.TagHeadPosition = head
        t.Commit()