def from_xodr(xodr_file, sample_distance=0.25):
     xodr_string = ""
     with open(xodr_file, "r") as f:
         xodr_string = f.read()
     map_name = xodr_file.split(".")[0]
     carla_map = carla.Map(map_name, xodr_string)
     return OpenDriveManager(carla_map, sample_distance)
Esempio n. 2
0
def map_from_opendrive(opendrive: str, log_file_name: str = None):
    try:
        import carla
    except ImportError:
        raise Exception('Error importing carla.')
    from pylot.map.hd_map import HDMap
    return HDMap(carla.Map('map', opendrive), log_file_name)
Esempio n. 3
0
 def on_open_drive_map(self, msg):
     self._logger.debug('@{}: open drive update'.format(msg.timestamp))
     try:
         import carla
     except ImportError:
         raise Exception('Error importing carla.')
     self._map = HDMap(carla.Map('challenge', msg.data),
                       self._log_file_name)
Esempio n. 4
0
def main():
    with open('Town01.xodr', 'r') as file:
        data = file.read()
        #print(data)
        map = carla.Map("Town01", data)

        print(map.transform_to_geolocation(carla.Location(0,0,0)))
        wp1 = map.get_waypoint(carla.Location(0,0,0))
        print(wp1)
        print(f"road_id: {wp1.road_id}, section_id: {wp1.section_id}, lane_id: {wp1.lane_id}, is_junction: {wp1.is_junction}")
        print(wp1.next(1)[0])
Esempio n. 5
0
 def on_opendrive_map(self, msg):
     """Invoked whenever a message is received on the open drive stream.
     Args:
         msg (:py:class:`~erdos.message.Message`): Message that contains
             the open drive string.
     """
     self._logger.debug('@{}: received open drive message'.format(
         msg.timestamp))
     try:
         import carla
     except ImportError:
         raise Exception('Error importing carla.')
     self._logger.info('Initializing HDMap from open drive stream')
     from pylot.map.hd_map import HDMap
     self._map = HDMap(carla.Map('map', msg.data))
Esempio n. 6
0
def build_binary_for_tm(package_name, dirname, maps):

    xodrs = set((map["name"], map["xodr"]) for map in maps if "xodr" in map)

    for target_name, xodr in xodrs:
        with open(os.path.join(dirname, xodr), "rt") as f:
            data = f.read()

        # copy the binary file
        tm_folder_target = os.path.join(CARLA_ROOT_PATH, "Unreal", "CarlaUE4",
                                        "Content", package_name, "Maps",
                                        target_name, "TM")

        if not os.path.exists(tm_folder_target):
            os.makedirs(tm_folder_target)

        m = carla.Map(str(target_name), data)
        m.cook_in_memory_map(
            str(os.path.join(tm_folder_target, "%s.bin" % target_name)))
def _netconvert_carla_impl(xodr_file, output, tmpdir, guess_tls=False):
    """
    Implements netconvert carla.
    """
    # ----------
    # netconvert
    # ----------
    basename = os.path.splitext(os.path.basename(xodr_file))[0]
    tmp_sumo_net = os.path.join(tmpdir, basename + '.net.xml')

    try:
        basedir = os.path.dirname(os.path.realpath(__file__))
        result = subprocess.call(['netconvert',
            '--opendrive', xodr_file,
            '--output-file', tmp_sumo_net,
            '--geometry.min-radius.fix',
            '--geometry.remove',
            '--opendrive.curve-resolution', '1',
            '--opendrive.import-all-lanes',
            '--type-files', os.path.join(basedir, 'data/opendrive_netconvert.typ.xml'),
            # Necessary to link odr and sumo ids.
            '--output.original-names',
            # Discard loading traffic lights as them will be inserted manually afterwards.
            '--tls.discard-loaded', 'true',
        ])
    except subprocess.CalledProcessError:
        raise RuntimeError('There was an error when executing netconvert.')
    else:
        if result != 0:
            raise RuntimeError('There was an error when executing netconvert.')

    # --------
    # Sumo net
    # --------
    sumo_net = sumolib.net.readNet(tmp_sumo_net)
    sumo_topology = build_topology(sumo_net)

    # ---------
    # Carla map
    # ---------
    with open(xodr_file, 'r') as f:
        carla_map = carla.Map('netconvert', str(f.read()))

    # ---------
    # Landmarks
    # ---------
    tls = {}  # {tlsid: SumoTrafficLight}

    landmarks = carla_map.get_all_landmarks_of_type('1000001')
    for landmark in landmarks:
        if landmark.name == '':
            # This is a workaround to avoid adding traffic lights without controllers.
            logging.warning('Landmark %s has not a valid name.', landmark.name)
            continue

        road_id = str(landmark.road_id)
        for from_lane, to_lane in landmark.get_lane_validities():
            for lane_id in range(from_lane, to_lane + 1):
                if lane_id == 0:
                    continue

                wp = carla_map.get_waypoint_xodr(landmark.road_id, lane_id, landmark.s)
                if wp is None:
                    logging.warning(
                        'Could not find waypoint for landmark {} (road_id: {}, lane_id: {}, s:{}'.
                        format(landmark.id, landmark.road_id, lane_id, landmark.s))
                    continue

                # When the landmark belongs to a junction, we place te traffic light at the
                # entrance of the junction.
                if wp.is_junction and sumo_topology.is_junction(road_id, lane_id):
                    tlid = str(wp.get_junction().id)
                    if tlid not in tls:
                        tls[tlid] = SumoTrafficLight(tlid)
                    tl = tls[tlid]

                    if guess_tls:
                        for from_edge, from_lane in sumo_topology.get_incoming(road_id, lane_id):
                            successors = sumo_topology.get_successors(from_edge, from_lane)
                            for to_edge, to_lane in successors:
                                tl.add_landmark(landmark.id, tl.id, from_edge, to_edge, from_lane,
                                                to_lane)

                    else:
                        connections = sumo_topology.get_path_connectivity(road_id, lane_id)
                        for from_, to_ in connections:
                            from_edge, from_lane = from_
                            to_edge, to_lane = to_

                            tl.add_landmark(landmark.id, tl.id, from_edge, to_edge, from_lane,
                                            to_lane)

                # When the landmarks does not belong to a junction (i.e., belongs to a std road),
                # we place the traffic light between that std road and its successor.
                elif not wp.is_junction and not sumo_topology.is_junction(road_id, lane_id):
                    from_edge, from_lane = sumo_topology.get_sumo_id(road_id, lane_id, landmark.s)

                    for to_edge, to_lane in sumo_topology.get_successors(from_edge, from_lane):
                        tlid = SumoTrafficLight.generate_tl_id(from_edge, to_edge)
                        if tlid not in tls:
                            tls[tlid] = SumoTrafficLight(tlid)
                        tl = tls[tlid]

                        tl.add_landmark(landmark.id, tl.id, from_edge, to_edge, from_lane, to_lane)

                else:
                    logging.warning('Landmark %s could not be added.', landmark.id)

    # ---------------
    # Modify sumo net
    # ---------------
    parser = ET.XMLParser(remove_blank_text=True)
    tree = ET.parse(tmp_sumo_net, parser)
    root = tree.getroot()

    for tl in tls.values():
        SumoTrafficLight.generate_default_program(tl)
        edges_tags = tree.xpath('//edge')
        if not edges_tags:
            raise RuntimeError('No edges found in sumo net.')
        root.insert(root.index(edges_tags[-1]) + 1, tl.to_xml())

        for connection in tl.connections:
            tags = tree.xpath(
                '//connection[@from="{}" and @to="{}" and @fromLane="{}" and @toLane="{}"]'.format(
                    connection.from_road, connection.to_road, connection.from_lane,
                    connection.to_lane))

            if tags:
                if len(tags) > 1:
                    logging.warning(
                        'Found repeated connections from={} to={} fromLane={} toLane={}.'.format(
                            connection.from_road, connection.to_road, connection.from_lane,
                            connection.to_lane))

                tags[0].set('tl', str(connection.tlid))
                tags[0].set('linkIndex', str(connection.link_index))
            else:
                logging.warning('Not found connection from={} to={} fromLane={} toLane={}.'.format(
                    connection.from_road, connection.to_road, connection.from_lane,
                    connection.to_lane))

    tree.write(output, pretty_print=True, encoding='UTF-8', xml_declaration=True)
Esempio n. 8
0
 def on_opendrive_map(self, msg):
     self._map = HDMap(carla.Map('challenge', msg.data),
                       self._log_file_name)
Esempio n. 9
0
def load_map(xodr_file):
    with open(xodr_file, 'r') as f:
        carla_map = carla.Map('odr2lanelet2', str(f.read()))
    return OdrMap(carla_map)
Esempio n. 10
0
 def on_open_drive_map(self, msg):
     self._logger.debug('@{}: open drive update'.format(msg.timestamp))
     self._map = HDMap(carla.Map('challenge', msg.data),
                       self._log_file_name)
Esempio n. 11
0
 def on_opendrive_map(self, msg):
     self._logger.debug('@{}: received open drive message'.format(
         msg.timestamp))
     self._logger.info('Initializing HDMap from open drive stream')
     self._map = HDMap(carla.Map('map', msg.data), self._log_file_name)
Esempio n. 12
0
 def on_opendrive_map(self, msg):
     self._logger.info('Planner running in scenario runner mode')
     self._map = HDMap(carla.Map('map', msg.data), self._log_file_name)
                       type=str,
                       help='OpenDRIVE file')
args = argparser.parse_args()

# read the OpenDRIVE
try:
    f = open(args.file, "rt")
except:
    print("OpenDRIVE file not found!")
    exit(1)

data = f.read()
f.close()

# create the map with the OpenDRIVE content
m = carla.Map("t", data)
points = m.get_crosswalks()
for i in range(len(points)):
    print(points[i])

# generate the .OBJ file
f = open("crosswalks.obj", "wt")
faceIndex = 0
vertexIndex = 0
i = 0
totalCrosswalks = 0
totalPoints = 0
while (i < len(points)):
    totalCrosswalks += 1
    # object
    f.write("o crosswalk_%d\n" % totalCrosswalks)