Beispiel #1
0
def add_door_right(room_, side_):
    line = QLineF(room_.topRight(), room_.bottomRight())

    line_lenght = int(line.length())
    step = line_lenght / 100.

    line_points = []
    for t in np.arange(0.25, 0.75, step):
        line_point = line.pointAt(t)
        line_points.append(QPointF(line_point.x(), line_point.y()))

    random_center_door = random.choice(line_points)

    left_door = QPointF(random_center_door.x(), random_center_door.y() - 0.5)
    right_door = QPointF(random_center_door.x(), random_center_door.y() + 0.5)

    if side_ == 'bottom':
        polygon = QPolygonF([
            right_door,
            room_.topRight(),
            room_.topLeft(),
            room_.bottomLeft(),
            room_.bottomRight(), left_door
        ])

    elif side_ == 'top':
        polygon = QPolygonF([
            right_door,
            room_.bottomRight(),
            room_.bottomLeft(),
            room_.topLeft(),
            room_.topRight(), left_door
        ])

    return polygon
Beispiel #2
0
def add_door_center(room_):
    line = QLineF(room_.topLeft(), room_.topRight())
    line_lenght = int(
        line.length()
    )  # -1 sin pasillo, 0 antes de la primera habitacion, 1 antes de la segunda

    step = line_lenght / 100.

    line_points = []
    for t in np.arange(0.25, 0.75, step):
        line_point = line.pointAt(t)
        line_points.append(QPointF(line_point.x(), line_point.y()))

    random_center_door = random.choice(line_points)

    left_door = QPointF(random_center_door.x() - 0.5, random_center_door.y())
    right_door = QPointF(random_center_door.x() + 0.5, random_center_door.y())

    polygon = QPolygonF([
        right_door,
        room_.topRight(),
        room_.bottomRight(),
        room_.bottomLeft(),
        room_.topLeft(), left_door
    ])

    return polygon
Beispiel #3
0
 def try_to_append_point(self, p_abs):
     p: QPointF = p_abs - self.pos()
     if len(self.points) > 0:
         line = QLineF(self.points[-1], p)
         if line.length() < 0.5:
             return False
     self.points.append(p)
     return True
Beispiel #4
0
    def _draw_reticle(self):
        if self._reticle is None or (self._reticle.size() != self.size()):
            self._new_reticle()

            dbm_lines = [
                QLineF(self._hz_to_x(self._low_frequency), self._dbm_to_y(dbm),
                       self._hz_to_x(self._high_frequency),
                       self._dbm_to_y(dbm))
                for dbm in numpy.arange(self._low_dbm, self._high_dbm, 20.0)
            ]
            dbm_labels = [
                (dbm,
                 QPointF(
                     self._hz_to_x(self._low_frequency) + 2,
                     self._dbm_to_y(dbm) - 2))
                for dbm in numpy.arange(self._low_dbm, self._high_dbm, 20.0)
            ]

            frequency_lines = [
                QLineF(self._hz_to_x(frequency),
                       self._dbm_to_y(self._high_dbm),
                       self._hz_to_x(frequency), self._dbm_to_y(self._low_dbm))
                for frequency in
                numpy.arange(self._low_frequency, self._high_frequency,
                             self._frequency_step * 20.0)
            ]
            frequency_labels = [(frequency,
                                 QPointF(
                                     self._hz_to_x(frequency) + 2,
                                     self._dbm_to_y(self._high_dbm) + 10))
                                for frequency in numpy.arange(
                                    self._low_frequency, self._high_frequency,
                                    self._frequency_step * 10.0)]

            painter = QtGui.QPainter(self._reticle)
            try:
                painter.setRenderHint(QtGui.QPainter.Antialiasing)

                painter.setPen(Qt.blue)

                # TODO: Removed to support old (<1.0) PySide API in Ubuntu 10.10
                #painter.drawLines(dbm_lines)
                for dbm_line in dbm_lines:
                    painter.drawLine(dbm_line)
                # TODO: Removed to support old (<1.0) PySide API in Ubuntu 10.10
                #painter.drawLines(frequency_lines)
                for frequency_line in frequency_lines:
                    painter.drawLine(frequency_line)

                painter.setPen(Qt.white)
                for dbm, point in dbm_labels:
                    painter.drawText(point, '%+.0f' % dbm)
                for frequency, point in frequency_labels:
                    painter.drawText(point,
                                     '%.02f' % (old_div(frequency, 1e6)))

            finally:
                painter.end()
Beispiel #5
0
 def _set_line_and_border(self):
     if self._vertical:
         self._bounding_rect = QRectF(-self._width / 2, self._start,
                                      self._width, self._length)
         self._line = QLineF(0, self._start, 0, self._start + self._length)
     else:
         self._bounding_rect = QRectF(self._start, -self._width / 2,
                                      self._length, self._width)
         self._line = QLineF(self._start, 0, self._start + self._length, 0)
 def drawArrow(self):
     line = QLineF(self._edge2, self.__destPoint)
     v = line.unitVector()
     v.setLength(12)
     v.translate(QPointF(line.dx(), line.dy()))
     n = v.normalVector()
     n.setLength(n.length() * 0.5)
     n2 = n.normalVector().normalVector()
     p1 = v.p2()
     p2 = n.p2()
     p3 = n2.p2()
     return QPolygonF([p1, p2, p3, p1])
Beispiel #7
0
    def append_point(self, posF_in_view: QPointF) -> bool:
        """Only used for active drawing.
        Appends a point (floating, in viewport coordinates),
        if the distance to the last one isn't oo small"""

        p: QPointF = (self.viewport_pos + posF_in_view) - self.pos()

        if len(self.points) > 0:
            line = QLineF(self.points[-1], p)
            if line.length() < 0.5:
                return False

        self.points.append(p)
        return True
Beispiel #8
0
def get_intersection_points(rect1, rect2):
    r1_tl = rect1.topLeft()
    r1_tr = rect1.topRight()
    r1_br = rect1.bottomRight()
    r1_bl = rect1.bottomLeft()

    r2_tl = rect2.topLeft()
    r2_tr = rect2.topRight()
    r2_br = rect2.bottomRight()
    r2_bl = rect2.bottomLeft()

    sec_list1 = []
    sec_list2 = []

    sec_list1.append(QLineF(r1_tl, r1_bl))
    sec_list1.append(QLineF(r1_tl, r1_tr))
    sec_list1.append(QLineF(r1_tr, r1_br))
    sec_list1.append(QLineF(r1_br, r1_bl))

    sec_list2.append(QLineF(r2_tl, r2_bl))
    sec_list2.append(QLineF(r2_tl, r2_tr))
    sec_list2.append(QLineF(r2_tr, r2_br))
    sec_list2.append(QLineF(r2_br, r2_bl))

    for i in range(len(sec_list1)):
        for r in range(len(sec_list2)):
            if sec_list1[i].intersect(
                    sec_list2[r]
            )[0] == QLineF.IntersectType.BoundedIntersection:
                print('intersects')
                print(sec_list1[i].intersect(sec_list2[r])[1].x(),
                      sec_list1[i].intersect(sec_list2[r])[1].y())
Beispiel #9
0
 def try_to_append_point(self, p_abs):
     # p: QPointF = self.mapToScene(self.pos()) + (p_viewport-self.pos())
     # print('---------------------------')
     # print(p)
     # print(p_viewport)
     # print(self.pos())
     # print(self.mapToScene(self.pos()))
     # print('---------------------------')
     p: QPointF = p_abs - self.pos()
     if len(self.points) > 0:
         line = QLineF(self.points[-1], p)
         if line.length() < 0.5:
             return False
     self.points.append(p)
     return True
Beispiel #10
0
    def paintEvent(self, ev):
        """
        Manually implemented paint event

        :param ev: the QT paint event
        :return:
        """
        h = self.height()
        w = self.width()
        p = QPainter(self)
        p.setClipRect(ev.region().boundingRect())
        pen = QPen(QColor(0, 0, 0))
        pen.setWidth(4)
        ls = QFontMetricsF(p.font()).lineSpacing()
        for idx, t in enumerate(sorted(list(self._loadData.keys()))):
            y = 10 + idx * ls
            pen.setColor(ThreadToColor.singleton.get(t))
            p.setPen(pen)
            p.drawLine(QLineF(15, y, 15 + 15, y))
            pen.setColor(QColor(0, 0, 0))
            p.setPen(pen)
            p.drawText(QPointF(35, y), t)

        if len(self._loadData) > 0:
            right = max([
                polygon[polygon.count() - 1].x()
                for _, polygon in self._loadData.items()
            ])
        else:
            right = 0.0
        p.translate(w - 10 - right * 20, h - 10)
        p.scale(
            20, -(h - 20)
        )  # x direction: 20 pixels per second, y direction: spread between 10 and h-10
        topleft = p.transform().inverted()[0].map(QPointF(10, 10))
        pen.setWidthF(0)
        pen.setCosmetic(True)
        left = topleft.x()
        p.setRenderHint(QPainter.Antialiasing, True)
        p.setPen(pen)
        p.drawLine(QLineF(left, 0, right, 0))
        p.drawLine(QLineF(left, 0, left, 1))
        idx = 0
        for t, polygon in self._loadData.items():
            pen.setColor(ThreadToColor.singleton.get(t))
            p.setPen(pen)
            p.drawPolyline(polygon)
        p.end()
Beispiel #11
0
    def set_line(self, max_value=0, resize=False):
        height = self._parent.size().height() + self._top + self._bottom
        shift = int(height - height / 1.1)
        y = -self._top + shift

        if not self._is_upload:
            value = 0
            max_value = int(max_value / 1.1)
            megabyte = 1024 * 1024
            if max_value > megabyte:
                value = "{} MB".format(round(max_value / megabyte, 1))
            elif max_value > 1024:
                max_value //= 1024
                if max_value >= 10:
                    max_value = max_value // 10 * 10
                value = "{} KB".format(max_value)
            elif max_value > 0:
                if max_value >= 10:
                    max_value = max_value // 10 * 10
                value = "{} B".format(max_value)
            scale_text =  self._text_start if not value \
                else "{}{}/s".format(self._text_start, value)

            font_height = QFontMetrics(self._text_item.font())\
                .boundingRect(scale_text).height()
            x = 10
            self._text_item.setPos(x, y - font_height - 10)
            self._text_item.setPlainText(scale_text)

        if not resize:
            return

        self._line.setLine(QLineF(0, y, self._parent.size().width() + 30, y))
 def setSelectedUnit(self, selected_cp: QMapControlPoint):
     self.state = QLiberationMapState.MOVING_UNIT
     self.selected_cp = selected_cp
     position = self._transform_point(selected_cp.control_point.position)
     self.movement_line = QtWidgets.QGraphicsLineItem(
         QLineF(QPointF(*position), QPointF(*position)))
     self.scene().addItem(self.movement_line)
Beispiel #13
0
 def testDrawOverloads(self):
     '''Calls QPainter.drawLines overloads, if something is
        wrong Exception and chaos ensues. Bug #395'''
     self.painter.drawLines([QLine(QPoint(0,0), QPoint(1,1))])
     self.painter.drawLines([QPoint(0,0), QPoint(1,1)])
     self.painter.drawLines([QPointF(0,0), QPointF(1,1)])
     self.painter.drawLines([QLineF(QPointF(0,0), QPointF(1,1))])
     self.painter.drawPoints([QPoint(0,0), QPoint(1,1)])
     self.painter.drawPoints([QPointF(0,0), QPointF(1,1)])
     self.painter.drawConvexPolygon([QPointF(10.0, 80.0),
                                     QPointF(20.0, 10.0),
                                     QPointF(80.0, 30.0),
                                     QPointF(90.0, 70.0)])
     self.painter.drawConvexPolygon([QPoint(10.0, 80.0),
                                     QPoint(20.0, 10.0),
                                     QPoint(80.0, 30.0),
                                     QPoint(90.0, 70.0)])
     self.painter.drawPolygon([QPointF(10.0, 80.0),
                               QPointF(20.0, 10.0),
                               QPointF(80.0, 30.0),
                               QPointF(90.0, 70.0)])
     self.painter.drawPolygon([QPoint(10.0, 80.0),
                               QPoint(20.0, 10.0),
                               QPoint(80.0, 30.0),
                               QPoint(90.0, 70.0)])
     self.painter.drawPolyline([QPointF(10.0, 80.0),
                                QPointF(20.0, 10.0),
                                QPointF(80.0, 30.0),
                                QPointF(90.0, 70.0)])
     self.painter.drawPolyline([QPoint(10.0, 80.0),
                                QPoint(20.0, 10.0),
                                QPoint(80.0, 30.0),
                                QPoint(90.0, 70.0)])
    def mouseMoveEvent(self, event):
        pos = event.scenePos()
        x = pos.x()
        y = pos.y()

        if self.mode == 'cursor':
            # Get items on cursor
            message = '(x, y)=({x}, {y}) '.format(x=int(x), y=int(y))
            for img in self.img_contents:
                # Get pixel value
                pix_val = img.pixel(x, y)
                pix_rgb = QColor(pix_val).getRgb()
                message += '(R, G, B) = {RGB} '.format(RGB=pix_rgb[:3])

            # show scene status on parent's widgets status bar
            self.window.statusBar().showMessage(message)

        if self.mode == 'pen' or self.mode == 'eraser':
            if x >= 0 and x < self.width() and y >= 0 and y < self.height():
                if len(self.points) != 0:
                    draw_color = self.window.draw_color
                    # Set transparenc value
                    draw_color.setAlpha(self.window.layer_alpha)
                    draw_size = self.window.draw_tool_size
                    pen = QPen(draw_color, draw_size, Qt.SolidLine,
                               Qt.RoundCap, Qt.RoundJoin)
                    self.line_items.append(
                        self.addLine(QLineF(self.points[-1].x(),
                                            self.points[-1].y(), x, y),
                                     pen=pen))
                    self.lines.append(self.line_items[-1].line())
                    self.pens.append(pen)

                self.points.append(pos)
Beispiel #15
0
    def moveObject(self, object, pos):

        if object is self.__endsCapture[0]:
            line = QLineF(pos, self.line().p2())
            self.__blockMove = True
            self.setLine(line)
            self.__updateTextLinePos()
            self.__blockMove = False
            return
        if object is self.__endsCapture[1]:
            line = QLineF(self.line().p1(), pos)
            self.__blockMove = True
            self.setLine(line)
            self.__updateTextLinePos()
            rect = self.collidingItems()
            self.__blockMove = False
            return
Beispiel #16
0
 def _radius_from_point_and_angle(self, point, angle):
     line = QLineF()
     line.setP1(point)
     line.setAngle(angle)
     normal = line.normalVector()
     normal.setLength(self.magic_number / 2)
     return QPointF(normal.dx(), normal.dy())
Beispiel #17
0
 def _handle_execution_animation_value_changed(self, step):
     gradient = QLinearGradient(self.src_center, self.dst_center)
     delta = 8 * self.magic_number / QLineF(self.src_center, self.dst_center).length()
     gradient.setColorAt(0, self._color)
     gradient.setColorAt(max(0.0, step - delta), self._color)
     gradient.setColorAt(step, self._exec_color)
     gradient.setColorAt(min(1.0, step + delta), self._color)
     gradient.setColorAt(1.0, self._color)
     self.setBrush(gradient)
Beispiel #18
0
    def sceneMouseMovedEvent(self, event: QGraphicsSceneMouseEvent):
        if self.game is None:
            return

        mouse_position = Point(event.scenePos().x(), event.scenePos().y())
        if self.state == QLiberationMapState.MOVING_UNIT:
            self.setCursor(Qt.PointingHandCursor)
            self.movement_line.setLine(
                QLineF(self.movement_line.line().p1(), event.scenePos())
            )

            if self.is_valid_ship_pos(mouse_position):
                self.movement_line.setPen(CONST.COLORS["green"])
            else:
                self.movement_line.setPen(CONST.COLORS["red"])

        mouse_world_pos = self._scene_to_dcs_coords(mouse_position)
        if DisplayOptions.navmeshes.blue_navmesh:
            self.highlight_mouse_navmesh(
                self.scene(),
                self.game.blue_navmesh,
                self._scene_to_dcs_coords(mouse_position),
            )
            if DisplayOptions.path_debug.shortest_path:
                self.draw_shortest_path(
                    self.scene(), self.game.blue_navmesh, mouse_world_pos, player=True
                )

        if DisplayOptions.navmeshes.red_navmesh:
            self.highlight_mouse_navmesh(
                self.scene(), self.game.red_navmesh, mouse_world_pos
            )

        debug_blue = DisplayOptions.path_debug_faction.blue
        if DisplayOptions.path_debug.shortest_path:
            self.draw_shortest_path(
                self.scene(),
                self.game.navmesh_for(player=debug_blue),
                mouse_world_pos,
                player=False,
            )
        elif not DisplayOptions.path_debug.hide:
            if DisplayOptions.path_debug.barcap:
                task = FlightType.BARCAP
            elif DisplayOptions.path_debug.cas:
                task = FlightType.CAS
            elif DisplayOptions.path_debug.sweep:
                task = FlightType.SWEEP
            elif DisplayOptions.path_debug.strike:
                task = FlightType.STRIKE
            elif DisplayOptions.path_debug.tarcap:
                task = FlightType.TARCAP
            else:
                raise ValueError("Unexpected value for DisplayOptions.path_debug")
            self.draw_test_flight_plan(
                self.scene(), task, mouse_world_pos, player=debug_blue
            )
    def reload_scene(self):
        scene = self.scene()
        scene.clear()

        playerColor = self.game.get_player_color()
        enemyColor = self.game.get_enemy_color()

        self.addBackground()

        # Display Culling
        if DisplayOptions.culling and self.game.settings.perf_culling:
            self.display_culling(scene)

        for cp in self.game.theater.controlpoints:

            pos = self._transform_point(cp.position)

            scene.addItem(
                QMapControlPoint(self, pos[0] - CONST.CP_SIZE / 2,
                                 pos[1] - CONST.CP_SIZE / 2, CONST.CP_SIZE,
                                 CONST.CP_SIZE, cp, self.game_model))

            if cp.captured:
                pen = QPen(brush=CONST.COLORS[playerColor])
                brush = CONST.COLORS[playerColor + "_transparent"]
            else:
                pen = QPen(brush=CONST.COLORS[enemyColor])
                brush = CONST.COLORS[enemyColor + "_transparent"]

            self.draw_ground_objects(scene, cp)

            if cp.target_position is not None:
                proj = self._transform_point(cp.target_position)
                scene.addLine(
                    QLineF(QPointF(pos[0], pos[1]), QPointF(proj[0], proj[1])),
                    QPen(CONST.COLORS["green"], width=10, s=Qt.DashDotLine))

        for cp in self.game.theater.enemy_points():
            if DisplayOptions.lines:
                self.scene_create_lines_for_cp(cp, playerColor, enemyColor)

        for cp in self.game.theater.player_points():
            if DisplayOptions.lines:
                self.scene_create_lines_for_cp(cp, playerColor, enemyColor)

        self.draw_flight_plans(scene)

        for cp in self.game.theater.controlpoints:
            pos = self._transform_point(cp.position)
            text = scene.addText(cp.name, font=CONST.FONT_MAP)
            text.setPos(pos[0] + CONST.CP_SIZE, pos[1] - CONST.CP_SIZE / 2)
            text = scene.addText(cp.name, font=CONST.FONT_MAP)
            text.setDefaultTextColor(Qt.white)
            text.setPos(pos[0] + CONST.CP_SIZE + 1,
                        pos[1] - CONST.CP_SIZE / 2 + 1)
Beispiel #20
0
    def __init__(self, parent, api_obj, diagramScene):
        """

        :param parent:
        :param api_obj:
        """
        super(ShuntGraphicItem, self).__init__(parent)

        self.w = 15.0
        self.h = 30.0

        self.parent = parent

        self.api_object = api_obj

        self.diagramScene = diagramScene

        self.width = 4

        if self.api_object is not None:
            if self.api_object.active:
                self.style = ACTIVE['style']
                self.color = ACTIVE['color']
            else:
                self.style = DEACTIVATED['style']
                self.color = DEACTIVATED['color']
        else:
            self.style = OTHER['style']
            self.color = OTHER['color']

        pen = QPen(self.color, self.width, self.style)

        # Properties of the container:
        self.setFlags(self.ItemIsSelectable | self.ItemIsMovable)
        # self.setCursor(QCursor(Qt.PointingHandCursor))

        # line to tie this object with the original bus (the parent)
        self.nexus = QtWidgets.QGraphicsLineItem()
        self.nexus.setPen(QPen(self.color, self.width, self.style))
        parent.scene().addItem(self.nexus)

        self.lines = list()
        self.lines.append(QLineF(QPointF(self.w / 2, 0), QPointF(self.w / 2, self.h * 0.4)))
        self.lines.append(QLineF(QPointF(0, self.h * 0.4), QPointF(self.w, self.h * 0.4)))
        self.lines.append(QLineF(QPointF(0, self.h * 0.6), QPointF(self.w, self.h * 0.6)))
        self.lines.append(QLineF(QPointF(self.w / 2, self.h * 0.6), QPointF(self.w / 2, self.h)))
        self.lines.append(QLineF(QPointF(0, self.h * 1), QPointF(self.w, self.h * 1)))
        self.lines.append(QLineF(QPointF(self.w * 0.15, self.h * 1.1), QPointF(self.w * 0.85, self.h * 1.1)))
        self.lines.append(QLineF(QPointF(self.w * 0.3, self.h * 1.2), QPointF(self.w * 0.7, self.h * 1.2)))
        for l in self.lines:
            l1 = QLine(self)
            l1.setLine(l)
            l1.setPen(pen)
            self.addToGroup(l1)

        self.setPos(self.parent.x(), self.parent.y() + 100)
        self.update_line(self.pos())
Beispiel #21
0
def get_graticules(
        rect: QRect) -> Tuple[Dict[float, float], Dict[float, QLineF]]:
    """Get a set of graticules scaled to fit within the given :class:`QtCore.QRect`

    The scale ranges from -20 to 120 (ire) in increments of 10. An extra value of
    7.5 ire is included (NTSC setup level)

    Arguments:
        rect (:class:`QtCore.QRect`): The bounding box as a :class:`QtCore.QRect`

    Returns
    -------
    ire_vals : dict
        A mapping of ire values to their normalized positions
    lines : dict
        A mapping of :class:`QtCore.QLineF` objects with their ire values as keys
    """

    # Overall scale: -20 to 120
    # ire_vals = {
    #     0: 0,
    #     7.5: 16 / 255,      # NTSC black
    #     100: 235 / 255,
    # }
    ire_vals = {}
    # scale_factor = 255/219
    vmax = 120
    vmin = -20
    vsize = vmax - vmin
    ires = [
        -20, -10, 0, 7.5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120
    ]

    def ire_to_pos_norm(ire):
        v = ire
        # v = (ire * 219 + 16) / 255# * scale_factor
        return (v - vmin) / vsize

    for ire in ires:
        ire_vals[ire] = ire_to_pos_norm(ire)

    lines = {}

    rect_w = rect.width()
    rect_h = rect.height()

    w_scale = rect_w - 1
    h_scale = rect_h - 1

    for ire, pos_norm in ire_vals.items():
        pos_y = (pos_norm * h_scale - h_scale) * -1
        lines[float(ire)] = QLineF(0, pos_y, rect_w, pos_y)

    return ire_vals, lines
Beispiel #22
0
def get_point_along_walls(room, margin):
    r_aux = copy.deepcopy(room.room_qrect)

    r_aux = r_aux.adjusted(+margin, -margin, -margin,
                           +margin)  # left,top,right,bottom

    lines = {
        'top': QLineF(r_aux.topLeft(), r_aux.topRight()),
        'right': QLineF(r_aux.topRight(), r_aux.bottomRight()),
        'bottom': QLineF(r_aux.bottomLeft(), r_aux.bottomRight()),
        'left': QLineF(r_aux.topLeft(), r_aux.bottomLeft())
    }

    del lines[room.door_position]

    side = random.choice(list(lines.keys()))
    p = random.uniform(0.25, 0.75)

    return QPointF(lines[side].pointAt(p).x(),
                   lines[side].pointAt(p).y()), side
    def sceneMouseMovedEvent(self, event: QGraphicsSceneMouseEvent):
        if self.state == QLiberationMapState.MOVING_UNIT:
            self.setCursor(Qt.PointingHandCursor)
            self.movement_line.setLine(
                QLineF(self.movement_line.line().p1(), event.scenePos()))

            pos = Point(event.scenePos().x(), event.scenePos().y())
            if self.is_valid_ship_pos(pos):
                self.movement_line.setPen(CONST.COLORS["green"])
            else:
                self.movement_line.setPen(CONST.COLORS["red"])
    def styleChange(self):
        super().styleChange()
        self.prepareGeometryChange()
        style = self.style()

        margin = style.pixelMetric(Style.ConnectionStemTextMargin)
        metrics = QFontMetricsF(self._text_item.font())

        self._stem_item.setLine(QLineF(self.stemRoot(), self.stemTip()))
        self._text_item.setPos(self.stemTip().x() + margin,
                               metrics.capHeight() / 2)
Beispiel #25
0
    def mouseMoveEvent(self, event: QGraphicsSceneMouseEvent):

        if self.__blockMove:
            return
        if self.__currentEndsMove == MoveLineEnds.NONE:
            return

        if self.__tryCapture is not None:
            self.__tryCapture.unCapture(self)

        if self.__currentEndsMove == MoveLineEnds.P1:
            line = QLineF(event.pos(), self.line().p2())
            self.setLine(line)
            self.__updateTextLinePos()
            rect = self.__filteredCapturedObject()
            print(rect)
            if 1 == len(rect):
                rect = rect[0]
                self.__tryCapture = rect
                self.__tryCapture.tryCapture(self)
            self.update()
            return

        if self.__currentEndsMove == MoveLineEnds.P2:
            line = QLineF(self.line().p1(), event.pos())
            self.setLine(line)
            self.__updateTextLinePos()
            rect = self.__filteredCapturedObject()
            print(rect)
            if 1 == len(rect):
                rect = rect[0]
                self.__tryCapture = rect
                self.__tryCapture.tryCapture(self)
            self.update()
            return

        if self.__currentEndsMove == MoveLineEnds.BOTH:
            super().mouseMoveEvent(event)
            self.__updateTextLinePos()
            self.update()
            return
Beispiel #26
0
 def _handle_execution_animation_value_changed(self, step):
     gradient = QLinearGradient(self.src_center, self.dst_center)
     yellow = QColor(255, 255, 0, 204)
     red = QColor(255, 0, 0, 204)
     delta = 8 * self.magic_number / QLineF(self.src_center,
                                            self.dst_center).length()
     gradient.setColorAt(0, yellow)
     gradient.setColorAt(max(0.0, step - delta), yellow)
     gradient.setColorAt(step, red)
     gradient.setColorAt(min(1.0, step + delta), yellow)
     gradient.setColorAt(1.0, yellow)
     self.setBrush(gradient)
    def draw_navmesh_neighbor_line(self, scene: QGraphicsScene, poly: Polygon,
                                   begin: ShapelyPoint) -> None:
        vertex = Point(begin.x, begin.y)
        centroid = poly.centroid
        direction = Point(centroid.x, centroid.y)
        end = vertex.point_from_heading(
            vertex.heading_between_point(direction),
            nautical_miles(2).meters)

        scene.addLine(
            QLineF(QPointF(*self._transform_point(vertex)),
                   QPointF(*self._transform_point(end))),
            CONST.COLORS["yellow"])
Beispiel #28
0
    def drawBackground(self, painter, rect):
        if self.draft_mode:
            border_rect = self.get_grid_border()
            grid_rect = self.get_grid_border(-self._grid_size.width() / 2)

            line_list = []
            # horizontal grid lines
            for line_coordinate in range(grid_rect.top(), border_rect.bottom(),
                                         self._grid_size.height()):
                line_list.append(
                    QLineF(border_rect.left(), line_coordinate,
                           border_rect.right(), line_coordinate))
            # vertical process lines
            left_border = int((grid_rect.left() + self._grid_size.width()) / (2 * self._grid_size.width())) * \
                self._grid_size.width() * 2 - self._grid_size.width()
            for line_coordinate in range(left_border, border_rect.right(),
                                         self._grid_size.width() * 2):
                line_list.append(
                    QLineF(line_coordinate, border_rect.top(), line_coordinate,
                           border_rect.bottom()))

            # vertical commodity lines
            left_border = int(
                grid_rect.left() /
                (2 * self._grid_size.width())) * self._grid_size.width() * 2
            for line_coordinate in range(left_border, border_rect.right(),
                                         self._grid_size.width() * 2):
                line_list.append(
                    QLineF(line_coordinate - 1, border_rect.top(),
                           line_coordinate - 1, border_rect.bottom()))
                line_list.append(
                    QLineF(line_coordinate + 1, border_rect.top(),
                           line_coordinate + 1, border_rect.bottom()))

            painter.setPen(QPen(Qt.lightGray, 1))
            painter.drawLines(line_list)

        super().drawBackground(painter, rect)
Beispiel #29
0
    def _bezier_offset(self) -> QPointF:
        """Symmetric offset of a control point from source/target.
        
        Bezier calculation functions assume that sourcePos() and targetPos() are not None.
        """
        close_distance = self.style().pixelMetric(
            Style.EdgeBezierCloseDistance)
        point_offset = self.style().pixelMetric(Style.EdgeBezierPointOffset)

        closeness_factor = min(
            QLineF(self._source_pos, self._target_pos).length() /
            close_distance, 1)

        return QPointF(point_offset, 0) * closeness_factor
Beispiel #30
0
    def contextMenuEvent(self, event):
        """context menu to interact with process items - delete item"""
        # prevent context menu of scene not in draft mode
        if not self.draft_mode:
            return

        if self._edit_mode == SelectConnect.SELECT:
            # open context menu only for process items
            self._clicked_item = self.itemAt(event.scenePos(), QTransform())
            if self._clicked_item:
                if isinstance(self._clicked_item, ProcessItem):
                    menu = QMenu()
                    delete_action = QAction("Delete", None)
                    delete_action.triggered.connect(
                        lambda: self.delete_process(self._clicked_item))
                    menu.addAction(delete_action)
                    menu.exec_(event.screenPos())
                    self._clicked_item = None
        else:
            # open context menu for commodities of other sections
            menu = QMenu()
            section_list = [
                item for item in OverviewSelection if item is not self._section
                and item is not OverviewSelection.OVERVIEW
            ]
            for section in section_list:
                submenu = QMenu(section.name)
                section_coms = [
                    commodity for commodity in self._model.commodity_list
                    if section in commodity.connection_count.keys()
                ]
                for commodity in section_coms:
                    action = submenu.addAction(str(commodity))
                    action.setData(commodity)

                # only add sub menu if commodities are available
                if section_coms:
                    menu.addMenu(submenu)

            # execute menu
            action = menu.exec_(QCursor.pos())
            if action:
                # start connection
                line_pen = QPen(Qt.lightGray, 1, Qt.DashLine)
                line = QLineF(event.scenePos(), event.scenePos())
                self._connect_line = self.addLine(line, line_pen)
                self._connect_line.setData(0, None)
                self._connect_line.setData(1, action.data())
                self.views()[1].setMouseTracking(True)
Beispiel #31
0
 def testQLineFToTuple(self):
     l = QLineF(1, 2, 3, 4)
     self.assertEqual((1, 2, 3, 4), l.toTuple())