File size: 5,420 Bytes
314ecfb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
"""Privileged object observations for the stage-3 oracle agent (upper-bound experiment only).

Reads every vehicle / walker / static prop actor and the map's parked vehicles straight from the CARLA
world, then feeds them through the same FOV-limited ObjectBank used to build the training labels, so
the agent sees exactly the token distribution the model was trained on. Nothing here is a perception
model; a tracker (stage 2) is meant to replace this file.
"""
import math

import numpy as np

import carla
from srunner.scenariomanager.carla_data_provider import CarlaDataProvider

from dataloader.object_bank import (
    CLASS_CAR, CLASS_STATIC, CLASS_WALKER, FEAT_DIM, ObjectBank, Observation, ego_pose_from_matrix,
    raw_to_features,
)

ENV_OBJECT_LABELS = ("Car", "Truck", "Bus", "Motorcycle", "Bicycle")
ENV_ID_OFFSET = 1_000_000  # keeps env-object ids clear of actor ids (>0) and bank pseudo-ids (-1, -2, ...)


class OracleObjectSource:
    def __init__(self, bank_kwargs, actor_range=120.0, noise=None):
        """noise: optional team_code.oracle_noise.TrackerNoise applied to the observations."""
        self.bank = ObjectBank(**bank_kwargs)
        self.actor_range = float(actor_range)
        self.noise = noise
        self._env_objects = None
        self._env_world_id = None

    def reset(self):
        self.bank.reset()
        if self.noise is not None:
            self.noise.reset()
        self._env_objects = None
        self._env_world_id = None

    def _load_env_objects(self, world):
        """Parked vehicles baked into the map (SimLingo's `static_car`). CARLA gives them uint64 ids
        that overflow the bank's int64 id array, so they get compact negative ids; ids only serve
        frame-to-frame association and never reach the model."""
        rows = []
        for name in ENV_OBJECT_LABELS:
            label = getattr(carla.CityObjectLabel, name, None)
            if label is None:
                continue
            for obj in world.get_environment_objects(label):
                bb = obj.bounding_box
                rows.append((-(ENV_ID_OFFSET + len(rows)), bb.location.x, bb.location.y, math.radians(bb.rotation.yaw),
                             max(bb.extent.x, 0.1), max(bb.extent.y, 0.1), max(bb.extent.z, 0.05)))
        self._env_objects = np.asarray(rows, dtype=np.float64).reshape(-1, 7)
        self._env_world_id = world.id

    def _env_observations(self, world, ego_xy):
        if self._env_objects is None or self._env_world_id != world.id:
            self._load_env_objects(world)
        if len(self._env_objects) == 0:
            return []
        d = np.hypot(self._env_objects[:, 1] - ego_xy[0], self._env_objects[:, 2] - ego_xy[1])
        observations = []
        for row in self._env_objects[d < self.actor_range]:
            observations.append(Observation(
                obj_id=int(row[0]), cls=CLASS_STATIC, world_xy=row[1:3].copy(), world_yaw=float(row[3]),
                speed=0.0, length=float(row[4]), width=float(row[5]), height=float(row[6])))
        return observations

    def step(self, t):
        """Returns (features [N, FEAT_DIM] float32, mask [N] bool, raw rows, ids, count)."""
        world = CarlaDataProvider.get_world()
        hero = CarlaDataProvider.get_hero_actor()
        n = self.bank.max_objects
        if world is None or hero is None:
            return np.zeros((n, FEAT_DIM), np.float32), np.zeros(n, bool), np.zeros((n, 10), np.float32), np.zeros(n, np.int64), 0
        transform = hero.get_transform()
        ego_matrix = np.asarray(transform.get_matrix(), dtype=np.float64)
        ego_xy = np.array([transform.location.x, transform.location.y])
        observations = []
        for actor in world.get_actors():
            if actor.id == hero.id:
                continue
            type_id = actor.type_id
            if type_id.startswith("vehicle."):
                cls = CLASS_CAR
            elif type_id.startswith("walker.pedestrian"):
                cls = CLASS_WALKER
            elif type_id.startswith("static.prop."):
                cls = CLASS_STATIC
            else:
                continue
            actor_transform = actor.get_transform()
            loc = actor_transform.location
            if math.hypot(loc.x - ego_xy[0], loc.y - ego_xy[1]) > self.actor_range:
                continue
            bb = actor.bounding_box
            velocity = actor.get_velocity()
            speed = math.hypot(velocity.x, velocity.y) if cls != CLASS_STATIC else 0.0
            observations.append(Observation(
                obj_id=int(actor.id), cls=cls, world_xy=np.array([loc.x, loc.y], dtype=np.float64),
                world_yaw=math.radians(actor_transform.rotation.yaw + bb.rotation.yaw), speed=speed,
                length=max(bb.extent.x, 0.1), width=max(bb.extent.y, 0.1), height=max(bb.extent.z, 0.05)))
        observations.extend(self._env_observations(world, ego_xy))
        if self.noise is not None:
            ego_yaw = ego_pose_from_matrix(ego_matrix)[2]
            observations = self.noise.apply(float(t), observations, ego_xy, ego_yaw, camera_x=self.bank.camera_x)
        raw, ids, count = self.bank.step(float(t), ego_matrix, observations)
        if self.noise is not None:
            raw, ids, count = self.noise.filter_rows(raw, ids, count)
        mask = np.arange(n) < count
        return raw_to_features(raw), mask, raw, ids, count