File size: 4,962 Bytes
0c3dd1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
113
114
115
116
117
118
119
120
121
"""Client for the art_lockstep physics server (NEW CODE).

One server process == one episode == one freshly constructed Chrono system,
ARTcar and RigidTerrain. Communication is strictly request/response over
pipes, so results never depend on wall-clock timing.
"""
import os
import select
import subprocess
import time

STATE_FIELDS = ('step time cog_x cog_y cog_z q_e0 q_e1 q_e2 q_e3 vel_x vel_y vel_z wloc_x wloc_y wloc_z '
                'ref_x ref_y ref_z applied_steer applied_thr applied_brake drv_steer drv_thr drv_brake '
                'veh_speed finite step_wall_s').split()

DEFAULT_BINARY = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'build', 'art_lockstep')


class PhysicsError(RuntimeError):
    """Infrastructure failure of the physics server (crash, timeout, message format)."""


class PhysicsServer:
    def __init__(self, x, y, yaw, binary=DEFAULT_BINARY, terrain_json=None, waypoint_boxes=None,
                 replicate_vis=False, timeout_s=120.0, stderr_path=None):
        self.timeout_s = timeout_s
        args = [binary, '--x', repr(float(x)), '--y', repr(float(y)), '--yaw', repr(float(yaw))]
        if terrain_json:
            args += ['--terrain-json', terrain_json]
        if waypoint_boxes:
            args += ['--waypoint-boxes', waypoint_boxes]
        if replicate_vis:
            args += ['--replicate-vis', '1']
        self.args = args
        self.extra_output = []
        t0 = time.perf_counter()
        self._stderr = open(stderr_path, 'w') if stderr_path else subprocess.DEVNULL
        env = dict(os.environ)
        env.setdefault('OMP_NUM_THREADS', '1')
        self.proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self._stderr,
                                     bufsize=0, env=env)
        self._buf = b''
        ready = self._read_until(b'READY')
        self.ready_line = ready
        self.server_init_s = float(ready.split()[1].split('=')[1])
        self.state = self._parse_state(self._read_until(b'X '))
        self.spawn_to_ready_s = time.perf_counter() - t0
        self.step_calls = 0

    # -- low level ---------------------------------------------------------
    def _readline(self):
        deadline = time.monotonic() + self.timeout_s
        while b'\n' not in self._buf:
            remaining = deadline - time.monotonic()
            if remaining <= 0:
                raise PhysicsError(f'physics server timeout after {self.timeout_s}s')
            r, _, _ = select.select([self.proc.stdout], [], [], remaining)
            if not r:
                continue
            chunk = os.read(self.proc.stdout.fileno(), 1 << 16)
            if not chunk:
                raise PhysicsError(f'physics server exited (code {self.proc.poll()})')
            self._buf += chunk
        line, self._buf = self._buf.split(b'\n', 1)
        return line.decode()

    def _read_until(self, prefix):
        while True:
            line = self._readline()
            if line.startswith(prefix.decode()):
                return line
            if line.startswith('ART_LOCKSTEP_FATAL'):
                raise PhysicsError(line)
            self.extra_output.append(line)  # e.g. Chrono GetLog() text

    def _send(self, text):
        try:
            os.write(self.proc.stdin.fileno(), text.encode())
        except (BrokenPipeError, OSError) as e:
            raise PhysicsError(f'physics server pipe error: {e}')

    @staticmethod
    def _parse_state(line):
        parts = line.split()[1:]
        if len(parts) != len(STATE_FIELDS):
            raise PhysicsError(f'bad state line ({len(parts)} fields): {line[:200]}')
        st = {}
        for k, v in zip(STATE_FIELDS, parts):
            st[k] = float(v)
        st['step'] = int(parts[0])
        st['finite'] = int(parts[STATE_FIELDS.index('finite')])
        return st

    # -- API ----------------------------------------------------------------
    def step(self, n):
        if n <= 0:
            raise ValueError('step count must be positive')
        self._send(f'S {int(n)}\n')
        self.state = self._parse_state(self._read_until(b'X '))
        self.step_calls += 1
        if not self.state['finite']:
            raise PhysicsError(f"non-finite physics state at step {self.state['step']}")
        return self.state

    def set_inputs(self, steering, throttle, braking):
        self._send(f'U {float(steering)!r} {float(throttle)!r} {float(braking)!r}\n')
        parts = self._read_until(b'OK').split()
        return float(parts[1]), float(parts[2]), float(parts[3])

    def close(self):
        if self.proc.poll() is None:
            try:
                self._send('Q\n')
                self.proc.wait(timeout=10)
            except Exception:
                self.proc.kill()
                self.proc.wait()
        if self._stderr not in (None, subprocess.DEVNULL):
            self._stderr.close()
        return self.proc.returncode