Public release

This commit is contained in:
2026-10-06 22:07:41 +00:00
parent 9944af66e7
commit 2bc0c9e3f9
45 changed files with 1812 additions and 168 deletions
+15 -7
View File
@@ -4,10 +4,12 @@ Experimental simulator autopilot and Tesla Semi cab displays for American Truck
## Run
Use `Run-Native-Drive.bat` or the **Tesla Semi FSD** desktop shortcut. Both start the native backend.
Use `Run-Native-Drive.bat` or the **Tesla Semi FSD** desktop shortcut to open ATS and its companion together. With `tools/install_ats_autostart.ps1` installed, opening ATS through any shortcut also starts the cab screens and native controller automatically. The per-user login watcher stays idle when ATS is closed; no administrator setup is needed.
The watcher reuses an existing companion, prevents competing vJoy runners, retries a failed companion with backoff, and closes its companion cleanly when the exact ATS process exits. Automatic startup never engages driving controls; F8 remains required. Startup logs are in `diagnostics/ats-autostart.log` and `diagnostics/native-runtime.log`. Remove **ATS Native FSD Companion** from your Windows Startup folder to disable automatic launch.
```powershell
C:\Python314\python.exe -B tools/run_native_gameplay.py --input auto --cab-only --no-record
C:\Python314\python.exe -B tools/run_native_gameplay.py --input auto
```
The engine must be powered, Drive selected, ATS cruise disabled, and a supported GPS route available before engagement. The map cache prepares the trip in the background and the screen reports readiness and missing connections.
@@ -17,7 +19,7 @@ The engine must be powered, Drive selected, ATS cruise disabled, and a supported
- **Manual steering/braking or Escape:** release controls.
- **Cabin mouse-look:** independent of driving observations.
User-facing speeds, distances and range use imperial units. MAX follows increases in the truck navigator's posted limit, with a 5 MPH trailer offset or 10 MPH bobtail offset. Home/End can override the target within 5–80 MPH. A lower or unchanged posted limit does not overwrite a manual setting.
User-facing speeds, distances and range use imperial units. Every confirmed change in the truck navigator's posted limit resets MAX to that limit, including decreases. Home/End adjusts by 5 MPH within +/-5 MPH with a trailer or +/-10 MPH without one, bounded by the controller's 5-80 MPH range. Unchanged or temporarily unavailable limits preserve the manual setting; a new sign resets it.
The verified automatic input transport is vJoy. `--input vjoy`, `--input ets2la` and `--input spf` select explicit transports; the SPF bridge is diagnostic and its acknowledgement alone does not establish that ATS mapped its controls.
@@ -31,7 +33,7 @@ Steering follows ordered lane geometry with lane-center feedback, damping, speed
Passing uses mounted adjacent-road lane definitions and measured vehicle bodies. When MAX exceeds a slower lead's speed, the planner checks a supported passing lane, signals, follows a road-anchored transition, and returns only after the passed vehicle clears the player's trailer. Shoulders and opposing lanes are excluded. Signalized junction queues do not trigger a pass.
Traffic-light planning associates live lamp states with authored stop curves. Green entry also requires the supported crossing policy and fresh observed traffic gaps. Incomplete observations retain a hold. Vehicle observations do not provide complete detection of random construction cones, yellow X barriers, invisible walls, or temporary closures. Unsupported geometry remains an explicit route gap.
Traffic-light planning associates live lamp states with authored stop curves. Exact prefab UID lookups in the pinned game map registry supplement the nearby list, which can omit the junction under the truck. An identity-verified loaded segment with no semaphore instances establishes an unsignalized junction; missing lamp observations alone do not. Green or unsignalized entry also requires supported authored priority and fresh observed traffic gaps. Unconditional stop completion and unsupported additional rules retain a hold. Incomplete observations retain a hold. Vehicle observations do not provide complete detection of random construction cones, yellow X barriers, invisible walls, or temporary closures. Unsupported geometry remains an explicit route gap.
Roads and prefab paths use verified source formulas and measured spans. Banked roads support an experimental linear endpoint-roll surface model up to six degrees; truck heading, height and lane-membership checks still apply. The approximation and driving controller remain experimental.
@@ -43,7 +45,7 @@ The custom navigation display shows the detour and retains the original trip. Ga
## Cab displays
The two custom Tesla Semi screens show driving status, vehicle and trailer visuals, nearby traffic, the selected path, active navigation, gear, truck indicators, battery estimate and range. The right screen powers off with the truck. Hide the optional desktop panel with `--cab-only`.
The two custom Tesla Semi screens show driving status, vehicle and trailer visuals, nearby traffic, the selected path, active navigation, gear, truck indicators, battery estimate and range. The right screen powers off with the truck. Normal launches render only these screens; use `--desktop-panel` to show the additional desktop panel. `--cab-only` remains supported.
Native driving does not capture a camera feed. The auxiliary viewport and camera hook are retired. `Disable-Forward-Camera.bat` runs the reversible removal helper with ATS closed, preserving the SPF framework, TruckScreen plugin, telemetry and vJoy.
@@ -55,9 +57,15 @@ Build with `native/truck_screen/build.ps1`; install the display package with `In
GPS, actor and signal reads run in independent background workers. The control loop consumes completed observations without waiting for slow process-memory reads or reconnects. Original observation times and expiry checks remain; a late result cannot become fresh by completing late. Pauses and GPS destination changes invalidate cached observations immediately.
Cab rendering runs on a separate worker. Actuator command publication and release use separate synchronization. A 500 ms command watchdog remains active; manual takeover and confirmed focus/actuator faults release controls. Every new engagement requires a human F8 press.
GPS process-memory verification runs in its own read-only process, isolated from bulk map decoding and display work. Its handoff permits one outstanding read and retains the original request and cached observation times through delayed replies.
`diagnostics/native-control.jsonl` records engagements, releases, source ages, reader durations, selected lanes, trip gaps, traffic, charging status, and control/render timings. `diagnostics/native-lanes/trips` contains trip reports. `--no-record` disables image recording but retains compact control logs.
Mounted lane source checks also run in a background verifier after startup validation. Snapshots reject archive changes or checks older than two seconds. Lane projection uses bounded scalar geometry to avoid repeated thread handoffs during bulk work; slow mapping iterations and command timeouts record competing thread locations without copying their locals.
Bulk map/permission JSON decoding yields between object batches, and cache writes stream the same pinned bytes. Cyclic garbage collection runs only while disengaged, without a pending F8 request, with fresh stopped telemetry and the parking brake set. Reference counting remains enabled. Per-planner timings and parked collection durations appear in control diagnostics.
Cab rendering runs in a separate process that owns only the display textures. A bounded feeder sends one display snapshot at a time and replaces pending snapshots with the latest; full lane graphs are excluded. Stale display packets cannot publish old ACTIVE status as current. The control process uses a 1 ms Python thread slice so bulk workers yield execution sooner. Actuator command publication and release use separate synchronization. A 500 ms command watchdog remains active; manual takeover and confirmed focus/actuator faults release controls. Every new engagement requires a human F8 press.
`diagnostics/native-control.jsonl` records the loaded Git revision and source fingerprint at startup, engagements, releases, source ages, reader durations, selected lanes, trip gaps, traffic, charging status, and control/render timings. `diagnostics/native-lanes/trips` contains trip reports. Normal launches use compact control logs; `--record` opts into full scene recording. `--no-record` overrides it. Full evidence encoding yields between batches so diagnostic recording can share execution with control threads.
```powershell
C:\Python314\python.exe -B -m unittest discover -s tests
+1 -2
View File
@@ -1,4 +1,3 @@
@echo off
cd /d "%~dp0"
"C:\Python314\python.exe" tools\run_native_gameplay.py %*
pause
start "" "C:\Python314\pythonw.exe" -B tools\ats_autostart.py --launch %*
+1 -2
View File
@@ -1,4 +1,3 @@
@echo off
cd /d "%~dp0"
"C:\Python314\python.exe" -B tools\run_native_gameplay.py --input auto %*
pause
start "" "C:\Python314\pythonw.exe" -B tools\ats_autostart.py --launch %*
+9
View File
@@ -69,6 +69,7 @@ class FSDController:
self.min_follow_dist = 15.0
self.inertial_hold_active = False
self.fault = None
self.watchdog_diagnostics = None
self._command = None
self._last_actuation = None
self._last_lateral = self.clock()
@@ -234,6 +235,14 @@ class FSDController:
f"Control watchdog: command stalled for {age * 1000:.0f} ms")
if expired:
self.release_all_controls()
if age > self.command_timeout:
# Capture competing work only after neutralization.
# This evidence never changes command expiry or leases.
from telemetry.native_runtime_work import thread_stack_snapshot
self.watchdog_diagnostics=dict(command_age_ms=age*1000.,sampled_at=self.clock())
try:self.watchdog_diagnostics['threads']=thread_stack_snapshot()
except Exception as exc:
self.watchdog_diagnostics['diagnostic_error']=type(exc).__name__
return
if not foreground:
# A single worker check can disagree with the control loop
+3 -3
View File
@@ -1,4 +1,4 @@
"""Persist speed settings and follow higher navigation limits without actuators."""
"""Persist speed settings and follow confirmed navigation limits without actuators."""
import json
import math
from pathlib import Path
@@ -65,8 +65,8 @@ class NavigationSpeedLimit:
self._last_sample = now
if now - self._pending_since < self.CONFIRM_S or mph == self.limit_mph:
return None
previous, self.limit_mph = self.limit_mph, mph
return mph if previous is None or mph > previous else None
self.limit_mph = mph
return mph
def valid_speed(value):
+21 -13
View File
@@ -129,7 +129,8 @@ class NativeCrossingPlanner:
if not isinstance(plan,dict) or not fresh(plan,now,.35):
raise ValueError('Fresh selected native route path required')
exact=NativeSignalPlanner().assess(scene,plan)
match_fields=('route_revision','selected_lane_id','phase','phase_code','phase_sampled_at','association')
match_fields=('route_revision','selected_lane_id','phase','phase_code','phase_sampled_at','association',
'traffic_light_absence_verified')
if (isinstance(supplied,dict) and supplied.get('retained_stop') is True
and any(supplied.get(k)!=exact.get(k) for k in match_fields)):
# Only an existing controller hold may nominate a just-passed
@@ -140,14 +141,17 @@ class NativeCrossingPlanner:
if all(supplied.get(k)==candidate.get(k) for k in match_fields)),None)
if exact is None:
raise ValueError('Retained stop does not match a freshly verified passed stop point')
exact=dict(exact,state=('proceed' if exact.get('phase')=='green'
exact=dict(exact,state=('proceed' if (exact.get('phase')=='green'
or exact.get('traffic_light_absence_verified') is True)
and (exact.get('stop_point') or {}).get('traffic_rule')=='cross_line' else 'unknown'))
result['retained_stop']=True
if not isinstance(supplied,dict) or any(supplied.get(k)!=exact.get(k) for k in match_fields):
raise ValueError('Signal plan does not match the current route and live phase')
result.update(available=exact.get('available') is True,route_revision=exact.get('route_revision'),
association=exact.get('association'),phase=exact.get('phase'))
if exact.get('phase')!='green' or exact.get('state')!='proceed' or exact.get('signal_phase_verified') is not True:
uncontrolled=exact.get('traffic_light_absence_verified') is True
if exact.get('state')!='proceed' or not (uncontrolled or
exact.get('phase')=='green' and exact.get('signal_phase_verified') is True):
raise ValueError('Exact governed green phase required; stop/yield rules remain active')
if exact.get('front_geometry_verified') is not True:
raise ValueError('Verified native truck front required')
@@ -172,18 +176,21 @@ class NativeCrossingPlanner:
definition=signals.get('traffic_rule_definition') or {}
if definition.get('verified') is not True or definition.get('sha256')!=RULES_SHA256:
raise ValueError('Installed traffic-rule definitions unqualified')
live=next(s for s in signals['signals'] if s['prefab_uid']==association['prefab_uid']
and s['semaphore_id']==association['semaphore_id'])
remaining=number(live.get('time_remaining_s'))
if remaining is not None:
remaining-=max(0.,now-signals['sampled_at'])
if remaining is None or remaining<=.5:
raise ValueError('Green phase is ending or remaining time is unknown')
remaining=None
if not uncontrolled:
live=next(s for s in signals['signals'] if s['prefab_uid']==association['prefab_uid']
and s['semaphore_id']==association['semaphore_id'])
remaining=number(live.get('time_remaining_s'))
if remaining is not None:
remaining-=max(0.,now-signals['sampled_at'])
if remaining is None or remaining<=.5:
raise ValueError('Green phase is ending or remaining time is unknown')
result.update(priority_semantics_resolved=True,priority=dict(value=priority,additive=False,
source=PRIORITY_SOURCE,rule_source=RULE_SOURCE,curve_index=governed['curve_index'],
label={4:'minor left',5:'minor right',6:'minor straight',10:'major left',11:'major right',12:'major straight'}[priority],
semantics='Explicit absolute curve priority; yield to every observed conflicting trajectory'),
protection='unknown: permissive observed-gap policy',green_time_remaining_s=remaining)
protection='unknown: permissive observed-gap policy',green_time_remaining_s=remaining,
traffic_light_absence_verified=uncontrolled)
traffic_source=sources.get('traffic') or {};traffic=traffic_source.get('data') or {}
if traffic_source.get('fresh') is not True or not fresh(traffic,now,.3):
raise ValueError('Fresh native traffic required for intersection entry')
@@ -243,7 +250,7 @@ class NativeCrossingPlanner:
times=np.arange(0.,HORIZON_S+STEP_S/2,STEP_S)
sweep=_prepare_sweep(path)
earliest=next((float(t) for t in times if _progress(speed,float(t))>=max(0.,exact['stop_distance_m'])),None)
if earliest is None or remaining<earliest+.5:
if earliest is None or remaining is not None and remaining<earliest+.5:
raise ValueError('Green is too short for the projected entry approach')
result.update(observed_traversal_complete=True,actor_count=len(actors),
footprint=dict(front_m=front,rear_m=rear,half_width_m=half_width,vertical_m=vertical),
@@ -306,7 +313,8 @@ class NativeCrossingPlanner:
if plan.get('usable_for_control') is not True or plan.get('lane_membership_verified') is not True:
raise ValueError('Observed gap only; selected native path is not control-qualified')
result.update(available=True,state='proceed',proceed_authorized=True,experimental_proceed=True,
reason='Experimental permissive green: explicit authored priority and no observed conflict',
reason=('Unsignalized junction: authored priority and no observed conflict' if uncontrolled else
'Experimental permissive green: explicit authored priority and no observed conflict'),
entry_speed_cap_mps=ENTRY_SPEED_CAP_MPS,valid_for_s=.2,
semantics_source=LOCATOR_SOURCE)
except (KeyError,TypeError,ValueError,OverflowError,StopIteration) as exc:
+14 -3
View File
@@ -144,8 +144,9 @@ class NativeGameplayController:
self._signal_hold = None
return signal
restored = dict(candidate, retained_stop=True)
green = (candidate.get('signal_phase_verified') is True
green = ((candidate.get('signal_phase_verified') is True
and candidate.get('phase') == 'green')
or candidate.get('traffic_light_absence_verified') is True)
restored.update(state='proceed' if green else 'hold',
stop_required=not green,
usable_for_control=not green)
@@ -516,6 +517,8 @@ class NativeGameplayController:
association = (overtake.get('association') if control_plan is not plan else None) or plan.get('association') or {}
lateral_error = number(association.get('ego_lateral_right_m'))
heading_dot = number(association.get('heading_dot'))
turn_alignment = association.get('turn_alignment_recovery') is True
geometry['turn_alignment_recovery'] = turn_alignment
if lateral_error is not None:
lane_ids = plan.get('selected_lane_ids') or []
lane_key = (plan.get('route_revision'),
@@ -604,6 +607,10 @@ class NativeGameplayController:
# Lane recovery steering is not road curvature. Use the authored
# road shape for corner speed and measured drift for stability limits.
target = self.target_speed_mph
if turn_alignment:
# Keep pursuing the fresh exit lane while the chassis catches up;
# the old failure branch centered the wheel and forced a full stop.
target = min(target, 20.)
if curve.get('speed_limit_mph') is not None:
target = min(target,curve['speed_limit_mph'])
stability_cap = self._stability_speed_cap(
@@ -659,7 +666,9 @@ class NativeGameplayController:
crossing_stamp = number(crossing.get('sampled_at'))
crossing_ttl = number(crossing.get('valid_for_s'))
crossing_cap = number(crossing.get('entry_speed_cap_mps'))
crossing_proceed = (signal_associated and signal.get('phase') == 'green'
crossing_proceed = (signal_associated and (signal.get('phase') == 'green'
or signal.get('traffic_light_absence_verified') is True
and crossing.get('traffic_light_absence_verified') is True)
and not signal_stop and crossing.get('proceed_authorized') is True
and crossing.get('experimental_proceed') is True
and crossing.get('observed_clearance') is True
@@ -728,7 +737,9 @@ class NativeGameplayController:
elif crossing_hold:
reason = crossing.get('reason') or 'Intersection priority pending'
elif crossing_proceed:
reason = 'Green: yielding to observed traffic gaps'
reason = ('Unsignalized junction: yielding to observed traffic gaps'
if signal.get('traffic_light_absence_verified') is True
else 'Green: yielding to observed traffic gaps')
elif charge_gap is not None:
reason='Charging/fuel stop: park and refuel' if charge_gap<=1.5 else 'Approaching charging/fuel stop'
return self.result(reason,True,axis,action,intensity,
+26 -2
View File
@@ -276,8 +276,12 @@ class NativeOvertakePlanner:
and all(number(v) is not None for v in velocity)
and number(actor.get('measured_age_s')) is not None
and 0. <= actor['measured_age_s'] <= .3)
if not known and -100. < lo < 120.:
if not known and not committed and -100. < lo < 120.:
raise ValueError('Target lane actor motion is not yet measured')
# A new actor/velocity dropout cannot cancel a transition already
# under way. Fresh measured bodies still block an alongside merge;
# forward bodies with unknown motion are stationary braking evidence
# in native_lead on the anchored path. New changes need motion proof.
actor_speed = float(np.asarray(velocity)[[0, 2]]@tangent) if known else 0.
if lo >= front:
gap = lo-front
@@ -332,6 +336,12 @@ class NativeOvertakePlanner:
if hit is None or hit['error_m'] > 1.75:
raise ValueError('Truck departed the anchored passing path')
line = np.vstack((hit['projection'], self.world_path[hit['index']+1:]))
# Projection at a stored vertex repeats that vertex. Remove it before
# local-path validation, which correctly rejects real zero-length spans.
lengths = np.linalg.norm(np.diff(line[:, [0, 2]], axis=0), axis=1)
line = line[np.r_[True, lengths > 1e-5]]
if len(line) < 2:
raise ValueError('Anchored passing path exhausted before settling')
local, _ = _local_points(line, position, float(sdk['world_rotation'][0])*2.*math.pi)
lengths = np.linalg.norm(np.diff(local[:, :2], axis=0), axis=1)
local = local[np.r_[True, lengths > 1e-5]]
@@ -380,6 +390,7 @@ class NativeOvertakePlanner:
graph = (sources.get('lane_graph') or {}).get('data') or {}
traffic = (sources.get('traffic') or {}).get('data') or scene.get('nearby_traffic') or {}
sdk = scene.get('sdk') or {}
permission = None
try:
speed = number(sdk.get('speed_mps'))
if speed is None:
@@ -493,5 +504,18 @@ class NativeOvertakePlanner:
return self._report(now, path, association, permission, clearance,
'Bypassing a stopped vehicle' if self.mode == 'obstacle_bypass' else 'Passing slower traffic')
except (KeyError, TypeError, ValueError, OverflowError, IndexError) as exc:
return dict(_empty(now, str(exc), 'blocked' if self.state.startswith('changing') else 'waiting'),
result = dict(_empty(now, str(exc), 'blocked' if self.state.startswith('changing') else 'waiting'),
maneuver_hold=self.state.startswith('changing'), route_revision=revision)
if result['maneuver_hold'] and permission is not None:
# Occupancy can withdraw permission to keep merging without
# erasing where the truck already is. Preserve only membership
# in the previously authorized corridor while braking. This
# neither starts a new change nor asserts fresh traffic clearance.
try:
_, association, _ = self._anchored_path(sdk)
result.update(lane_membership_only=True,permission_verified=True,
current_lane_id=self.current_lane_id,target_lane_id=self.target_lane_id,
world_path=self.world_path.tolist(),association=association)
except (KeyError,TypeError,ValueError,OverflowError,IndexError):
pass
return result
+120 -46
View File
@@ -31,37 +31,32 @@ def unavailable(reason, now):
def closest(points, position, forward):
# Authored prefab paths can contain thousands of segments. Project them
# together: a Python/NumPy call per segment used to delay fresh commands.
# Keep the original heading/height gates and first-minimum tie behavior.
points = np.asarray(points, dtype=float)
# Python scalar geometry avoids repeatedly yielding execution to busy map
# workers between NumPy operations. These bounded lane polylines are small
# enough to project in one pass; preserve heading/height and first ties.
if isinstance(points,np.ndarray):points=points.tolist()
if len(points) < 2:
return None
position = np.asarray(position, dtype=float)
delta = np.diff(points, axis=0)
horizontal = delta[:, [0, 2]]
length = np.linalg.norm(horizontal, axis=1)
indices = np.flatnonzero(length >= 1e-6)
if not len(indices):
return None
heading = (horizontal[indices]/length[indices, None]) @ forward
indices = indices[heading >= .7]
heading = heading[heading >= .7]
if not len(indices):
return None
offset = (position-points[indices])[:, [0, 2]]
fraction = np.clip(np.sum(offset*horizontal[indices], axis=1)/length[indices]**2, 0., 1.)
projection = points[indices]+fraction[:, None]*delta[indices]
lateral = np.linalg.norm((position-projection)[:, [0, 2]], axis=1)
height = np.abs(position[1]-projection[:, 1])
score = lateral+height*2.+(1.-heading)*3.
valid = np.flatnonzero((height <= 1.) & np.isfinite(score))
if not len(valid):
return None
j = int(valid[np.argmin(score[valid])])
return dict(index=int(indices[j]), fraction=float(fraction[j]), projection=projection[j],
error_m=float(lateral[j]), height_error_m=float(height[j]),
heading_dot=float(heading[j]), score=float(score[j]))
px,py,pz=map(float,position);fx,fz=map(float,forward)
best=None
for index,(a,b) in enumerate(zip(points,points[1:])):
ax,ay,az=map(float,a);bx,by,bz=map(float,b)
dx,dy,dz=bx-ax,by-ay,bz-az
length=math.hypot(dx,dz)
if length<1e-6:continue
heading=(dx*fx+dz*fz)/length
if heading<.7:continue
fraction=min(1.,max(0.,((px-ax)*dx+(pz-az)*dz)/(length*length)))
projection=[ax+fraction*dx,ay+fraction*dy,az+fraction*dz]
lateral=math.hypot(px-projection[0],pz-projection[2])
height=abs(py-projection[1])
score=lateral+height*2.+(1.-heading)*3.
if height>1. or not math.isfinite(score):continue
if best is None or score<best['score']:
best=dict(index=index,fraction=fraction,projection=projection,
error_m=lateral,height_error_m=height,heading_dot=heading,score=score)
if best is not None:best['projection']=np.asarray(best['projection'],float)
return best
def same_lane_prefab_continuation(lane_ids, lanes):
@@ -117,7 +112,7 @@ def source_span_verified(lane,span):
def _horizontal_length(a, b):
return float(np.linalg.norm((np.asarray(b, float)-np.asarray(a, float))[[0, 2]]))
return math.hypot(float(b[0])-float(a[0]),float(b[2])-float(a[2]))
def _trim_tail(points, distance):
@@ -305,6 +300,9 @@ class NativeRoutePlanner:
# follows the road surface. Small grade/anchor noise should not drop a
# centered semi at speed.
MAX_CONTROL_HEIGHT_ERROR_M = .75
TURN_ALIGNMENT_MAX_SPEED_MPS = 25. * .44704
TURN_ALIGNMENT_MIN_HEADING_DOT = math.cos(math.radians(25.))
TURN_ALIGNMENT_HOLD_S = 4.
def __init__(self, *, allow_source_geometry=False):
self.allow_source_geometry=bool(allow_source_geometry)
@@ -314,12 +312,41 @@ class NativeRoutePlanner:
self.lane_id = self.route_revision = None
self.next_lane_id = self.trip_edge_index = None
self._transition_entry_lane = None
self._aligned_turn = None
self._turn_alignment_since = None
def _turn_alignment_allowed(self, sdk, now, position, selected, hit):
"""Finish a previously verified turn without dropping live steering.
Pursuit/chassis lag can exceed the straight-road heading gate at the
exit of an authored curve. Recovery is confined to that same qualified
route chain, low speed, normal lane width, and four seconds. It cannot
authorize a new turn from a misaligned initial pose.
"""
context = self._aligned_turn
speed = number(sdk.get('speed_mps'))
if (context is None or speed is None
or not 0. <= speed <= self.TURN_ALIGNMENT_MAX_SPEED_MPS
or not selected or selected[0] not in context['lane_ids']
or hit['error_m'] > 1.75
or hit['height_error_m'] > self.MAX_CONTROL_HEIGHT_ERROR_M
or hit['heading_dot'] < self.TURN_ALIGNMENT_MIN_HEADING_DOT
or math.dist(position, context['position']) > 35.):
return False
if self._turn_alignment_since is None:
if not 0. <= now-context['sampled_at'] <= .5:
return False
self._turn_alignment_since = now
return 0. <= now-self._turn_alignment_since <= self.TURN_ALIGNMENT_HOLD_S
def assess(self, scene):
now = number(scene.get('sampled_at'))
if now is None:
raise ValueError('Finite native scene time required')
empty = lambda reason: unavailable(reason, now)
def empty(reason):
self._aligned_turn = None
self._turn_alignment_since = None
return unavailable(reason, now)
if not scene.get('sdk_fresh'):
return empty('Fresh SDK pose required for native planning')
sources = scene.get('sources') or {}
@@ -383,9 +410,12 @@ class NativeRoutePlanner:
maneuver_hit = None
maneuver_ids = {maneuver.get('current_lane_id'), maneuver.get('target_lane_id')}-{None}
maneuver_stamp = number(maneuver.get('sampled_at'))
if (maneuver.get('active') is True and maneuver.get('allowed_for_gameplay') is True
moving_maneuver = (maneuver.get('active') is True and maneuver.get('allowed_for_gameplay') is True
and maneuver.get('clearance_verified') is True)
held_maneuver = (maneuver.get('maneuver_hold') is True
and maneuver.get('lane_membership_only') is True)
if ((moving_maneuver or held_maneuver)
and maneuver.get('permission_verified') is True
and maneuver.get('clearance_verified') is True
and maneuver.get('route_revision') == revision
and maneuver_stamp is not None and 0. <= now-maneuver_stamp <= .3
and len(maneuver_ids) == 2):
@@ -603,20 +633,27 @@ class NativeRoutePlanner:
# even when the next lane is connected and fully measured.
while (length < self.MAX_SPEED_COVERAGE_M or not used_edges) and len(selected) < 16:
choice = trip_policy[route_index].get(selected[-1]) if trip_policy is not None else None
if choice is not None and choice.get('kind') != 'continue':
continuation = 'gps-lane-change-required' if choice.get('kind') == 'lane-change' else choice.get('kind')
preparing_change = choice is not None and choice.get('kind') == 'lane-change'
if choice is not None and choice.get('kind') not in ('continue', 'lane-change'):
continuation = choice.get('kind')
break
# An early lane-change request is not the physical end of this
# lane. Carry a unique authored same-route continuation while a
# gap is pending, provided its trip policy still reaches the goal.
# A genuine dead end still truncates coverage and requires braking.
options = []
for edge in successors.get(selected[-1], []):
target = edge.get('to_lane_id')
if target not in lanes or target in selected:
continue
if choice is not None and target != choice.get('next_lane_id'):
if choice is not None and not preparing_change and target != choice.get('next_lane_id'):
continue
lane = lanes[target]
pair = str(lane['start_node_uid']), str(lane['end_node_uid'])
if route_index+1 >= len(pairs) or pair != pairs[route_index+1]:
continue
if preparing_change and (trip_policy[route_index+1].get(target) or {}).get('reaches_destination') is not True:
continue
error = math.dist(world[-1], points[target][0])
transition = edge.get('transition_kind') == 'road-profile'
if error <= .25 or (transition and error <= PROFILE_TRANSITION_MAX_GAP_M):
@@ -626,7 +663,8 @@ class NativeRoutePlanner:
if preferred is not None:
options = [option for option in options if option[1] == preferred]
if len(options) != 1:
continuation = 'route-end' if route_index+1 >= len(pairs) else 'connection-missing-or-ambiguous'
continuation = ('gps-lane-change-required' if preparing_change else
'route-end' if route_index+1 >= len(pairs) else 'connection-missing-or-ambiguous')
break
_, target, edge = options[0]
selected.append(target); used_edges.append(edge); route_index += 1
@@ -660,10 +698,17 @@ class NativeRoutePlanner:
qualification_truncated = (qualified_ids != selected or (len(qualified) >= 2
and math.dist(qualified[-1], world[-1]) > .01))
center_bound = 2.5 if maneuver_hit is not None and lane_id in maneuver_ids else 1.75
turn_alignment = (association_hit['heading_dot'] < .97
and not hit.get('profile_source_id')
and maneuver_hit is None
and graph.get('source_verified') is True
and lane_id in qualified_ids and len(qualified) >= 2
and self._turn_alignment_allowed(sdk, now, position,
qualified_ids, association_hit))
membership = (graph.get('source_verified') is True and bool(qualified_ids)
and association_hit['error_m'] <= center_bound
and association_hit['height_error_m'] <= self.MAX_CONTROL_HEIGHT_ERROR_M
and association_hit['heading_dot'] >= .97)
and (association_hit['heading_dot'] >= .97 or turn_alignment))
# A source-qualified span can end at a road-profile handoff even when
# the route-matched lane graph still has a continuous, forward path.
# In the native runner source geometry is an explicit experimental
@@ -695,7 +740,10 @@ class NativeRoutePlanner:
world=qualified; selected=qualified_ids
local=np.asarray(world,float)-position
self._transition_entry_lane = transition_entry_lane
qualified_coverage=sum(float(np.linalg.norm((np.asarray(b)-a)[[0,2]])) for a,b in zip(world,world[1:])) if membership else None
# One array operation replaces hundreds of tiny NumPy calls, each of
# which can yield the GIL to rendering/recording for a full time slice.
qualified_coverage=(float(np.linalg.norm(np.diff(np.asarray(world,float)[:,[0,2]],axis=0),axis=1).sum())
if membership else None)
local = np.column_stack((local[:, [0, 2]]@forward,
-local[:, 0]*forward[1]+local[:, 2]*forward[0],
-local[:, 1]))
@@ -705,11 +753,20 @@ class NativeRoutePlanner:
ordered=[local[0]]
lengths=[0.]
for point in local[1:]:
segment=float(np.linalg.norm((point-ordered[-1])[:2]))
segment=math.hypot(float(point[0]-ordered[-1][0]),float(point[1]-ordered[-1][1]))
if segment<=1e-5:continue
remaining=self.MAX_PATH_M-lengths[-1]
if remaining<=1e-5:break
ordered.append(ordered[-1]+(point-ordered[-1])*min(1.,remaining/segment))
# Keep existing vertices directly. Only the final clipped vertex
# needs interpolation; tiny array arithmetic at every vertex can
# repeatedly hand execution to a busy background Python thread.
if segment <= remaining:
ordered.append(point)
else:
fraction=remaining/segment
previous=ordered[-1]
ordered.append([float(previous[i])+(float(point[i])-float(previous[i]))*fraction
for i in range(3)])
lengths.append(lengths[-1]+min(segment,remaining))
ordered=np.asarray(ordered)
traversal=None
@@ -723,7 +780,7 @@ class NativeRoutePlanner:
prefix = [local[0]]
for point in local[1:]:
if point[0] <= prefix[-1][0]+1e-4:
if np.linalg.norm(point-prefix[-1]) < 1e-5:
if math.dist(point,prefix[-1]) < 1e-5:
continue
break
prefix.append(point)
@@ -739,7 +796,7 @@ class NativeRoutePlanner:
# the native controller consumes traversal_path and never extrapolates.
legacy_valid = len(local) >= 2 and local[-1, 0] >= 3. and local[0, 0] >= -5.
traversal_extent = float(lengths[-1]) if len(lengths) else 0.
if len(local) < 2 or local[0, 0] < -5. or traversal_extent < 3.:
if len(ordered) < 2 or ordered[0, 0] < -5. or traversal_extent < 3.:
return empty('Native route path lacks current forward coverage')
if legacy_valid:
x = np.linspace(max(0., float(local[0, 0])), min(self.MAX_PATH_M, float(local[-1, 0])), 33)
@@ -749,10 +806,26 @@ class NativeRoutePlanner:
# This is display/backward-compatibility geometry only. It is not
# promoted to the control path and deliberately contains no
# straight-line extension through the bend.
path = dict(x=[float(local[0, 0]), float(local[-1, 0])],
y=[float(local[0, 1]), float(local[-1, 1])],
z=[float(local[0, 2]), float(local[-1, 2])])
path = dict(x=[float(ordered[0, 0]), float(ordered[-1, 0])],
y=[float(ordered[0, 1]), float(ordered[-1, 1])],
z=[float(ordered[0, 2]), float(ordered[-1, 2])])
eligible = membership and bool(qualified_ids) and traversal_extent >= 3.
if eligible and not turn_alignment:
self._turn_alignment_since = None
# Only a real bend in the currently qualified prefab arms recovery.
# Do not infer a turn from lateral error or an upcoming GPS branch.
current = lanes[lane_id]
segments = np.diff(points[lane_id][:, [0, 2]], axis=0)
lengths_m = np.linalg.norm(segments, axis=1)
directions = segments[lengths_m > 1e-5] / lengths_m[lengths_m > 1e-5, None]
curved_prefab = (current.get('kind') == 'prefab' and len(directions) > 1
and float(np.min(directions @ directions[0])) < math.cos(math.radians(15.)))
if curved_prefab:
self._aligned_turn = dict(sampled_at=now, position=position.tolist(),
lane_ids=list(qualified_ids))
elif not eligible:
self._aligned_turn = None
self._turn_alignment_since = None
reason=''
delta=position-association_hit['projection']
lateral=float(-delta[0]*forward[1]+delta[2]*forward[0])
@@ -774,6 +847,7 @@ class NativeRoutePlanner:
ego_lateral_right_m=lateral,height_error_m=association_hit['height_error_m'],
profile_transition_active=bool(hit.get('profile_source_id')),
lane_change_envelope=maneuver_hit is not None and lane_id in maneuver_ids,
turn_alignment_recovery=bool(turn_alignment and eligible),
heading_dot=association_hit['heading_dot'], retained_lane=retained is not None),
continuation='qualified-span-end' if eligible and qualification_truncated else continuation,
forward_coverage_m=traversal_extent, qualified_lane_ids=qualified_ids,
+14 -2
View File
@@ -176,8 +176,15 @@ class NativeSignalPlanner:
and PHASES.get(signal.get('phase_code')) == signal.get('phase')
and evidence is not None and evidence.get('placement_verified') is True
and np.linalg.norm(xyz(evidence.get('start'))-xyz(governor['start'])) <= 1e-5)
control=next((p for p in report.get('prefab_controls',[])
if p.get('prefab_uid')==uid),{})
uncontrolled=(signal is None and control.get('loaded_segment_verified') is True
and type(control.get('semaphore_instance_count')) is int
and control['semaphore_instance_count']==0
and control.get('traffic_light_absence_verified') is True)
candidates.append(dict(distance=distance, point=point, governor=governor,
signal=signal, phase_verified=verified, lane_id=lane_id,
uncontrolled=uncontrolled,
chain=chain, error_m=hit['error'], heading_dot=float(heading@hit['heading']/heading_norm)))
except (KeyError, TypeError, ValueError, OverflowError) as exc:
rejected.append(str(exc))
@@ -190,7 +197,7 @@ class NativeSignalPlanner:
def evidence(candidate):
point, signal, governor = candidate['point'], candidate['signal'], candidate['governor']
verified = candidate['phase_verified']
return dict(unknown('', now), available=verified,
return dict(unknown('', now), available=verified or candidate['uncontrolled'],
phase=signal.get('phase') if verified else None,
phase_code=signal.get('phase_code') if verified else None,
route_revision=revision, selected_lane_id=candidate['lane_id'],
@@ -199,6 +206,7 @@ class NativeSignalPlanner:
reference_distance_m=candidate['distance'],
own_front_extent_m=front if front_verified else None,
front_geometry_verified=front_verified, signal_phase_verified=verified,
traffic_light_absence_verified=candidate['uncontrolled'],
association=dict(prefab_uid=point['prefab_uid'], semaphore_id=governor['semaphore_id'],
stop_curve_index=point['curve_index'], governed_curve_index=governor['curve_index'],
ordered_curve_chain=candidate['chain'], lane_id=candidate['lane_id'],
@@ -236,7 +244,11 @@ class NativeSignalPlanner:
result['yellow_assessment'] = dict(comfortable_deceleration_mps2=2., reaction_time_s=.3,
stopping_distance_m=speed*.3+speed*speed/4., stop_feasible=gap >= speed*.3+speed*speed/4.,
crossing_permission_verified=False)
if not chosen['phase_verified']:
if (chosen['uncontrolled'] and point['traffic_rule']=='cross_line'
and front_verified and speed is not None and speed>=-.02):
result.update(state='proceed',stop_required=False,
reason='Unsignalized junction; authored priority and observed clearance required')
elif not chosen['phase_verified']:
result['reason'] = 'Selected approach semaphore has no verified live phase'
elif not front_verified or speed is None or speed < 0.:
result['reason'] = 'Fresh native front extent and forward speed required'
+8 -6
View File
@@ -105,15 +105,15 @@ class NativeControlLog:
'coverage_speed_cap_mph coverage_cap_active stability_speed_cap_mph '
'stability_cap_active coverage_gap_hold route_gap_hold queue_brake_hold '
'retained_signal_hold signal_stop_distance_m curve_speed_cap_mph '
'curve_lateral_acceleration_mps2'),
'curve_lateral_acceleration_mps2 maneuver_brake_hold lane_loss_brake_hold'),
energy=_fields(data.get('energy_navigation'),'active state reason battery_percent trigger_percent charge_target_percent '
'route_revision stop_lane_id stop_position original_destination_preserved game_gps_modified'),
signal=_fields(signal, 'available usable_for_control reason phase phase_code state '
'stop_required stop_distance_m reference_distance_m stop_point association '
'signal_phase_verified phase_sampled_at sampled_at route_revision selected_lane_id '
'signal_phase_verified traffic_light_absence_verified phase_sampled_at sampled_at route_revision selected_lane_id '
'rejected_associations retained_stop passed_stop_points'),
crossing=_fields(crossing, 'available reason state proceed_authorized observed_clearance '
'complete_coverage conflicts association sampled_at entry_speed_cap_mps'),
'complete_coverage traffic_light_absence_verified conflicts association sampled_at entry_speed_cap_mps'),
route=_fields(route, 'available usable_for_control reason sampled_at age_s route_revision '
'selected_lane_ids lane_membership_verified association continuation forward_coverage_m '
'qualified_coverage_m source_geometry_fallback'),
@@ -126,16 +126,18 @@ class NativeControlLog:
for key,field in (('gps','ats_navigation_route'),('signals','traffic_signals'))},
maneuver=_fields(maneuver, 'available active allowed_for_gameplay state reason mode direction '
'current_lane_id target_lane_id route_revision sampled_at transition_m permission_verified '
'clearance_verified completion_verified clearance maneuver_hold signal_error'),
'clearance_verified completion_verified clearance maneuver_hold lane_membership_only signal_error'),
following=_fields(decision.get('following_guard'), 'available reason acceleration_inhibited '
'trailer_chain_incomplete lead'),
braking=_fields(decision.get('following_braking'), 'emergency gap_m reason target_speed_mps'),
geometry=_fields(decision.get('steering_geometry'), 'path_extent_m native_lane_center_error_m '
'native_path_axis native_lane_center_feedback_axis axis_limit lookahead_m '
'native_lane_center_error_rate_mps steering_rate_limit_per_s'),
'native_lane_center_error_rate_mps steering_rate_limit_per_s turn_alignment_recovery'),
timing=_fields(data.get('loop_timing'), 'elapsed_before_control_ms control_dispatch_ms '
'navigation_traffic_ms scene_snapshot_ms native_planning_ms sdk_to_control_ms '
'cabin_render_ms previous_hud_ms previous_loop_ms'),
'cabin_render_ms previous_hud_ms previous_loop_ms route_planner_ms signal_planner_ms '
'crossing_planner_ms overtake_planner_ms'),
runtime_maintenance=_bounded(data.get('runtime_maintenance')),
actuator_focus=_bounded(data.get('actuator_focus')),
release=_bounded(release))
accepted = self._enqueue('snapshot', now, fields)
+37 -14
View File
@@ -671,10 +671,12 @@ class NativeLaneGraph:
"""Fast bounded snapshots of an offline extracted graph; never extracts live."""
def __init__(self, cache_path=DEFAULT_CACHE, *, game_log=GAME_LOG,
verify_sources=True, clock=time.monotonic, radius_m=350, max_lanes=96,
validation_path=None, permissions_path=None):
validation_path=None, permissions_path=None, defer_source_checks=False):
self.clock, self.game_log = clock, Path(game_log)
self.verify_sources, self.radius_m, self.max_lanes = verify_sources, radius_m, max_lanes
self.cache, self.reason, self._next_check = None, '', 0.
self.defer_source_checks=bool(defer_source_checks)
self.source_checked_at=None
self.validation = dict(eligible_primitives=0, reason='No independent geometry observation report')
self.source_qualification = dict(qualified_primitives=0, empirically_validated=False)
self.permission_report = None
@@ -686,7 +688,8 @@ class NativeLaneGraph:
self._extent = None
try:
payload = Path(cache_path).read_bytes()
cache = json.loads(payload)
from telemetry.native_runtime_work import cooperative_json_loads
cache = cooperative_json_loads(payload)
if cache.get('schema_version') != 1 or cache.get('game_build_sha256') != BUILD_SHA256:
raise ValueError('Unsupported native lane cache provenance')
if cache.get('usable_for_control') is not False or cache.get('interpolation_verified') is not False:
@@ -723,7 +726,7 @@ class NativeLaneGraph:
permission_file = Path(permissions_path) if permissions_path is not None else Path(cache_path).parent/'lane-permissions.json'
try:
permission_payload = permission_file.read_bytes()
permission_report = json.loads(permission_payload)
permission_report = cooperative_json_loads(permission_payload)
if permission_report.get('schema_version') != 1:
raise ValueError('Unsupported native lane permission report')
if permission_report.get('graph_sha256') != hashlib.sha256(payload).hexdigest():
@@ -808,6 +811,7 @@ class NativeLaneGraph:
self.reason = ''
except (OSError, ValueError, KeyError) as exc:
self.reason = str(exc)
self.source_checked_at=self.clock()
def snapshot(self, telemetry, route=None):
now = self.clock()
@@ -821,7 +825,10 @@ class NativeLaneGraph:
boundaries=[], lanes=[], source='Mounted ATS lane definitions'))
if self.cache is None:
return base
if now >= self._next_check:
if self.defer_source_checks and self.verify_sources:
if self.source_checked_at is None or now-self.source_checked_at>2.:
return dict(base,reason='Mounted lane source validation pending')
elif now >= self._next_check:
self._check_sources()
self._next_check = now + 1.
if self.reason:
@@ -1082,7 +1089,7 @@ class NativeLaneGraphManager:
verify_sources=self.verify_sources, clock=clock,
radius_m=radius_m, max_lanes=max_lanes,
validation_path=validation_path,
permissions_path=self.permissions_path)
permissions_path=self.permissions_path,defer_source_checks=True)
self._job = None
self._job_cell = None
self._finish_thread = None
@@ -1092,11 +1099,17 @@ class NativeLaneGraphManager:
self._last_build = None
self._last_error = ''
self._closed = False
self._source_stop=threading.Event()
self._source_thread=None
self._trip_key = self._trip_requested = None
self._trip_result = None
self._trip_sources = None
self._trip_missing_key, self._trip_missing = None, []
self._trip_thread = None
if self.verify_sources:
self._source_thread=threading.Thread(target=self._check_sources_async,
name='ATS mounted lane source verifier',daemon=True)
self._source_thread.start()
if (self._reader.cache is not None and self._reader.permission_report is None
and (self.cache_path.parent/'permission-assets/lane-permission-catalog.json').is_file()):
self._finalizing = True
@@ -1121,13 +1134,21 @@ class NativeLaneGraphManager:
build(self.cache_path, catalog, self.permissions_path)
return True
def _check_sources_async(self):
# Game-log parsing and filesystem stat calls can take hundreds of
# milliseconds. Only the initial check runs before driving starts.
while not self._source_stop.wait(.75):
reader=self.reader
if reader.cache is not None:reader._check_sources()
def _refresh_permissions_async(self):
try:
if self._bind_permissions():
new_reader = NativeLaneGraph(self.cache_path, game_log=self.game_log,
verify_sources=self.verify_sources, clock=self.clock,
radius_m=self.radius_m, max_lanes=self.max_lanes,
validation_path=self.validation_path, permissions_path=self.permissions_path)
validation_path=self.validation_path, permissions_path=self.permissions_path,
defer_source_checks=True)
with self._lock:
if not self._closed:
self._reader = new_reader
@@ -1359,14 +1380,15 @@ class NativeLaneGraphManager:
if job.returncode != 0 or output is None or not output.is_file():
raise ValueError((stderr or stdout or 'native lane prefetch failed').strip()[-500:])
addition_bytes = output.read_bytes()
addition = json.loads(addition_bytes)
from telemetry.native_runtime_work import cooperative_json_loads, cooperative_json_write
addition = cooperative_json_loads(addition_bytes)
old_bytes = self.cache_path.read_bytes() if self.cache_path.exists() else None
old = json.loads(old_bytes) if old_bytes else None
old = cooperative_json_loads(old_bytes) if old_bytes else None
permission_report = None
compatible = isinstance(old, dict) and _source_identity(old) == _source_identity(addition)
if compatible and self.permissions_path.exists() and old_bytes:
try:
report = json.loads(self.permissions_path.read_text(encoding='utf-8'))
report = cooperative_json_loads(self.permissions_path.read_text(encoding='utf-8'))
if (report.get('schema_version') == 1
and report.get('graph_sha256') == hashlib.sha256(old_bytes).hexdigest()
and isinstance(report.get('road_permissions'), dict)):
@@ -1377,13 +1399,12 @@ class NativeLaneGraphManager:
if len(merged.get('lanes', ())) > MAX_CACHE_LANES or len(merged.get('connections', ())) > MAX_CACHE_CONNECTIONS:
raise ValueError('Persistent native lane cache reached its bounded size; compact/rebuild required')
pending = self.cache_path.with_suffix('.pending.json')
merged_bytes = json.dumps(merged, separators=(',', ':')).encode('utf-8')
pending.write_bytes(merged_bytes)
merged_sha256 = cooperative_json_write(pending, merged)
pending.replace(self.cache_path)
if permission_report is not None:
permission_report['graph_sha256'] = hashlib.sha256(merged_bytes).hexdigest()
permission_report['graph_sha256'] = merged_sha256
permission_pending = self.permissions_path.with_suffix('.pending.json')
permission_pending.write_text(json.dumps(permission_report, separators=(',', ':')), encoding='utf-8')
cooperative_json_write(permission_pending, permission_report)
permission_pending.replace(self.permissions_path)
# Re-resolve every road group, including newly prefetched sectors.
# Carrying the old report alone left those roads unable to pass.
@@ -1396,7 +1417,7 @@ class NativeLaneGraphManager:
verify_sources=self.verify_sources, clock=self.clock,
radius_m=self.radius_m, max_lanes=self.max_lanes,
validation_path=self.validation_path,
permissions_path=self.permissions_path)
permissions_path=self.permissions_path,defer_source_checks=True)
if new_reader.cache is None:
raise ValueError(new_reader.reason or 'merged native lane cache failed validation')
with self._lock:
@@ -1470,6 +1491,8 @@ class NativeLaneGraphManager:
return result
def close(self):
self._source_stop.set()
if self._source_thread is not None:self._source_thread.join(timeout=.5)
with self._lock:
self._closed = True
job = self._job
+10 -1
View File
@@ -54,6 +54,7 @@ class NativeObservationWorker:
def _run(self):
next_read = 0.
last_reader_stamp=last_observation_stamp=last_generation=None
try:
while True:
with self._condition:
@@ -74,7 +75,15 @@ class NativeObservationWorker:
result = dict(self.reader.snapshot(sample, *context))
stamp = result.get('sampled_at')
if isinstance(stamp, (int, float)) and math.isfinite(stamp):
result['sampled_at'] = min(stamp, input_time)
# Readers reuse their original cached timestamp.
# Keep the first handoff bound for that observation:
# a later poll must not advance it toward read end
# and fabricate a second traffic-motion sample.
if generation!=last_generation or stamp!=last_reader_stamp:
last_reader_stamp=stamp
last_observation_stamp=min(stamp,input_time)
last_generation=generation
result['sampled_at'] = last_observation_stamp
result['age_s'] = max(0., self.clock()-result['sampled_at'])
except Exception as exc:
result = dict(available=False, reason='Native '+self.kind+' read failed: '+str(exc))
+58
View File
@@ -0,0 +1,58 @@
"""Isolate read-only process-memory reads from bulk work in the control host."""
import multiprocessing
import math
import time
def _read_child(connection,factory):
reader=factory()
try:
while True:
request=connection.recv()
if request is None:return
sample,context=request
try:result=dict(reader.snapshot(sample,*context))
except Exception as exc:result=dict(available=False,reason=type(exc).__name__+': '+str(exc))
connection.send(result)
except (EOFError,BrokenPipeError,OSError):
pass
finally:reader.close();connection.close()
class NativeReaderProcess:
"""One bounded outstanding read, original request times retained on retries."""
def __init__(self,factory,*,clock=time.monotonic,context=None):
context=context or multiprocessing.get_context('spawn')
self.clock=clock;self._sent_at=None;self._closed=False
self._source_stamp=self._bound_stamp=None
self._connection,child=context.Pipe()
self._process=context.Process(target=_read_child,args=(child,factory),
name='ATS isolated GPS reader',daemon=True)
self._process.start();child.close()
@property
def pid(self):return self._process.pid
def snapshot(self,sample,*context):
if self._closed:return dict(available=False,reason='Isolated reader closed')
if self._sent_at is None:
self._sent_at=self.clock()
self._connection.send((sample,context))
if not self._connection.poll(.3):
return dict(available=False,reason='Waiting for isolated GPS observation')
result=dict(self._connection.recv());sent,self._sent_at=self._sent_at,None
stamp=result.get('sampled_at')
if isinstance(stamp,(int,float)) and math.isfinite(stamp):
# A cached child observation must keep its first request bound.
# Re-polling it cannot move the timestamp toward read completion.
if stamp!=self._source_stamp:
self._source_stamp=stamp;self._bound_stamp=min(stamp,sent)
result['sampled_at']=self._bound_stamp
result['age_s']=max(0.,self.clock()-result['sampled_at'])
return result
def close(self):
if self._closed:return
self._closed=True;self._connection.close()
if self._process.is_alive():self._process.terminate()
self._process.join(timeout=.5)
+105
View File
@@ -0,0 +1,105 @@
"""Keep bulk cache work and cyclic-collector scans out of live command deadlines."""
import gc
import hashlib
import json
import math
import sys
import threading
from pathlib import Path
import time
def thread_stack_snapshot():
"""Bounded locations only: no locals, source text, or retained frames."""
frames=sys._current_frames()
result=[]
for thread in threading.enumerate()[:16]:
frame=frames.get(thread.ident);stack=[]
while frame is not None and len(stack)<8:
stack.append(f'{Path(frame.f_code.co_filename).name}:{frame.f_lineno}:{frame.f_code.co_name}')
frame=frame.f_back
result.append(dict(thread=thread.name,stack=stack))
return result
def cooperative_json_loads(payload, *, yield_every=64, yield_fn=None):
"""Decode the identical JSON while giving other Python threads regular turns."""
pause = yield_fn or (lambda: time.sleep(0))
count = 0
def object_hook(value):
nonlocal count
count += 1
if count % yield_every == 0:
pause()
return value
return json.loads(payload, object_hook=object_hook)
def cooperative_json_dumps(value, *, yield_every=512, yield_fn=None, **options):
"""Encode complete evidence without monopolizing Python during a large row."""
pause = yield_fn or (lambda: time.sleep(0))
encoder = json.JSONEncoder(**options)
chunks = []
for count, chunk in enumerate(encoder.iterencode(value), 1):
chunks.append(chunk)
if count % yield_every == 0:
pause()
return ''.join(chunks)
def cooperative_json_write(path, value, *, yield_every=512, yield_fn=None):
"""Stream the original compact format and digest without a monolithic dump."""
pause = yield_fn or (lambda: time.sleep(0))
encoder = json.JSONEncoder(separators=(',', ':'))
digest = hashlib.sha256()
with path.open('wb') as stream:
batch = []
for chunk in encoder.iterencode(value):
batch.append(chunk)
if len(batch) >= yield_every:
encoded = ''.join(batch).encode('utf-8')
stream.write(encoded); digest.update(encoded)
batch.clear(); pause()
if batch:
encoded = ''.join(batch).encode('utf-8')
stream.write(encoded); digest.update(encoded)
return digest.hexdigest()
class NativeRuntimeMaintenance:
"""Reference counting stays active; cyclic scans require a parked, idle lease."""
def __init__(self, *, clock=time.monotonic, collector=gc):
self.clock, self.collector = clock, collector
self._restore_enabled = collector.isenabled()
self._restore_switch_interval = sys.getswitchinterval()
# Control/observation threads must not repeatedly wait a full 5 ms
# Python time slice whenever NumPy releases execution to bulk workers.
sys.setswitchinterval(min(.001,self._restore_switch_interval))
collector.disable()
self._next_collection = 0.
self.collections = 0
self.last_collection_ms = None
self.last_collected = None
def maintain(self, data, *, engaged=False, pending_engagement=False):
now = self.clock()
speed, age = data.get('speed_mps'), data.get('age')
parked = (not engaged and not pending_engagement and data.get('valid') is True
and data.get('paused') is False and data.get('park_brake') is True
and type(speed) in (float, int) and math.isfinite(speed) and abs(speed) < .1
and type(age) in (float, int) and math.isfinite(age) and 0. <= age <= .35)
if parked and now >= self._next_collection and self.collector.get_count()[0] >= 700:
started = self.clock()
self.last_collected = self.collector.collect(2)
self.last_collection_ms = (self.clock()-started)*1000.
self.collections += 1
self._next_collection = self.clock()+30.
return dict(automatic_cyclic_collection=self.collector.isenabled(),
thread_switch_interval_s=sys.getswitchinterval(),
collections=self.collections, last_collection_ms=self.last_collection_ms,
last_collected=self.last_collected, parked_collection_allowed=parked)
def close(self):
sys.setswitchinterval(self._restore_switch_interval)
if self._restore_enabled:
self.collector.enable()
+53 -2
View File
@@ -23,6 +23,10 @@ from telemetry.nearby_traffic import NearbyTrafficReader
KDOP_OFFSET = 0x650
# Pinned base_ctrl map_kdop_items: UID-ordered registry, independently checked
# against mounted prefab IDs. The nearby list omits the junction underneath us.
MAP_ITEMS_OFFSET = 0x10
MAX_MAP_ITEMS = 1000000
KDOP_INSTRUCTION_RVA = 0x47c31d
KDOP_INSTRUCTION = bytes.fromhex('4c8d81500600000f297898488d9178060000')
MAX_KDOP_ITEMS = 20000
@@ -162,7 +166,7 @@ def associate_governed_curves(report, lane_graph, rule_proof=None):
traffic_rule_definition=rule_proof or dict(verified=False,sha256=RULES_SHA256))
def read_signals(read, base, telemetry, type_reader, clock=time.monotonic):
def read_signals(read, base, telemetry, type_reader, clock=time.monotonic, prefab_uids=(), registry_indices=None):
"""Bounded identity-verified snapshot; reject phase transitions mid-read."""
started = clock()
ego = telemetry.get('world_position')
@@ -184,7 +188,42 @@ def read_signals(read, base, telemetry, type_reader, clock=time.monotonic):
if not game:
raise ValueError('No live game object for native signals')
items = array(game+KDOP_OFFSET, 8, MAX_KDOP_ITEMS)
if prefab_uids:
header = identity(game+MAP_ITEMS_OFFSET,40)
_, pointer, count, capacity, _ = struct.unpack('<5Q',header)
if not 0 <= count <= capacity <= MAX_MAP_ITEMS:
raise ValueError('Native map registry bounds invalid')
if len(prefab_uids)>MAX_PREFABS:
raise ValueError('Native map prefab lookup bound exceeded')
def registry_item(index):
item=struct.unpack('<Q',identity(pointer+index*8,8))[0]
uid=struct.unpack('<Q',identity(item+0x40,8))[0]
return item,uid
for requested in sorted(set(prefab_uids)):
uid=int(requested)
if not 0<uid<2**64:raise ValueError('Native prefab UID invalid')
cached=None if registry_indices is None else registry_indices.get(uid)
if type(cached) is int and 0<=cached<count and registry_item(cached)[1]==uid:
low=cached
else:
low,high=0,count
while low<high:
middle=(low+high)//2
_,found=registry_item(middle)
if found<uid:low=middle+1
else:high=middle
if low>=count:continue
item,found=registry_item(low)
if found!=uid:continue
if ((low and registry_item(low-1)[1]>=uid)
or (low+1<count and registry_item(low+1)[1]<=uid)):
raise ValueError('Native map registry UID order differs')
if identity(item+10,1)!=b'\x04':
raise ValueError('Native mapped prefab type differs')
if registry_indices is not None:registry_indices[uid]=low
items+=struct.pack('<Q',item)
groups, phases, prefab_count, actor_count, ignored_rules = {}, {}, 0, 0, 0
prefab_controls=[]
seen_items = set()
for offset in range(0, len(items), 8):
item = struct.unpack_from('<Q', items, offset)[0]
@@ -201,6 +240,10 @@ def read_signals(read, base, telemetry, type_reader, clock=time.monotonic):
if prefab_count > MAX_PREFABS:
raise ValueError('Native prefab count exceeds signal snapshot bound')
semaphores = array(segment+0x80, 16, MAX_SEMAPHORES_PER_PREFAB)
prefab_controls.append(dict(prefab_uid=str(uid),loaded_segment_verified=True,
semaphore_instance_count=len(semaphores)//16,
traffic_light_absence_verified=not semaphores,
source='Identity-verified loaded prefab segment semaphore array'))
for pos in range(0, len(semaphores), 16):
semaphore_id, _, actor = struct.unpack_from('<IIQ', semaphores, pos)
if not actor:
@@ -267,6 +310,7 @@ def read_signals(read, base, telemetry, type_reader, clock=time.monotonic):
return dict(available=True, reason='', source='ATS native semaphore rules',
sampled_at=clock(), age_s=0., snapshot_read_interval_monotonic=[started,clock()],
signals=signals, loaded_prefabs_observed=prefab_count,
prefab_controls=prefab_controls,
loaded_semaphore_actors_observed=actor_count, ignored_nonlight_rules=ignored_rules,
observed_live_rule_count=len(phases), range_m=MAX_RANGE_M,
build_sha256=BUILD_SHA256, complete_coverage=False, usable_for_control=False,
@@ -279,6 +323,7 @@ class NativeSignalsReader(NearbyTrafficReader):
self._cached = unavailable('Waiting for native signals')
self._rule_proof = None
self._next_rule_check = 0.
self._map_indices={}
def _connect(self):
super()._connect()
@@ -306,7 +351,13 @@ class NativeSignalsReader(NearbyTrafficReader):
try:
if not self.handle:
self._connect()
self._cached = read_signals(self._read,self.base,telemetry,self._type,self.clock)
ego=telemetry['world_position']
requested={lane['prefab_uid'] for lane in (lane_graph or {}).get('lanes',[])
if lane.get('kind')=='prefab' and lane.get('prefab_uid')
and any(math.dist(ego,p)<=MAX_RANGE_M for p in lane.get('centerline',[])[::8])}
self._map_indices={uid:index for uid,index in self._map_indices.items()
if str(uid) in requested}
self._cached = read_signals(self._read,self.base,telemetry,self._type,self.clock,requested,self._map_indices)
self._next_read = now+.1
return associate_governed_curves(self._cached,lane_graph,self._rule_proof)
except OSError as exc:
+3 -2
View File
@@ -6,6 +6,7 @@ from pathlib import Path
import struct
from telemetry.native_geometry import prefab_placement
from telemetry.native_runtime_work import cooperative_json_loads
def gas_spawns(payload):
@@ -54,7 +55,7 @@ def load_station_catalog(graph,cache_dir):
candidates=[base/'sectors'/(name+'.display.json')]+sorted((base/'prefetch').glob('*/sectors/'+name+'.display.json'))
for path in candidates:
try:
sector=json.loads(path.read_text())
sector=cooperative_json_loads(path.read_text())
if sector.get('asset_sha256')!=source['asset_sha256'] or sector.get('parser_hashes')!=parser:continue
raw=path.with_name(name+'.base').read_bytes()
if hashlib.sha256(raw).hexdigest()!=source['asset_sha256']:continue
@@ -73,7 +74,7 @@ def load_station_catalog(graph,cache_dir):
candidates=[base/'prefabs'/(token+'.json')]+sorted((base/'prefetch').glob('*/prefabs/'+token+'.json'))
for path in candidates:
try:
d=json.loads(path.read_text())
d=cooperative_json_loads(path.read_text())
if d.get('asset_sha256') not in hashes or d.get('parser_hashes')!=prefab_parser:continue
payload=path.with_suffix('.ppd').read_bytes()
if hashlib.sha256(payload).hexdigest()!=d['asset_sha256']:continue
+15 -1
View File
@@ -1,7 +1,7 @@
import unittest
import threading
from types import SimpleNamespace
from unittest.mock import Mock
from unittest.mock import Mock,patch
from control.fsd_controller import FSDController
from tests.test_integration import MockKeyboard
@@ -142,6 +142,20 @@ class ActuationTimingTests(unittest.TestCase):
self.assertIn('700 ms', self.controller.fault)
self.assertEqual(self.writes, [])
def test_timeout_diagnostics_run_after_neutral_and_cannot_override_release(self):
self.joystick.neutral=Mock()
self.controller.apply_controls(.01,'throttle',.2)
self.now=1.7
def failed_trace():
self.joystick.neutral.assert_called_once()
raise RuntimeError('trace unavailable')
with patch('telemetry.native_runtime_work.thread_stack_snapshot',side_effect=failed_trace):
self.controller._tick()
self.assertEqual(self.writes,[])
self.assertIn('700 ms',self.controller.fault)
self.assertAlmostEqual(self.controller.watchdog_diagnostics['command_age_ms'],700.)
self.assertEqual(self.controller.watchdog_diagnostics['diagnostic_error'],'RuntimeError')
if __name__ == '__main__':
unittest.main()
+63
View File
@@ -0,0 +1,63 @@
"""Companion process ownership, restart backoff and ATS close lifecycle."""
import unittest
import os
import subprocess
import sys
from unittest.mock import Mock
from tools.ats_autostart import Supervisor,ProcessLifetime
from tools.run_native_gameplay import _arguments
class ATSAutostartTests(unittest.TestCase):
@unittest.skipUnless(os.name=='nt','Windows process handles')
def test_process_lifetime_tracks_real_exit_without_killing_a_process(self):
child=subprocess.Popen([sys.executable,'-c','import sys; sys.stdin.read()'],stdin=subprocess.PIPE)
lifetime=ProcessLifetime(child.pid)
try:
self.assertTrue(lifetime.running())
child.communicate(timeout=5.)
self.assertFalse(lifetime.running())
finally:
lifetime.close()
if child.poll() is None:child.communicate(timeout=5.)
def test_launches_one_child_for_one_game_and_no_child_for_closed_or_ambiguous_game(self):
child=Mock();child.poll.return_value=None
launch=Mock(return_value=child);supervisor=Supervisor(launch,occupied=lambda:False)
supervisor.tick([],0.);supervisor.tick([1,2],1.)
launch.assert_not_called()
supervisor.tick([42],2.);supervisor.tick([42],3.)
launch.assert_called_once_with(42)
def test_existing_manual_runner_is_reused(self):
launch=Mock();supervisor=Supervisor(launch,occupied=lambda:True)
supervisor.tick([42],10.)
launch.assert_not_called()
def test_failed_runner_restarts_with_backoff_and_never_engages_controls(self):
child=Mock();child.poll.return_value=None
launch=Mock(return_value=child);supervisor=Supervisor(launch,occupied=lambda:False)
supervisor.tick([42],0.)
child.poll.return_value=1;supervisor.tick([42],1.)
supervisor.tick([42],5.)
self.assertEqual(launch.call_count,1)
child.poll.return_value=None;supervisor.tick([42],6.)
self.assertEqual(launch.call_count,2)
child.poll.return_value=1;supervisor.tick([42],7.)
self.assertEqual(supervisor.retry_at,17.)
def test_clean_game_exit_resets_retry_for_next_launch(self):
child=Mock();child.poll.return_value=None
launch=Mock(return_value=child);supervisor=Supervisor(launch,occupied=lambda:False)
supervisor.tick([42],0.);child.poll.return_value=0
supervisor.tick([],1.)
child.poll.return_value=None;supervisor.tick([43],2.)
self.assertEqual(launch.call_args.args,(43,))
def test_runner_can_follow_exact_game_process(self):
_,args=_arguments(['--game-pid','42'])
self.assertEqual(args.game_pid,42)
self.assertFalse(args.desktop_panel)
if __name__=='__main__':unittest.main()
+82
View File
@@ -0,0 +1,82 @@
import mmap
import os
import threading
import time
import unittest
import uuid
from types import SimpleNamespace,MappingProxyType
from unittest.mock import Mock
from ui.cabin_display_process import CabinDisplayProcess,display_snapshot
class CabinDisplayProcessTests(unittest.TestCase):
def test_payload_keeps_actual_selected_path_without_static_graph_or_evidence(self):
path={'available':True,'x':[0.,20.],'y':[0.,1.],'z':[0.,0.]}
data=dict(driving_scene=dict(schema_version=1,trajectory=path,decision={'engaged':True},
sources={'lane_graph':{'large':'must not travel'}}),
native_lane_graph={'lanes':['large geometry'],'trip_plan':{'state':'gaps','issues':[{'edge_index':72}]}},
pop_trajectory_controller={'duplicate':'must not travel'},nearby_traffic={'actors':[{'id':'truck'}]})
result=display_snapshot(data)
self.assertNotIn('sources',result['driving_scene'])
self.assertNotIn('lanes',result['native_lane_graph'])
self.assertNotIn('pop_trajectory_controller',result)
self.assertEqual(result['driving_scene']['trajectory'],path)
self.assertEqual(result['native_lane_graph']['trip_plan']['issues'],[{'edge_index':72}])
self.assertEqual(result['nearby_traffic'],data['nearby_traffic'])
self.assertIn('sources',data['driving_scene'])
def test_blocked_ipc_coalesces_pending_scenes_without_blocking_submit(self):
entered,unblock,latest=threading.Event(),threading.Event(),threading.Event()
packets=[]
def send(packet):
packets.append(packet)
if len(packets)==1:entered.set()
elif packet[0]['sequence']==3:latest.set()
def recv():
self.assertTrue(unblock.wait(2.));return 123.
connection=SimpleNamespace(send=send,recv=recv,close=Mock())
process=SimpleNamespace(start=Mock(),pid=123,is_alive=lambda:False,join=Mock())
context=SimpleNamespace(Pipe=lambda:(connection,SimpleNamespace(close=Mock())),Process=lambda **kw:process)
worker=CabinDisplayProcess(context=context)
try:
worker.submit({'sequence':1},True);self.assertTrue(entered.wait(2.))
worker.submit({'sequence':2},True);worker.set_roads([(MappingProxyType({'uid':'road'}),[[0.,0.,0.]])])
worker.submit({'sequence':3},False);unblock.set()
self.assertTrue(latest.wait(2.))
self.assertEqual([p[0]['sequence'] for p in packets],[1,3])
self.assertFalse(packets[-1][1])
self.assertEqual(packets[-1][2],[({'uid':'road'},[[0.,0.,0.]])])
finally:unblock.set();worker.close()
@unittest.skipUnless(os.name=='nt','Windows named cab mappings')
def test_spawned_renderer_publishes_both_screens_and_power_off(self):
from ui.dashboard_stream import SIZE,HEADER,HEADER_SIZE
names={key:'Local\\ATSCabTest-'+uuid.uuid4().hex for key in ('right','left')}
mappings={key:mmap.mmap(-1,SIZE,tagname=name) for key,name in names.items()}
worker=CabinDisplayProcess(names=names)
try:
self.assertNotEqual(worker.pid,os.getpid())
data=dict(valid=True,age=0.,engine_enabled=True,electric_enabled=True,gear=3,
speed_mph=40.,cruise_speed_mph=65.,truck_name='Semi truck 2019',status='Ready')
deadline=time.monotonic()+5
while time.monotonic()<deadline:
worker.submit(data,False)
if all(HEADER.unpack(m[:HEADER_SIZE])[6]>0 for m in mappings.values()):break
time.sleep(.05)
self.assertTrue(all(HEADER.unpack(m[:HEADER_SIZE])[6]>0 for m in mappings.values()))
before=HEADER.unpack(mappings['right'][:HEADER_SIZE])[6]
worker.submit(dict(data,engine_enabled=False,electric_enabled=False),False)
deadline=time.monotonic()+2
while time.monotonic()<deadline:
header=HEADER.unpack(mappings['right'][:HEADER_SIZE])
if (header[5]%2==0 and header[6]>before and
mappings['right'][HEADER_SIZE:HEADER_SIZE+4]==b'\0\0\0\xff'):break
time.sleep(.02)
self.assertGreater(HEADER.unpack(mappings['right'][:HEADER_SIZE])[6],before)
self.assertEqual(mappings['right'][HEADER_SIZE:HEADER_SIZE+4],b'\0\0\0\xff')
self.assertIsNone(worker.error)
finally:
worker.close()
for mapping in mappings.values():mapping.close()
+25 -16
View File
@@ -27,60 +27,69 @@ class SpeedControlTests(unittest.TestCase):
session.active=True
session.driver._axis=.04;session.driver._last=100.
self.confirm_limit(session,55.)
self.assertEqual(session.driver.target_speed_mph,60.)
self.assertEqual(session.driver.target_speed_mph,55.)
self.assertTrue(session.active)
self.assertEqual(session.driver._axis,.04)
self.assertEqual(session.driver._last,100.)
session.persist_speed();save.assert_called_once_with(60.)
session.persist_speed();save.assert_called_once_with(55.)
factory.assert_not_called()
def test_navigation_limit_uses_five_mph_trailer_offset_and_ten_mph_bobtail_offset(self):
def test_posted_limit_is_base_for_trailer_and_bobtail_adjustments(self):
trailer=GameplaySession(NativeGameplayController(),Mock())
self.confirm_limit(trailer,55.)
# Unknown own-trailer state stays conservative until the actor reader
# verifies the chain; the connected-trailer policy is also +5 MPH.
self.assertEqual(trailer.driver.target_speed_mph,60.)
# verifies the chain; either truck starts at the posted limit itself.
self.assertEqual(trailer.driver.target_speed_mph,55.)
self.assertEqual(trailer.navigation_speed_offset_mph,5.)
self.assertIsNone(trailer.trailer_attached)
bobtail=GameplaySession(NativeGameplayController(),Mock())
for now in (1.,1.1,1.2,1.31):
bobtail.observe_speed_limit(self.navigation_data(55.,trailer_attached=False),now=now)
self.assertEqual(bobtail.driver.target_speed_mph,65.)
self.assertEqual(bobtail.driver.target_speed_mph,55.)
self.assertEqual(bobtail.navigation_speed_offset_mph,10.)
self.assertFalse(bobtail.trailer_attached)
trailer.adjust_speed(20,True);bobtail.adjust_speed(20,True)
self.assertEqual(trailer.driver.target_speed_mph,60.)
self.assertEqual(bobtail.driver.target_speed_mph,65.)
trailer.adjust_speed(-20,True);bobtail.adjust_speed(-20,True)
self.assertEqual(trailer.driver.target_speed_mph,50.)
self.assertEqual(bobtail.driver.target_speed_mph,45.)
def test_detaching_trailer_raises_same_confirmed_limit_to_bobtail_offset(self):
def test_detaching_trailer_changes_tolerance_without_resetting_target(self):
session=GameplaySession(NativeGameplayController(),Mock())
for now in (1.,1.1,1.2,1.31):
session.observe_speed_limit(self.navigation_data(55.,trailer_attached=True),now=now)
self.assertEqual(session.driver.target_speed_mph,60.)
self.assertEqual(session.driver.target_speed_mph,55.)
session.adjust_speed(1,True)
for now in (2.,2.1,2.2,2.31):
session.observe_speed_limit(self.navigation_data(55.,trailer_attached=False),now=now)
self.assertEqual(session.driver.target_speed_mph,65.)
self.assertEqual(session.driver.target_speed_mph,60.)
self.assertEqual(session.navigation_speed_policy()['allowed_adjustment_mph'],10.)
def test_manual_override_survives_same_lower_and_missing_limits(self):
def test_manual_override_survives_same_and_missing_limits_but_new_sign_resets(self):
session=GameplaySession(NativeGameplayController(),Mock())
self.confirm_limit(session,55.)
session.adjust_speed(-4,True)
self.confirm_limit(session,55.,2.)
self.assertEqual(session.driver.target_speed_mph,40.)
self.assertEqual(session.driver.target_speed_mph,50.)
session.observe_speed_limit(self.navigation_data(0.),now=2.4)
self.confirm_limit(session,55.,3.)
self.assertEqual(session.driver.target_speed_mph,40.)
self.assertEqual(session.driver.target_speed_mph,50.)
self.confirm_limit(session,45.,4.)
self.assertEqual(session.driver.target_speed_mph,40.)
self.assertEqual(session.driver.target_speed_mph,45.)
self.confirm_limit(session,55.,5.)
self.assertEqual(session.driver.target_speed_mph,60.)
self.assertEqual(session.driver.target_speed_mph,55.)
def test_higher_limit_never_lowers_manual_target_and_respects_existing_cap(self):
def test_each_confirmed_sign_resets_old_target_and_respects_existing_cap(self):
session=GameplaySession(NativeGameplayController(target_speed_mph=70.),Mock())
self.confirm_limit(session,55.)
self.confirm_limit(session,65.,2.)
self.assertEqual(session.driver.target_speed_mph,70.)
self.assertEqual(session.driver.target_speed_mph,65.)
self.confirm_limit(session,85.,3.)
self.assertEqual(session.driver.target_speed_mph,80.)
self.confirm_limit(session,25.,4.)
self.assertEqual(session.driver.target_speed_mph,25.)
def test_invalid_stale_or_unconfirmed_sign_cannot_raise_target(self):
session=GameplaySession(NativeGameplayController(),Mock())
+24
View File
@@ -57,6 +57,30 @@ def passed_stop_fixture(phase=8,actors=None):
class NativeCrossingTests(unittest.TestCase):
def test_unsignalized_junction_restarts_only_with_exact_loaded_absence_and_clear_gap(self):
for blocked in (False,True):
scene=fixture([crossing_actor()] if blocked else [])
report=scene['sources']['signals']['data']
report['signals']=[]
report['prefab_controls']=[dict(prefab_uid='42',loaded_segment_verified=True,
semaphore_instance_count=0,traffic_light_absence_verified=True)]
scene['signal_plan']=NativeSignalPlanner().assess(scene)
self.assertIsNone(scene['signal_plan']['phase'])
result=assess(scene)
self.assertEqual(result['proceed_authorized'],not blocked,result)
self.assertTrue(result['traffic_light_absence_verified'])
report['prefab_controls']=[]
scene['signal_plan']=NativeSignalPlanner().assess(scene)
self.assertFalse(assess(scene)['proceed_authorized'])
def test_live_red_cannot_be_overridden_by_absence_marker(self):
scene=fixture(phase=2)
scene['sources']['signals']['data']['prefab_controls']=[dict(prefab_uid='42',
loaded_segment_verified=True,semaphore_instance_count=0,traffic_light_absence_verified=True)]
scene['signal_plan']=NativeSignalPlanner().assess(scene)
self.assertFalse(scene['signal_plan']['traffic_light_absence_verified'])
self.assertFalse(assess(scene)['proceed_authorized'])
def test_sweep_culling_preserves_distance_past_skipped_segments(self):
path=np.column_stack((np.arange(101.),np.zeros(101),np.zeros(101)))
intervals=_intervals([80.,0.,-2.],(4.,2.,2.),0.,path,1.5,(0.,3.))
+26
View File
@@ -34,6 +34,32 @@ def inputs(now=10.,actors=None):
class NativeGameplayTests(unittest.TestCase):
def test_game_close_exits_loop_and_releases_controls_before_reading_or_dispatching(self):
session=Mock();session.driver.requires_inference=False
telemetry=Mock();cv=Mock()
run_loop(session=session,telemetry=telemetry,window=Mock(),monitor=Mock(),
capture=None,brain=None,actions=None,guard=None,hud=Mock(),cv=cv,
guarded_step=None,stop_when=lambda:True)
self.assertTrue(any('ATS closed' in call.args[0] for call in session.release.call_args_list))
telemetry.get_data.assert_not_called()
session.apply.assert_not_called()
def test_turn_alignment_keeps_live_steering_and_nonzero_speed_target(self):
controller=NativeGameplayController(65.)
data=inputs();data.update(speed_mps=8.,speed_mph=8.*2.2369362921)
plan=data['native_route_plan']
plan['association']=dict(ego_lateral_right_m=.5,heading_dot=.945,
turn_alignment_recovery=True)
plan['path']['y']=[x*.3 for x in plan['path']['x']]
result=controller.assess(None,data,None,now=10.)
self.assertTrue(result['allowed'])
self.assertTrue(result['steering_geometry']['available'])
self.assertTrue(result['steering_geometry']['turn_alignment_recovery'])
self.assertLess(result['requested_axis'],0.)
self.assertGreater(result['effective_speed_target_mph'],0.)
self.assertLessEqual(result['effective_speed_target_mph'],20.)
self.assertFalse(result.get('lane_loss_brake_hold',False))
def test_fresh_observed_body_outside_route_clears_old_braking_hold(self):
controller=NativeGameplayController(40.)
first=inputs(actors=[actor(forward=12.)]);first['speed_mps']=8.
+1 -1
View File
@@ -1,4 +1,4 @@
"""Vectorized lane association preserves the original geometric selection."""
"""Lane association preserves the original geometric selection."""
import unittest
import numpy as np
+22
View File
@@ -5,6 +5,7 @@ import math
from pathlib import Path
import tempfile
import unittest
from unittest.mock import Mock
from telemetry.native_lanes import (build_lane_graph, NativeLaneGraph, BUILD_SHA256,
PROFILE_TRANSITION_MAX_GAP_M,
@@ -201,6 +202,27 @@ class ExperimentalRoadQualificationTests(unittest.TestCase):
class NativeLaneSnapshotTests(unittest.TestCase):
def test_background_source_check_cannot_block_or_refresh_its_own_validation_age(self):
r,anchors=fixture();graph=build_lane_graph([r],anchors)
graph.update(schema_version=1,game_build_sha256=BUILD_SHA256,
usable_for_control=False,interpolation_verified=False,provenance={})
now=[10.]
with tempfile.TemporaryDirectory() as folder:
path=Path(folder)/'graph.json';path.write_text(json.dumps(graph))
reader=NativeLaneGraph(path,verify_sources=False,clock=lambda:now[0],defer_source_checks=True)
reader.verify_sources=True;reader.source_checked_at=10.
reader._check_sources=Mock(side_effect=AssertionError('No disk verification in snapshot'))
data=dict(valid=True,position_valid=True,paused=False,world_position=[50.,0.,0.])
self.assertTrue(reader.snapshot(data)['available'])
now[0]=11.9;self.assertTrue(reader.snapshot(data)['available'])
self.assertEqual(reader.source_checked_at,10.)
now[0]=12.1
result=reader.snapshot(data)
self.assertFalse(result['available']);self.assertIn('validation pending',result['reason'])
reader.source_checked_at=now[0];reader.reason='Native lane source archive changed'
self.assertFalse(reader.snapshot(data)['available'])
reader._check_sources.assert_not_called()
def test_snapshot_is_bounded_and_explicitly_noncontrol(self):
r, anchors = fixture()
graph = build_lane_graph([r], anchors)
+24
View File
@@ -44,6 +44,30 @@ def await_result(worker, data):
class NativeObservationWorkerTests(unittest.TestCase):
def test_cached_read_cannot_advance_first_handoff_timestamp(self):
class CachedReader:
def __init__(self):self.stamp=None;self.calls=0
def snapshot(self,data):
self.calls+=1
if self.stamp is None:
time.sleep(.07)
self.stamp=time.monotonic()
return dict(available=True,sampled_at=self.stamp,calls=self.calls,actors=[])
def close(self):pass
reader=CachedReader();worker=NativeObservationWorker(reader,kind='traffic',interval=.01)
try:
first=await_result(worker,sdk())
deadline=time.monotonic()+1.
while time.monotonic()<deadline:
later=worker.snapshot(sdk())
if later.get('calls',0)>first['calls']:break
time.sleep(.005)
else:self.fail('Cached result not published')
self.assertEqual(first['sampled_at'],later['sampled_at'])
self.assertLess(first['sampled_at'],reader.stamp-.05)
self.assertGreaterEqual(later['age_s'],first['age_s'])
finally:worker.close()
def test_slow_memory_read_does_not_block_control_and_retains_real_age(self):
reader = BlockingReader()
worker = NativeObservationWorker(reader, kind='traffic', interval=1.)
+34
View File
@@ -50,6 +50,40 @@ def plan_for(s):
class NativeOvertakeTests(unittest.TestCase):
def test_new_unknown_motion_behind_committed_change_does_not_stop_or_cancel_it(self):
planner=NativeOvertakePlanner();s,_=scene();first=planner.assess(s,plan_for(s))
unknown=actor('new-rear',forward=-50.,right=-3.6)
unknown['motion_available']=False
s,data=scene(now=10.1,actors=[unknown],prior=first)
plan=plan_for(s);result=planner.assess(s,plan)
self.assertTrue(result['active'],result['reason'])
self.assertFalse(result.get('maneuver_hold',False))
self.assertEqual(result['world_path'],first['world_path'])
data.update(driving_scene=s,native_route_plan=plan,native_overtake_plan=result)
decision=NativeGameplayController(75.).assess(None,data,None,now=10.1)
self.assertTrue(decision['allowed'])
self.assertGreater(decision['effective_speed_target_mph'],0.)
def test_blocked_midpoint_retains_membership_without_claiming_clearance(self):
planner=NativeOvertakePlanner();s,_=scene();first=planner.assess(s,plan_for(s))
path=np.asarray(first['world_path']);point=path[np.argmin(abs(path[:,0]+1.8))].tolist()
obstacle=actor('intruder',forward=0.,right=-3.6-point[0],**motion(25.))
s,_=scene(now=10.1,position=point,actors=[obstacle],prior=first)
blocked=planner.assess(s,plan_for(s))
self.assertTrue(blocked['maneuver_hold'])
self.assertTrue(blocked['lane_membership_only'])
self.assertFalse(blocked['active']);self.assertFalse(blocked['clearance_verified'])
s,data=scene(now=10.2,position=point,actors=[obstacle],prior=blocked)
plan=plan_for(s)
self.assertTrue(plan['usable_for_control'],plan['reason'])
self.assertTrue(plan['association']['lane_change_envelope'])
data.update(driving_scene=s,native_route_plan=plan,native_overtake_plan=blocked)
decision=NativeGameplayController(75.).assess(None,data,None,now=10.2)
self.assertTrue(decision['allowed']);self.assertEqual(decision['action'],'brake')
self.assertTrue(decision['maneuver_brake_hold'])
s['lane_maneuver']['permission_verified']=False
self.assertFalse(plan_for(s)['usable_for_control'])
def test_pass_starts_from_current_station_not_distant_road_origin(self):
s,_=scene(); planner=NativeOvertakePlanner(); original=copy.deepcopy(s)
result=planner.assess(s,plan_for(s))
+62
View File
@@ -0,0 +1,62 @@
import os
import time
import unittest
from types import SimpleNamespace
from unittest.mock import Mock
from telemetry.native_reader_process import NativeReaderProcess
class ReadOnlyTestReader:
def snapshot(self,sample,*context):
return dict(available=True,sampled_at=time.monotonic(),value=sample['value'],pid=os.getpid())
def close(self):pass
class NativeReaderProcessTests(unittest.TestCase):
def fake(self,result,polls):
connection=SimpleNamespace(send=Mock(),poll=Mock(side_effect=polls),recv=Mock(return_value=result),close=Mock())
process=SimpleNamespace(start=Mock(),pid=123,is_alive=lambda:False,join=Mock())
context=SimpleNamespace(Pipe=lambda:(connection,SimpleNamespace(close=Mock())),Process=lambda **kw:process)
now=[10.];reader=NativeReaderProcess(ReadOnlyTestReader,context=context,clock=lambda:now[0])
self.addCleanup(reader.close)
return reader,connection,now
def test_late_reply_stays_bound_to_original_request_without_backlog(self):
reader,connection,now=self.fake(dict(available=True,sampled_at=10.7),[False,True])
self.assertFalse(reader.snapshot({'value':1})['available'])
now[0]=10.8
result=reader.snapshot({'value':2})
connection.send.assert_called_once_with(({'value':1},()))
self.assertEqual(result['sampled_at'],10.)
self.assertAlmostEqual(result['age_s'],.8)
def test_cached_reader_timestamp_cannot_advance_during_process_handoff(self):
reader,_,now=self.fake(dict(available=True,sampled_at=9.9),[True,True])
first=reader.snapshot({'value':1});now[0]=10.1
second=reader.snapshot({'value':1})
self.assertEqual(first['sampled_at'],9.9)
self.assertEqual(second['sampled_at'],9.9)
self.assertAlmostEqual(second['age_s'],.2)
def test_cached_late_child_reply_keeps_its_first_handoff_bound(self):
reader,_,now=self.fake(dict(available=True,sampled_at=10.7),[True,True])
first=reader.snapshot({'value':1});now[0]=10.8
second=reader.snapshot({'value':1})
self.assertEqual(first['sampled_at'],10.)
self.assertEqual(second['sampled_at'],10.)
self.assertAlmostEqual(second['age_s'],.8)
def test_spawned_reader_uses_another_process_and_releases_it_on_close(self):
reader=NativeReaderProcess(ReadOnlyTestReader)
try:
deadline=time.monotonic()+3
while time.monotonic()<deadline:
result=reader.snapshot({'value':'native observation'})
if result.get('available'):break
self.assertTrue(result['available'])
self.assertEqual(result['value'],'native observation')
self.assertNotEqual(result['pid'],os.getpid())
self.assertEqual(result['pid'],reader.pid)
finally:reader.close()
self.assertFalse(reader._process.is_alive())
+101
View File
@@ -29,6 +29,92 @@ def scene(position=None, lanes=None, connections=None):
class NativeRoutePlannerTests(unittest.TestCase):
def turn_exit_scene(self, position=None, yaw=.25, now=10., speed=8.):
a=lane('turn','1','2',[0.,0.,0.],[-30.,0.,-35.])
a.update(kind='prefab',centerline=[[0.,0.,0.],[0.,0.,-20.],
[-5.,0.,-30.],[-15.,0.,-35.],[-30.,0.,-35.]])
b=lane('exit','2','3',[-30.,0.,-35.],[-100.,0.,-35.])
for record in (a,b):
points=np.asarray(record['centerline'])
length=float(np.linalg.norm(np.diff(points[:,[0,2]],axis=0),axis=1).sum())
record['validated_spans']=[dict(start_s_m=0.,end_s_m=length,
usable_for_control=True,evidence_sha256='measured')]
s=scene(position=position or [-16.,0.,-35.],lanes=[a,b],connections=[dict(
from_lane_id='turn',to_lane_id='exit',heading_dot=1.)])
s['sampled_at']=now
s['sdk'].update(world_rotation=[yaw,0.,0.],speed_mps=speed)
s['sources']['lane_graph']['data']['source_verified']=True
return s
def test_verified_turn_exit_keeps_path_through_heading_lag_and_lane_handoff(self):
planner=NativeRoutePlanner()
self.assertTrue(planner.assess(self.turn_exit_scene())['usable_for_control'])
for now,position in ((10.1,[-25.,0.,-35.]),(10.2,[-32.,0.,-35.])):
result=planner.assess(self.turn_exit_scene(position,yaw=.2,now=now))
self.assertTrue(result['usable_for_control'],result['reason'])
self.assertTrue(result['association']['turn_alignment_recovery'])
self.assertGreater(result['forward_coverage_m'],50.)
def test_turn_alignment_requires_prior_aligned_qualified_turn(self):
self.assertFalse(NativeRoutePlanner().assess(
self.turn_exit_scene([-25.,0.,-35.],yaw=.2))['usable_for_control'])
planner=NativeRoutePlanner()
s=self.turn_exit_scene()
s['sources']['lane_graph']['data']['lanes'][0]['kind']='road'
self.assertTrue(planner.assess(s)['usable_for_control'])
self.assertFalse(planner.assess(self.turn_exit_scene(
[-25.,0.,-35.],yaw=.2,now=10.1))['usable_for_control'])
def test_turn_alignment_does_not_relax_speed_lane_height_direction_or_source_gates(self):
for case in ('speed','center','height','heading','unverified','qualification','route','stale'):
with self.subTest(case=case):
planner=NativeRoutePlanner()
planner.assess(self.turn_exit_scene())
s=self.turn_exit_scene([-25.,0.,-35.],yaw=.2,now=10.1)
graph=s['sources']['lane_graph']['data']
if case=='speed':s['sdk']['speed_mps']=26.*.44704
elif case=='center':s['sdk']['world_position'][2]=-37.
elif case=='height':s['sdk']['world_position'][1]=.8
elif case=='heading':s['sdk']['world_rotation'][0]=.16
elif case=='unverified':graph['source_verified']=False
elif case=='qualification':graph['lanes'][0]['validated_spans']=[]
elif case=='route':s['sources']['route']['data']['revision']='different'
elif case=='stale':s['sources']['route']['fresh']=False
self.assertFalse(planner.assess(s)['usable_for_control'])
def test_turn_alignment_grace_expires_and_stale_scene_disarms_it(self):
for stale in (False,True):
planner=NativeRoutePlanner()
planner.assess(self.turn_exit_scene())
self.assertTrue(planner.assess(self.turn_exit_scene(
[-25.,0.,-35.],yaw=.2,now=10.1))['usable_for_control'])
if stale:
s=self.turn_exit_scene(now=10.2);s['sdk_fresh']=False
self.assertFalse(planner.assess(s)['usable_for_control'])
result=planner.assess(self.turn_exit_scene(
[-25.,0.,-35.],yaw=.2,now=10.3 if stale else 14.11))
self.assertFalse(result['usable_for_control'])
def test_turn_alignment_restores_normal_gate_when_aligned(self):
planner=NativeRoutePlanner();planner.assess(self.turn_exit_scene())
planner.assess(self.turn_exit_scene([-25.,0.,-35.],yaw=.2,now=10.1))
result=planner.assess(self.turn_exit_scene([-32.,0.,-35.],yaw=.25,now=10.2))
self.assertTrue(result['usable_for_control'])
self.assertFalse(result['association']['turn_alignment_recovery'])
self.assertIsNone(planner._turn_alignment_since)
def test_tiny_forward_vertex_does_not_discard_full_authored_traversal(self):
a=lane('a','1','2',[0.,0.,0.],[0.,0.,-40.])
a['centerline']=[[0.,0.,0.],[0.,0.,-10.],[0.,0.,-40.]]
a['validated_spans']=[dict(start_s_m=0.,end_s_m=40.,
usable_for_control=True,evidence_sha256='measured')]
for epsilon in (.00002,.00005,.00009):
s=scene(position=[0.,0.,-10+epsilon],lanes=[a],connections=[])
s['sources']['lane_graph']['data']['source_verified']=True
result=NativeRoutePlanner().assess(s)
self.assertTrue(result['usable_for_control'], result['reason'])
self.assertGreater(result['forward_coverage_m'],30.)
def test_route_follows_connected_lane_and_rejects_wrong_exit(self):
s=scene();original=copy.deepcopy(s)
result=NativeRoutePlanner().assess(s)
@@ -228,6 +314,21 @@ class NativeRoutePlannerTests(unittest.TestCase):
self.assertAlmostEqual(result['qualified_coverage_m'],790.)
self.assertEqual(result['forward_coverage_m'],100.)
def test_dense_banked_path_clips_at_forecast_without_losing_height(self):
candidate=lane('a','1','2',[0.,0.,0.],[0.,4.,-800.])
candidate['centerline']=np.linspace([0.,0.,0.],[0.,4.,-800.],1601).tolist()
candidate['validated_spans']=[dict(start_s_m=0.,end_s_m=800.,usable_for_control=True,evidence_sha256='measured')]
s=scene(position=[0.,.05,-10.],lanes=[candidate],connections=[])
s['sources']['lane_graph']['data']['source_verified']=True
result=NativeRoutePlanner().assess(s)
self.assertTrue(result['usable_for_control'])
self.assertAlmostEqual(result['qualified_coverage_m'],790.)
path=result['traversal_path']
self.assertAlmostEqual(path['s'][-1],100.)
self.assertAlmostEqual(path['x'][-1],100.)
self.assertAlmostEqual(path['z'][-1],-.5)
self.assertTrue(all(a<b for a,b in zip(path['s'],path['s'][1:])))
def test_connected_handoff_keeps_current_lane_until_endpoint_is_consumed(self):
candidates=[lane('a','1','2',[0.,0.,0.],[0.,0.,-40.]),lane('b','2','3',[0.,0.,-40.],[0.,0.,-120.])]
for l,length in zip(candidates,(40.,80.)):
+33
View File
@@ -0,0 +1,33 @@
import subprocess
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
from tools.run_native_gameplay import _arguments, _build_info
class NativeRunnerTests(unittest.TestCase):
def test_normal_launch_keeps_cab_displays_and_compact_diagnostics(self):
_,args=_arguments([])
self.assertFalse(args.desktop_panel)
self.assertFalse(args.record)
self.assertEqual(args.input,'auto')
_,args=_arguments(['--desktop-panel','--record'])
self.assertTrue(args.desktop_panel)
self.assertTrue(args.record)
_,args=_arguments(['--cab-only','--record','--no-record'])
self.assertFalse(args.desktop_panel)
self.assertFalse(args.record and not args.no_record)
def test_startup_fingerprint_distinguishes_local_edits_even_without_git(self):
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp);(root/'control').mkdir()
source=root/'control'/'controller.py';source.write_text('first')
with patch('tools.run_native_gameplay.subprocess.run',side_effect=subprocess.SubprocessError):
first=_build_info(root)
self.assertEqual(first,_build_info(root))
source.write_text('second')
self.assertNotEqual(first['source_sha256'],_build_info(root)['source_sha256'])
self.assertEqual(first['revision'],'unknown')
self.assertIsNone(first['tracked_changes'])
+86
View File
@@ -0,0 +1,86 @@
import hashlib
import json
from pathlib import Path
import tempfile
import sys
import unittest
from telemetry.native_runtime_work import (NativeRuntimeMaintenance,
cooperative_json_loads, cooperative_json_write, cooperative_json_dumps)
class Collector:
def __init__(self, enabled=True):
self.enabled=enabled; self.calls=[]
def isenabled(self):return self.enabled
def disable(self):self.enabled=False
def enable(self):self.enabled=True
def get_count(self):return (1000,0,0)
def collect(self, generation):self.calls.append(generation); return 7
def parked():
return dict(valid=True,paused=False,age=.01,park_brake=True,speed_mps=0.)
class NativeRuntimeWorkTests(unittest.TestCase):
def test_native_thread_slice_is_shortened_and_original_setting_restored(self):
original=sys.getswitchinterval()
policy=NativeRuntimeMaintenance(collector=Collector())
try:
self.assertLessEqual(sys.getswitchinterval(),.001)
self.assertEqual(policy.maintain(parked())['thread_switch_interval_s'],sys.getswitchinterval())
finally:policy.close()
self.assertEqual(sys.getswitchinterval(),original)
def test_collection_never_interrupts_active_pending_moving_or_unknown_states(self):
cases=[(parked(),True,False),(parked(),False,True)]
for changes in ({'speed_mps':5.},{'park_brake':False},{'valid':False},
{'paused':True},{'age':.5},{'speed_mps':float('nan')},
{'speed_mps':True}):
cases.append((dict(parked(),**changes),False,False))
collector=Collector(); policy=NativeRuntimeMaintenance(collector=collector)
try:
for data,active,pending in cases:
state=policy.maintain(data,engaged=active,pending_engagement=pending)
self.assertFalse(state['parked_collection_allowed'])
self.assertFalse(collector.enabled)
self.assertEqual(collector.calls,[])
finally:policy.close()
self.assertTrue(collector.enabled)
def test_parked_collection_is_rate_limited_and_original_gc_state_restored(self):
now=[10.]; collector=Collector(enabled=False)
policy=NativeRuntimeMaintenance(clock=lambda:now[0],collector=collector)
self.assertEqual(policy.maintain(parked())['last_collected'],7)
now[0]=20.; policy.maintain(parked())
self.assertEqual(collector.calls,[2])
now[0]=40.; policy.maintain(parked())
self.assertEqual(collector.calls,[2,2])
policy.close(); self.assertFalse(collector.enabled)
def test_cooperative_decode_keeps_validation_data_exact_and_yields(self):
data={'lanes':[{'id':str(i),'points':[[1.,2.,3.]],'unicode':'\u00e9','none':None} for i in range(200)]}
payload=json.dumps(data).encode(); yields=[]
self.assertEqual(cooperative_json_loads(payload,yield_fn=lambda:yields.append(1)),data)
self.assertGreater(len(yields),1)
with self.assertRaises(json.JSONDecodeError):cooperative_json_loads(b'{"truncated":')
def test_streamed_cache_is_byte_identical_and_digest_still_pins_its_source(self):
data={'lanes':[{'id':str(i),'points':[[.1,-2.,3e-4]],'unicode':'\u00e9'} for i in range(200)]}
expected=json.dumps(data,separators=(',',':')).encode()
with tempfile.TemporaryDirectory() as directory:
path=Path(directory)/'cache.json'; yields=[]
digest=cooperative_json_write(path,data,yield_fn=lambda:yields.append(1))
self.assertEqual(path.read_bytes(),expected)
self.assertEqual(digest,hashlib.sha256(expected).hexdigest())
self.assertGreater(len(yields),1)
def test_full_evidence_encoding_yields_and_preserves_strict_json(self):
data={'lanes':[{'id':str(i),'points':[[.1,-2.,3e-4]],'unicode':'\u00e9'} for i in range(200)]}
yields=[]
actual=cooperative_json_dumps(data,allow_nan=False,yield_fn=lambda:yields.append(1))
self.assertEqual(actual,json.dumps(data,allow_nan=False))
self.assertGreater(len(yields),1)
with self.assertRaises(ValueError):
cooperative_json_dumps({'invalid':float('nan')},allow_nan=False)
+12
View File
@@ -44,6 +44,18 @@ def drive_tick(controller, scene):
class NativeSignalControlFlowTests(unittest.TestCase):
def test_held_missing_light_resumes_when_exact_junction_is_unsignalized(self):
controller=NativeGameplayController()
self.assertEqual(drive_tick(controller,scene_at(10.))['action'],'brake')
for now in (10.1,10.2,10.3,10.4):
scene=scene_at(now)
scene['sources']['signals']['data']['signals']=[]
scene['sources']['signals']['data']['prefab_controls']=[dict(prefab_uid='42',
loaded_segment_verified=True,semaphore_instance_count=0,traffic_light_absence_verified=True)]
decision=drive_tick(controller,scene)
self.assertTrue(decision['native_crossing_plan']['proceed_authorized'],decision)
self.assertEqual(decision['action'],'throttle',decision)
def test_red_missing_overshot_and_fresh_green_departure(self):
controller=NativeGameplayController()
for scene in (scene_at(10.),scene_at(10.1,signal_missing=True),
+48 -2
View File
@@ -41,12 +41,58 @@ class Fixture:
return raw[address-start:address-start+size]
raise OSError('Unmapped test fixture')
def snapshot(self):
def snapshot(self,**kwargs):
return read_signals(self.read,self.base,dict(world_position=[0.,0.,0.]),
lambda v:self.types[v],clock=lambda:5.)
lambda v:self.types[v],clock=lambda:5.,**kwargs)
class NativeSignalTests(unittest.TestCase):
def test_registry_finds_junction_omitted_from_nearby_list(self):
f=Fixture()
f.memory[f.game+KDOP_OFFSET]=struct.pack('<5Q',0,0,0,0,0)
f.memory[f.game+0x10]=struct.pack('<5Q',0,0x270000,1,1,0)
f.memory[0x270000]=struct.pack('<Q',f.item)
report=f.snapshot(prefab_uids={'42'})
self.assertEqual(report['signals'][0]['prefab_uid'],'42')
self.assertFalse(report['prefab_controls'][0]['traffic_light_absence_verified'])
def test_only_identity_verified_empty_segment_proves_unsignalized(self):
f=Fixture()
f.memory[f.segment+0x80]=struct.pack('<5Q',0,0,0,0,0)
report=f.snapshot()
self.assertTrue(report['prefab_controls'][0]['traffic_light_absence_verified'])
self.assertEqual(report['prefab_controls'][0]['semaphore_instance_count'],0)
# Unsupported gates, absent actors or an empty nearby list are not
# proof that a selected junction has no traffic lights.
self.assertFalse(Fixture(rule_kind=0x4000).snapshot()['prefab_controls'][0]['traffic_light_absence_verified'])
f=Fixture();f.memory[f.game+KDOP_OFFSET]=struct.pack('<5Q',0,0,0,0,0)
self.assertEqual(f.snapshot()['prefab_controls'],[])
def test_torn_registry_header_is_rejected(self):
f=Fixture()
f.memory[f.game+0x10]=struct.pack('<5Q',0,0x270000,1,1,0)
f.memory[0x270000]=struct.pack('<Q',f.item)
def mutate(address,count):
if address==f.game+0x10 and count==2:
f.memory[address]=struct.pack('<5Q',0,0,0,0,0)
f.mutate=mutate
with self.assertRaisesRegex(ValueError,'graph changed'):
f.snapshot(prefab_uids={'42'})
def test_registry_index_hint_is_revalidated_and_shifted_uid_is_searched(self):
f=Fixture()
f.memory[f.game+0x10]=struct.pack('<5Q',0,0x270000,1,1,0)
f.memory[0x270000]=struct.pack('<Q',f.item)
indices={42:0}
self.assertEqual(f.snapshot(prefab_uids={'42'},registry_indices=indices)['signals'][0]['prefab_uid'],'42')
other=f.item+0x2000
raw=bytearray(80);raw[10]=4;struct.pack_into('<2Q',raw,64,41,f.segment)
f.memory[other]=bytes(raw)
f.memory[f.game+0x10]=struct.pack('<5Q',0,0x270000,2,2,0)
f.memory[0x270000]=struct.pack('<2Q',other,f.item)
f.snapshot(prefab_uids={'42'},registry_indices=indices)
self.assertEqual(indices[42],1)
def test_exact_live_phases_group_model_only_heads_without_inventing_stopline(self):
for code,phase in PHASES.items():
r=Fixture(code).snapshot()
+26
View File
@@ -56,6 +56,32 @@ def trip_scene(r,g,p):
class WholeTripTests(unittest.TestCase):
def test_pending_change_keeps_verified_current_lane_through_highway_segments(self):
lanes=[]
for start,end,z0,z1 in [('1','2',0.,-150.),('2','3',-150.,-750.)]:
for suffix,x in [('inner',-3.6),('outer',0.)]:
lanes.append(lane(start+suffix,start,end,[x,0.,z0],[x,0.,z1],
road_uid=start,travel_direction=1))
lanes.append(lane('exit','3','4',[-3.6,0.,-750.],[-3.6,0.,-850.]))
g=dict(source_verified=True,lanes=lanes,connections=[edge('1inner','2inner'),
edge('1outer','2outer'),edge('2inner','exit')])
permissions=dict(available=True,boundaries=[dict(inner_lane_id=k+'inner',outer_lane_id=k+'outer',
same_direction=True,definition_only=True,status='allowed') for k in ('1','2')])
r=route('1','2','3','4');p=compile_trip(r,g,cache_sha256='hash',permissions=permissions)
self.assertEqual(p['lane_policy'][0]['1outer']['kind'],'lane-change')
s=trip_scene(r,g,p)
plan=NativeRoutePlanner().assess(s)
self.assertTrue(plan['usable_for_control'],plan['reason'])
self.assertEqual(plan['selected_lane_ids'],['1outer','2outer'])
self.assertGreater(plan['qualified_coverage_m'],700.)
self.assertEqual(plan['route_lane_change']['to_lane_id'],'1inner')
self.assertTrue(plan['gps_lane_preparation_pending'])
s['sources']['lane_graph']['data']['connections']=[edge('1inner','2inner'),edge('2inner','exit')]
plan=NativeRoutePlanner().assess(s)
self.assertEqual(plan['selected_lane_ids'],['1outer'])
self.assertLess(plan['qualified_coverage_m'],150.)
self.assertEqual(plan['continuation'],'gps-lane-change-required')
def test_later_exit_selects_an_earlier_same_exit_lane_shift(self):
r,g=fork();original=copy.deepcopy((r,g))
p=compile_trip(r,g,cache_sha256='hash')
+94
View File
@@ -0,0 +1,94 @@
import copy
import math
import unittest
from unittest.mock import patch
from ui.traffic_animation import TrafficAnimation
def pose(x=0., yaw=0., **changes):
return dict(valid=True, paused=False, age=0., world_position=[x, 0., 0.],
world_rotation=[yaw/(2*math.pi), 0., 0.], **changes)
def report(at, x=0., **changes):
actor=dict(id='car', type='ai', world_position=[x, 0., -20.], length_m=5.,
width_m=2., height_m=1.5, world_heading_rad=0., heading_delta_rad=0.)
actor.update(changes)
return dict(available=True, sampled_at=at, age_s=0., actors=[actor])
class TrafficAnimationTests(unittest.TestCase):
def test_brief_failed_read_retains_original_stamp_and_expires(self):
animator=TrafficAnimation()
source=report(10.)
before=copy.deepcopy(source)
animator.snapshot(source, pose(), 10.)
failed=dict(available=False, actors=[], reason='read interrupted')
held=animator.snapshot(failed, pose(x=1.), 10.2)
self.assertTrue(held['display_held'])
self.assertEqual(held['sampled_at'],10.)
self.assertAlmostEqual(held['actors'][0]['left_m'],1.)
self.assertFalse(held['usable_for_control'])
self.assertEqual(source,before)
self.assertFalse(animator.snapshot(failed,pose(),10.51)['available'])
def test_new_observations_are_smoothed_and_valid_disappearance_is_immediate(self):
animator=TrafficAnimation()
animator.snapshot(report(1.),pose(),1.)
current=report(1.1,x=2.)
before=copy.deepcopy(current)
output=animator.snapshot(current,pose(),1.1)
self.assertGreater(output['actors'][0]['world_position'][0],0.)
self.assertLess(output['actors'][0]['world_position'][0],2.)
self.assertEqual(current,before)
self.assertEqual(animator.snapshot(dict(current,actors=[]),pose(),1.2)['actors'],[])
def test_prediction_is_bounded_and_pause_clears_all_history(self):
animator=TrafficAnimation()
moving=report(1.,motion_available=True,world_velocity_mps=[10.,0.,0.])
output=animator.snapshot(moving,pose(),1.4)
self.assertAlmostEqual(output['actors'][0]['world_position'][0],1.5)
paused=pose();paused['paused']=True
self.assertFalse(animator.snapshot(moving,paused,1.41)['available'])
self.assertIsNone(animator.report)
def test_reused_identity_teleport_and_wrapped_heading(self):
animator=TrafficAnimation()
animator.snapshot(report(1.,world_heading_rad=math.pi-.01),pose(),1.)
current=animator.snapshot(report(1.1,world_heading_rad=-math.pi+.01),pose(),1.1)
self.assertGreater(abs(current['actors'][0]['heading_delta_rad']),3.)
teleported=animator.snapshot(report(1.2,x=200.),pose(),1.2)
self.assertEqual(teleported['actors'][0]['world_position'][0],200.)
def test_clock_reset_and_invalid_geometry_never_retain_actors(self):
animator=TrafficAnimation()
animator.snapshot(report(10.),pose(),10.)
self.assertFalse(animator.snapshot({'available':False},pose(),1.)['available'])
self.assertFalse(animator.snapshot(report(1.1,x=float('nan')),pose(),1.1)['available'])
def test_cab_keeps_trailer_and_camera_framing_through_brief_read_gap(self):
from ui.tesla_fsd_hud import TeslaFSDHUD
hud=TeslaFSDHUD()
traffic=report(10.)
tractor=dict(id='ego',type='player',world_position=[0.,0.,0.],
world_heading_rad=0.,length_m=7.,width_m=2.5,height_m=3.5)
trailer=dict(tractor,id='trailer',type='player-trailer',
world_position=[0.,0.,9.],length_m=13.)
traffic.update(ego_geometry_available=True,ego_trailer_attached=True,
ego_vehicle=tractor,ego_trailers=[trailer])
data=pose();data.update(display_monotonic=10.1,nearby_traffic=traffic)
with patch.object(hud,'vehicle_mesh',wraps=hud.vehicle_mesh) as meshes:
hud.render_cab_right(None,data,False)
self.assertEqual(meshes.call_count,3)
data.update(display_monotonic=10.35,nearby_traffic={'available':False,'actors':[]})
with patch.object(hud,'vehicle_mesh',wraps=hud.vehicle_mesh) as meshes:
hud.render_cab_right(None,data,False)
self.assertEqual(meshes.call_count,3)
data['display_monotonic']=10.6
with patch.object(hud,'vehicle_mesh',wraps=hud.vehicle_mesh) as meshes:
hud.render_cab_right(None,data,False)
self.assertEqual(meshes.call_count,1)
if __name__=='__main__':unittest.main()
+174
View File
@@ -0,0 +1,174 @@
"""Start the native cab/control companion whenever the installed ATS opens."""
import argparse
import ctypes
from ctypes import wintypes as w
from datetime import datetime
import os
from pathlib import Path
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
DEFAULT_GAME = Path(r'C:\Program Files (x86)\DODI-Repacks\American Truck Simulator\bin\win_x64\amtrucks.exe')
class ProcessEntry(ctypes.Structure):
_fields_ = [('size', w.DWORD), ('usage', w.DWORD), ('pid', w.DWORD),
('heap', ctypes.c_size_t), ('module', w.DWORD), ('threads', w.DWORD),
('parent', w.DWORD), ('priority', w.LONG), ('flags', w.DWORD),
('name', w.WCHAR * 260)]
def kernel():
api = ctypes.WinDLL('kernel32', use_last_error=True)
signatures = {
'OpenProcess': ([w.DWORD, w.BOOL, w.DWORD], w.HANDLE),
'CloseHandle': ([w.HANDLE], w.BOOL),
'WaitForSingleObject': ([w.HANDLE, w.DWORD], w.DWORD),
'CreateToolhelp32Snapshot': ([w.DWORD, w.DWORD], w.HANDLE),
'Process32FirstW': ([w.HANDLE, ctypes.POINTER(ProcessEntry)], w.BOOL),
'Process32NextW': ([w.HANDLE, ctypes.POINTER(ProcessEntry)], w.BOOL),
'QueryFullProcessImageNameW': ([w.HANDLE, w.DWORD, w.LPWSTR, ctypes.POINTER(w.DWORD)], w.BOOL),
}
for name, (args, result) in signatures.items():
getattr(api, name).argtypes, getattr(api, name).restype = args, result
return api
class ProcessLifetime:
"""Retain the real process handle so a reused PID cannot extend its life."""
def __init__(self, pid):
self.api = kernel()
self.handle = self.api.OpenProcess(0x100000, False, pid)
if not self.handle:
raise OSError('Cannot observe ATS process lifetime')
def running(self):
return bool(self.handle and self.api.WaitForSingleObject(self.handle, 0) == 258)
def close(self):
if self.handle:
self.api.CloseHandle(self.handle)
self.handle = None
def game_processes(executable):
api = kernel()
snapshot = api.CreateToolhelp32Snapshot(2, 0)
if snapshot in (None, ctypes.c_void_p(-1).value):
raise OSError('Cannot list ATS processes')
expected = os.path.normcase(os.path.abspath(executable))
result = []
try:
entry = ProcessEntry(); entry.size = ctypes.sizeof(entry)
more = api.Process32FirstW(snapshot, ctypes.byref(entry))
while more:
if entry.name.lower() == 'amtrucks.exe':
handle = api.OpenProcess(0x1000, False, entry.pid)
if handle:
try:
size = w.DWORD(32768); buffer = ctypes.create_unicode_buffer(size.value)
if (api.QueryFullProcessImageNameW(handle, 0, buffer, ctypes.byref(size))
and os.path.normcase(buffer.value) == expected):
result.append(entry.pid)
finally:
api.CloseHandle(handle)
more = api.Process32NextW(snapshot, ctypes.byref(entry))
finally:
api.CloseHandle(snapshot)
return result
def companion_running():
from tools.run_native_gameplay import _acquire_instance_lock, _release_instance_lock
try:
handle = _acquire_instance_lock()
except RuntimeError:
return True
_release_instance_lock(handle)
return False
class Supervisor:
"""One companion per game; restart failures with a bounded retry delay."""
def __init__(self, launch, occupied=companion_running):
self.launch, self.occupied = launch, occupied
self.child = None
self.retry_at = 0.
self.failures = 0
self.game_pid = None
self.started_at = None
def tick(self, pids, now):
if self.child is not None and self.child.poll() is not None:
uptime = now-self.started_at
self.child = None
self.failures = self.failures+1 if uptime < 30. else 1
self.retry_at = now+min(60., 5.*2.**min(4, self.failures-1))
if len(pids) != 1:
if not pids and self.child is None:
self.game_pid = None; self.failures = 0; self.retry_at = 0.
return
if self.child is not None or now < self.retry_at or self.occupied():
return
self.game_pid = pids[0]
self.child = self.launch(self.game_pid)
self.started_at = now
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--game', type=Path, default=DEFAULT_GAME)
parser.add_argument('--launch', action='store_true', help='Also open ATS if it is closed')
args, runner_args = parser.parse_known_args(argv)
if not args.game.is_file():
raise FileNotFoundError('ATS executable not found: '+str(args.game))
if args.launch and not game_processes(args.game):
subprocess.Popen([str(args.game)], cwd=args.game.parent)
# The login watcher and one-click shortcut share this lock. A second
# shortcut can open ATS, then leave the existing watcher in charge.
import msvcrt
logs = ROOT/'diagnostics'; logs.mkdir(exist_ok=True)
lock = (logs/'ats-autostart.lock').open('a+b')
lock.seek(0, os.SEEK_END)
if not lock.tell(): lock.write(b'0'); lock.flush()
lock.seek(0)
try:
msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1)
except OSError:
lock.close()
return 0
def note(message):
with (logs/'ats-autostart.log').open('a', encoding='utf-8') as stream:
stream.write(datetime.now().isoformat(timespec='seconds')+' '+message+'\n')
def launch(pid):
output = logs/'native-runtime.log'
if output.exists() and output.stat().st_size > 5_000_000:
output.replace(logs/'native-runtime.previous.log')
python = str(Path(sys.executable).with_name('python.exe'))
command = [python, '-B', '-u', str(ROOT/'tools/run_native_gameplay.py'),
'--input', 'auto', '--game-pid', str(pid), *runner_args]
with output.open('ab', buffering=0) as stream:
child = subprocess.Popen(command, cwd=ROOT, stdout=stream, stderr=stream,
creationflags=subprocess.CREATE_NO_WINDOW)
note('Started native companion PID %s for ATS PID %s' % (child.pid, pid))
return child
supervisor = Supervisor(launch)
note('Watching '+str(args.game))
try:
while True:
try:
supervisor.tick(game_processes(args.game), time.monotonic())
except OSError as exc:
note('Retrying: '+str(exc))
time.sleep(5.)
time.sleep(1.)
finally:
lock.close()
if __name__ == '__main__':
main()
+4 -3
View File
@@ -15,6 +15,7 @@ import sys
STAGE = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(STAGE))
from telemetry.native_lane_permissions import LanePermissionResolver
from telemetry.native_runtime_work import cooperative_json_loads, cooperative_json_write
def _road_groups(graph):
@@ -59,9 +60,9 @@ def _road_record(uid, lanes):
def build(graph_path, catalog_path, output, *, allow_source_ordinal_binding=False):
graph_path, catalog_path, output = map(Path, (graph_path, catalog_path, output))
graph_bytes = graph_path.read_bytes()
graph = json.loads(graph_bytes)
graph = cooperative_json_loads(graph_bytes)
catalog_bytes = catalog_path.read_bytes()
catalog = json.loads(catalog_bytes)
catalog = cooperative_json_loads(catalog_bytes)
# A matching graph hash alone cannot rescue a catalog extracted from an
# older mod stack. Bind only definitions from the graph's mounted sources.
source = graph.get('provenance') or {}
@@ -104,7 +105,7 @@ def build(graph_path, catalog_path, output, *, allow_source_ordinal_binding=Fals
)
output.parent.mkdir(parents=True, exist_ok=True)
pending = output.with_suffix('.pending.json')
pending.write_text(json.dumps(report, separators=(',', ':')), encoding='utf-8')
cooperative_json_write(pending, report)
pending.replace(output)
return dict(path=str(output.resolve()), **report['coverage'], available=report['available'])
+41 -15
View File
@@ -46,34 +46,27 @@ class GameplaySession:
self.control_log=None
def observe_speed_limit(self,data,now=None):
observed_trailer=measured_trailer_attached(data)
policy_changed=(observed_trailer is not None
and observed_trailer != self._last_policy_trailer_state)
if observed_trailer is not None:
self.trailer_attached=observed_trailer
self.navigation_speed_offset_mph=navigation_speed_offset_mph(observed_trailer)
self._last_policy_trailer_state=observed_trailer
limit=self.navigation_speed.observe(data,self.clock() if now is None else now)
if limit is None:
if not policy_changed or self.navigation_speed.limit_mph is None:
return
limit=self.navigation_speed.limit_mph
return
target=min(self.driver.MAX_TARGET_MPH,
float(limit)+self.navigation_speed_offset_mph)
if target>self.driver.target_speed_mph:
float(limit))
if target!=self.driver.target_speed_mph:
self.driver.set_target_speed(target)
self.speed_dirty=True
trailer_label=('trailer' if self.trailer_attached is True else
'bobtail' if self.trailer_attached is False else
'trailer state unknown')
print('Navigation limit %d MPH + %d MPH %s; MAX set to %.0f MPH'%
(limit,self.navigation_speed_offset_mph,trailer_label,target),flush=True)
print('Navigation limit changed to %d MPH; MAX set to %.0f MPH'%
(limit,target),flush=True)
def navigation_speed_policy(self):
"""Expose the current posted-limit offset for the HUD and recordings."""
limit=self.navigation_speed.limit_mph
return dict(mode='limit-plus-trailer-tolerance',
return dict(mode='posted-limit-with-manual-adjustment',
base_limit_mph=limit,
offset_mph=self.navigation_speed_offset_mph,
offset_mph=(self.driver.target_speed_mph-limit if limit is not None else 0.),
allowed_adjustment_mph=self.navigation_speed_offset_mph,
trailer_attached=self.trailer_attached,
target_speed_mph=self.driver.target_speed_mph)
@@ -81,6 +74,11 @@ class GameplaySession:
if not steps or not foreground:return
target=max(self.driver.MIN_TARGET_MPH,min(self.driver.MAX_TARGET_MPH,
self.driver.target_speed_mph+steps*5.))
limit=self.navigation_speed.limit_mph
if limit is not None:
tolerance=self.navigation_speed_offset_mph
target=max(self.driver.MIN_TARGET_MPH,min(self.driver.MAX_TARGET_MPH,
max(limit-tolerance,min(limit+tolerance,target))))
if target!=self.driver.target_speed_mph:
self.driver.set_target_speed(target)
self.speed_dirty=True
@@ -99,6 +97,8 @@ class GameplaySession:
self.reason=reason
self.last_decision=None
controller,self.controller=self.controller,None
if controller is not None and getattr(controller,'watchdog_diagnostics',None):
self.log_event('command_stall',**controller.watchdog_diagnostics)
try:
if controller is not None:controller.close()
except Exception as exc:
@@ -258,9 +258,10 @@ def run_loop(*,session,telemetry,window,monitor,capture,brain,actions,guard,hud,
autopilot=None,road_reader=None,junction_reader=None,lane_choice_fn=None,display_map=None,
native_graph=None,native_signals=None,native_planner=None,native_signal_planner=None,
native_crossing_planner=None,native_overtake_planner=None,
energy_navigation=None,
energy_navigation=None,runtime_maintenance=None,
cabin_display=None,
desktop_panel=True,
stop_when=None,
clock=time.monotonic,sleep=time.sleep,max_loops=None):
"""Keep capturing after releases; each later engagement needs fresh human F8."""
import numpy as np
@@ -287,6 +288,9 @@ def run_loop(*,session,telemetry,window,monitor,capture,brain,actions,guard,hud,
scene_builder=DrivingSceneBuilder()
try:
while max_loops is None or loops<max_loops:
if stop_when is not None and stop_when():
session.release('ATS closed: controls released')
break
started=clock();loops+=1
key=cv.pollKey() & 0xff
if key in (ord('v'),ord('V')):
@@ -315,6 +319,12 @@ def run_loop(*,session,telemetry,window,monitor,capture,brain,actions,guard,hud,
session.release('F8: controls released; live manual view')
count=0
data=telemetry.get_data()
if runtime_maintenance is not None:
data['runtime_maintenance']=runtime_maintenance.maintain(data,
engaged=session.active,pending_engagement=bool(count))
# Collection is permitted only without a driving lease; refresh
# the SDK afterward rather than planning from its pre-scan pose.
data.update(telemetry.get_data())
session.observe_speed_limit(data,now=clock())
session.adjust_speed(getattr(monitor,'consume_speed_steps',lambda:0)(),foreground)
camera_reason=guard.reason(data,enforce_head_limits=False)
@@ -369,8 +379,11 @@ def run_loop(*,session,telemetry,window,monitor,capture,brain,actions,guard,hud,
mapping['lane_choice_preview']=dict(available=False,reason='Lane mapping unavailable: '+str(exc))
if native_graph is not None and map_due:
try:
graph_started=clock()
mapping['native_lane_graph']=native_graph.snapshot(data,mapping.get('navigation_route'))
graph_duration_ms=(clock()-graph_started)*1000.
if energy_navigation is not None:
energy_started=clock()
original=mapping.get('ats_navigation_route') or mapping.get('navigation_route') or {}
energy,route,trip=energy_navigation.snapshot(data,original,native_graph)
mapping['energy_navigation']=energy
@@ -378,6 +391,12 @@ def run_loop(*,session,telemetry,window,monitor,capture,brain,actions,guard,hud,
mapping['navigation_preview']=route_projector(route,data)
if energy.get('active'):
mapping['native_lane_graph']=native_graph.snapshot(data,route,trip_plan=trip)
energy_duration_ms=(clock()-energy_started)*1000.
else:energy_duration_ms=0.
if graph_duration_ms+energy_duration_ms>200.:
from telemetry.native_runtime_work import thread_stack_snapshot
session.log_event('mapping_stall',native_graph_ms=graph_duration_ms,
energy_navigation_ms=energy_duration_ms,threads=thread_stack_snapshot())
except Exception as exc:
mapping['native_lane_graph']=dict(available=False,reason='Native lanes unavailable: '+str(exc))
if native_signals is not None and (now>=next_signals or getattr(native_signals,'nonblocking',False)):
@@ -453,6 +472,8 @@ def run_loop(*,session,telemetry,window,monitor,capture,brain,actions,guard,hud,
data['native_route_plan']=dict(available=False,usable_for_control=False,
reason='Native route planning unavailable: '+str(exc),sampled_at=now)
scene['native_plan']=data['native_route_plan']
data['loop_timing']['route_planner_ms']=(clock()-native_planning_started)*1000
signal_started=clock()
if native_signal_planner is not None:
try:
data['native_signal_plan']=native_signal_planner.assess(scene)
@@ -463,6 +484,8 @@ def run_loop(*,session,telemetry,window,monitor,capture,brain,actions,guard,hud,
data['native_signal_plan']=dict(available=False,usable_for_control=False,
reason='Native signal planning unavailable: '+str(exc),sampled_at=now)
scene['signal_plan']=data['native_signal_plan']
data['loop_timing']['signal_planner_ms']=(clock()-signal_started)*1000
crossing_started=clock()
if native_crossing_planner is not None:
try:
data['native_crossing_plan']=native_crossing_planner.assess(scene)
@@ -470,6 +493,8 @@ def run_loop(*,session,telemetry,window,monitor,capture,brain,actions,guard,hud,
data['native_crossing_plan']=dict(available=False,proceed_authorized=False,
reason='Native crossing planning unavailable: '+str(exc),sampled_at=now)
scene['crossing_plan']=data['native_crossing_plan']
data['loop_timing']['crossing_planner_ms']=(clock()-crossing_started)*1000
overtake_started=clock()
if native_overtake_planner is not None:
try:
overtake_scene=dict(scene,target_speed_mph=session.driver.target_speed_mph,
@@ -496,6 +521,7 @@ def run_loop(*,session,telemetry,window,monitor,capture,brain,actions,guard,hud,
overtake['signal_error']='Automatic passing indicator unavailable: '+str(exc)
elif not (isinstance(overtake,dict) and overtake.get('active') is True):
last_overtake_signal_request=None
data['loop_timing']['overtake_planner_ms']=(clock()-overtake_started)*1000
try:
control_started=clock()
data['loop_timing']['native_planning_ms']=(control_started-native_planning_started)*1000
+29
View File
@@ -0,0 +1,29 @@
param(
[string]$GameExecutable = 'C:\Program Files (x86)\DODI-Repacks\American Truck Simulator\bin\win_x64\amtrucks.exe',
[string]$PythonExecutable = 'C:\Python314\pythonw.exe'
)
$ErrorActionPreference = 'Stop'
$atsRoot = Split-Path -Parent $PSScriptRoot
$atsWatcher = Join-Path $PSScriptRoot 'ats_autostart.py'
foreach ($atsRequiredPath in @($GameExecutable, $PythonExecutable, $atsWatcher)) {
if (-not (Test-Path -LiteralPath $atsRequiredPath -PathType Leaf)) { throw "Missing launcher component: $atsRequiredPath" }
}
$atsShell = New-Object -ComObject WScript.Shell
$atsStartupLink = Join-Path ([Environment]::GetFolderPath('Startup')) 'ATS Native FSD Companion.lnk'
$atsDesktopLink = Join-Path ([Environment]::GetFolderPath('Desktop')) 'Tesla Semi FSD.lnk'
foreach ($atsLinkPath in @($atsStartupLink, $atsDesktopLink)) {
if ((Test-Path -LiteralPath $atsLinkPath) -and -not (Test-Path -LiteralPath "$atsLinkPath.before-autostart.bak")) {
Copy-Item -LiteralPath $atsLinkPath -Destination "$atsLinkPath.before-autostart.bak"
}
$atsShortcut = $atsShell.CreateShortcut($atsLinkPath)
$atsShortcut.TargetPath = $PythonExecutable
$atsShortcut.Arguments = '-B "{0}" --game "{1}"' -f $atsWatcher, $GameExecutable
if ($atsLinkPath -eq $atsDesktopLink) { $atsShortcut.Arguments += ' --launch' }
$atsShortcut.WorkingDirectory = $atsRoot
$atsShortcut.IconLocation = "$GameExecutable,0"
$atsShortcut.Description = 'ATS with automatic native driving and Tesla Semi cab screens'
$atsShortcut.Save()
}
Start-Process -FilePath $PythonExecutable -ArgumentList ('-B "{0}" --game "{1}"' -f $atsWatcher, $GameExecutable) -WorkingDirectory $atsRoot -WindowStyle Hidden
Write-Output "Installed login watcher: $atsStartupLink"
Write-Output "Installed one-click launcher: $atsDesktopLink"
+61 -17
View File
@@ -2,7 +2,9 @@
import argparse
from datetime import datetime
import os
import hashlib
from pathlib import Path
import subprocess
import sys
from types import SimpleNamespace
@@ -51,14 +53,42 @@ def _release_instance_lock(handle):
handle.close()
def _run_main(argv=None):
def _arguments(argv=None):
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--speed',type=float)
parser.add_argument('--game-pid',type=int,help='Exit cleanly with this ATS process (automatic launcher)')
parser.add_argument('--no-record',action='store_true',help='Disable full recording; compact control diagnostics remain enabled')
parser.add_argument('--cab-only',action='store_true',help='Render cabin screens without the separate desktop panel')
parser.add_argument('--record',action='store_true',help='Opt in to full scene recording for diagnostics')
panel=parser.add_mutually_exclusive_group()
panel.add_argument('--desktop-panel',dest='desktop_panel',action='store_true',help='Show the additional desktop panel')
panel.add_argument('--cab-only',dest='desktop_panel',action='store_false',help='Render only the cabin screens (default)')
parser.set_defaults(desktop_panel=False)
parser.add_argument('--input',choices=('auto','spf','ets2la','vjoy'),default='auto',
help='Control transport; auto uses the verified vJoy path; other transports are explicit')
args=parser.parse_args(argv)
return parser,parser.parse_args(argv)
def _build_info(root=ROOT):
"""Capture the source loaded at startup, rather than inspecting it later."""
digest=hashlib.sha256()
for directory in ('control','telemetry','tools','ui','vision'):
for path in sorted((root/directory).rglob('*.py')):
digest.update(path.relative_to(root).as_posix().encode()+b'\0')
digest.update(path.read_bytes())
revision='unknown';dirty=None
try:
revision=subprocess.run(['git','rev-parse','HEAD'],cwd=root,capture_output=True,
text=True,check=True,timeout=3).stdout.strip()
dirty=bool(subprocess.run(['git','status','--porcelain','--untracked-files=no'],
cwd=root,capture_output=True,text=True,check=True,timeout=3).stdout.strip())
except (OSError,subprocess.SubprocessError):
pass
return dict(revision=revision,source_sha256=digest.hexdigest(),tracked_changes=dirty)
def _run_main(argv=None):
parser,args=_arguments(argv)
build=_build_info()
from control.gameplay_speed import load_speed,save_speed,valid_speed
settings=ROOT/'diagnostics/native-gameplay-settings.json'
speed=args.speed if args.speed is not None else load_speed(settings)
@@ -78,17 +108,25 @@ def _run_main(argv=None):
from telemetry.native_signals import NativeSignalsReader
from telemetry.native_control_log import NativeControlLog
from telemetry.native_observation_worker import NativeObservationWorker
from telemetry.native_reader_process import NativeReaderProcess
from telemetry.native_runtime_work import NativeRuntimeMaintenance
from control.virtual_joystick import prepare_library,VirtualJoystick
from control.fsd_controller import FSDController
from control.windows_input import ATSWindow,KeyboardInput,TakeoverMonitor
from control.navigation_preview import route_preview
from ui.tesla_fsd_hud import TeslaFSDHUD
from ui.cabin_display_worker import CabinDisplayWorker
from ui.dashboard_stream import DashboardStream,CAB_DISPLAY_BRIGHTNESS,LEFT_NAME
from ui.cabin_display_process import CabinDisplayProcess
from ui.map_background import DisplayMapWorker
from vision.calibration_recorder import CalibrationRecorder
import cv2 as cv
resources=[];session=None;shared_joystick=None
# Small independent displays should not create twenty parallel CV workers.
cv.setNumThreads(1)
resources=[NativeRuntimeMaintenance()];session=None;shared_joystick=None
game_lifetime=None
if args.game_pid is not None:
from tools.ats_autostart import ProcessLifetime
game_lifetime=ProcessLifetime(args.game_pid)
resources.append(game_lifetime)
prepared=None
selected_input=None
try:
@@ -96,7 +134,9 @@ def _run_main(argv=None):
def add(resource):
resources.append(resource)
return resource
sdk=add(ATSTelemetry());gps=add(NativeObservationWorker(GPSRouteReader(),kind='GPS'))
sdk=add(ATSTelemetry())
gps_process=NativeReaderProcess(GPSRouteReader)
gps=add(NativeObservationWorker(gps_process,kind='GPS'))
traffic=add(NativeObservationWorker(NearbyTrafficReader(),kind='traffic'));graph=add(NativeLaneGraphManager())
signals=add(NativeObservationWorker(NativeSignalsReader(),kind='signals'));background=add(DisplayMapWorker())
monitor=add(TakeoverMonitor(ignore_pedals=True,speed_window=window))
@@ -106,22 +146,22 @@ def _run_main(argv=None):
control_log=None
try:
control_log=add(NativeControlLog(ROOT/'diagnostics'/'native-control.jsonl'))
control_log.event('runtime_version',**build,desktop_panel=args.desktop_panel,
full_recording=args.record and not args.no_record,opencv_threads=cv.getNumThreads())
control_log.event('gps_process',pid=gps_process.pid,isolated=True)
print('Control diagnostics: '+str(control_log.path),flush=True)
except (OSError,ValueError) as exc:
print('Control diagnostics unavailable: '+str(exc),flush=True)
if not args.no_record:
print('Loaded build: '+build['revision'][:12]+' source '+build['source_sha256'][:12]+
(' (local edits)' if build['tracked_changes'] else ''),flush=True)
if args.record and not args.no_record:
directory=ROOT/'diagnostics'/('native-gameplay-'+datetime.now().strftime('%Y%m%d-%H%M%S-%f'))
recorder=add(CalibrationRecorder(directory,dict(scope='experimental-native-gameplay',
dry_run=False,image_save_hz=1,async_write=True,async_queue_capacity=8,
inference_present=False,production_eligible=False,target_speed_mph=speed)))
print('Recording: '+str(directory),flush=True)
def stream(**kwargs):
try:return add(DashboardStream(**kwargs))
except Exception as exc:
print('Display stream unavailable: '+str(exc),flush=True)
return None
right=stream(brightness=CAB_DISPLAY_BRIGHTNESS)
left=stream(name=LEFT_NAME,flip_vertical=False)
# The display child owns both shared textures and no actuator devices.
right=left=None
def acquire():
nonlocal shared_joystick,prepared,selected_input
# Keep one verified lease for the whole native session. A fresh
@@ -171,7 +211,9 @@ def _run_main(argv=None):
session.reason='Native GPS lane qualification pending; no model inference'
print('ATS native backend: no neural model or camera inference loaded. Human F8 owns controls.',flush=True)
hud=TeslaFSDHUD()
cabin_display=add(CabinDisplayWorker(TeslaFSDHUD(),right,left))
cabin_display=add(CabinDisplayProcess())
if control_log is not None:
control_log.event('display_process',pid=cabin_display.pid,isolated=True)
run_loop(session=session,telemetry=sdk,window=window,monitor=monitor,capture=None,brain=None,
actions=None,guard=SimpleNamespace(reason=lambda data,**kwargs:''),hud=hud,cv=cv,
guarded_step=None,recorder=recorder,gps=gps,traffic=traffic,traffic_tracker=TrafficTracker(),
@@ -180,8 +222,10 @@ def _run_main(argv=None):
native_signal_planner=NativeSignalPlanner(),native_crossing_planner=NativeCrossingPlanner(),
native_overtake_planner=NativeOvertakePlanner(),
energy_navigation=add(NativeEnergyNavigation()),
runtime_maintenance=resources[0],
cabin_display=cabin_display,
desktop_panel=not args.cab_only)
stop_when=(lambda:not game_lifetime.running()) if game_lifetime is not None else None,
desktop_panel=args.desktop_panel)
finally:
if session is not None:session.release('Native gameplay closing')
for resource in reversed(resources):
+122
View File
@@ -0,0 +1,122 @@
"""Display-only child process with one in-flight and one pending scene."""
import multiprocessing
import threading
import time
def display_snapshot(data):
"""Retain display decisions, never send the static lane graph to the HUD."""
result=dict(data)
graph=data.get('native_lane_graph') or {}
trip=graph.get('trip_plan') or {}
result['native_lane_graph']={'trip_plan':{key:trip[key] for key in
('available','source_verified','route_revision','truck_detours','map_nodes',
'state','missing_sector_count','upcoming_issue_count','issues') if key in trip}}
scene=data.get('driving_scene') or {}
result['driving_scene']={key:scene[key] for key in
('schema_version','decision','trajectory') if key in scene}
# The HUD uses selected paths and nearby actors, never source qualifications
# or the duplicated evidence/observation trees used by offline recording.
for key in ('pop_trajectory_controller','pop_model_actions','pop_model_lead',
'traffic_signals','native_signal_plan','native_crossing_plan',
'road_geometry','junction_paths','control_command','control_telemetry'):
result.pop(key,None)
return result
def _render_child(connection, names=None):
import cv2 as cv
from ui.tesla_fsd_hud import TeslaFSDHUD
from ui.dashboard_stream import DashboardStream,CAB_DISPLAY_BRIGHTNESS,LEFT_NAME
from ui.power_status import power_status
cv.setNumThreads(1)
hud=TeslaFSDHUD();streams={};right_powered=None
try:
for name,settings in (('right',dict(brightness=CAB_DISPLAY_BRIGHTNESS)),
('left',dict(name=LEFT_NAME,flip_vertical=False))):
if names is not None:settings['name']=names[name]
try:streams[name]=DashboardStream(**settings)
except Exception as exc:print(name+' cabin display unavailable: '+str(exc),flush=True)
while True:
packet=connection.recv()
if packet is None:return
data,engaged,roads,sent=packet
started=time.monotonic()
if roads is not None:hud.route_map.set_roads(roads)
# A late display packet never publishes old ACTIVE state or actors
# as current. The native consumer keeps its last valid frame.
if started-sent<=.5:
data['display_monotonic']=started
data['age']=data.get('age',0.)+max(0.,started-sent)
for name in tuple(streams):
try:
stream=streams[name]
if name=='right':
powered=power_status(data)['powered']
if powered:stream.publish(hud.render_cab_right(None,data,engaged))
elif right_powered is not False:stream.publish_power_off()
right_powered=powered
else:stream.publish(hud.render_cab_left(data,engaged))
except Exception as exc:
print(name+' cabin display disabled: '+str(exc),flush=True)
streams.pop(name).close()
connection.send((time.monotonic()-started)*1000.)
except (EOFError,BrokenPipeError,OSError):
pass
finally:
for stream in streams.values():stream.close()
connection.close()
class CabinDisplayProcess:
"""Only a feeder thread serializes/waits on IPC; controls never wait on it."""
def __init__(self, *, context=None, names=None):
context=context or multiprocessing.get_context('spawn')
self._condition=threading.Condition()
self._pending=None;self._roads=None;self._closed=False
self.render_ms=None;self.error=None
self._connection,child=context.Pipe()
self._process=context.Process(target=_render_child,args=(child,names),
name='ATS cabin renderer',daemon=True)
self._process.start();child.close()
self._thread=threading.Thread(target=self._send,name='ATS display IPC',daemon=True)
self._thread.start()
@property
def pid(self):return self._process.pid
def set_roads(self, roads):
with self._condition:self._roads=roads
def submit(self, data, engaged):
snapshot=display_snapshot(data)
with self._condition:
if not self._closed and self.error is None:
self._pending=(snapshot,bool(engaged),time.monotonic())
self._condition.notify()
def _send(self):
try:
while True:
with self._condition:
self._condition.wait_for(lambda:self._closed or self._pending is not None)
if self._closed:return
data,engaged,sent=self._pending;self._pending=None
roads,self._roads=self._roads,None
# Display-map metadata is immutable MappingProxyType in the
# parent. Detach it here, off the control thread, for IPC.
if roads is not None:roads=[(dict(metadata),points) for metadata,points in roads]
self._connection.send((data,engaged,roads,sent))
self.render_ms=self._connection.recv()
except Exception as exc:
if not self._closed:
self.error=str(exc) or type(exc).__name__
print('Cabin renderer unavailable; driving continues: '+self.error,flush=True)
def close(self):
with self._condition:
self._closed=True;self._pending=None;self._condition.notify()
# Termination affects only display output. It owns no input devices.
if self._process.is_alive():self._process.terminate()
self._process.join(timeout=1.)
self._connection.close();self._thread.join(timeout=1.)
+4 -3
View File
@@ -18,6 +18,7 @@ from types import MappingProxyType
import zipfile
from telemetry.road_geometry import BUILD_SHA256, road_curve
from telemetry.native_runtime_work import cooperative_json_loads,cooperative_json_write
from tools.extract_hashfs_assets import HashFSReader, MAX_ASSET
from tools.hashfs_cityhash import cityhash64
from tools.verify_prefab_asset_overlays import mounted_archives, archive_index_fingerprint
@@ -346,7 +347,7 @@ class MountedDisplayMap:
output = self.cache_dir / (name + '.display.json')
if output.exists():
try:
saved = json.loads(output.read_text(encoding='utf-8'))
saved = cooperative_json_loads(output.read_text(encoding='utf-8'))
except (OSError, ValueError):
saved = {}
if (saved.get('asset_sha256') == digest and saved.get('parser_hashes') == PARSER_HASHES
@@ -360,12 +361,12 @@ class MountedDisplayMap:
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
if completed.returncode:
raise ValueError('Sector parse failed: ' + name + ': ' + completed.stderr[-300:])
result = json.loads(pending.read_text(encoding='utf-8'))
result = cooperative_json_loads(pending.read_text(encoding='utf-8'))
if result.get('map_format') != 907:
raise ValueError('Parser reported incompatible map format')
result.update(asset_sha256=digest, parser_hashes=PARSER_HASHES, archive=str(archive.path),
usable_for_control=False)
pending.write_text(json.dumps(result, separators=(',', ':')), encoding='utf-8')
cooperative_json_write(pending,result)
pending.replace(output)
return result
+9 -3
View File
@@ -14,6 +14,7 @@ from ui.active_route_map import ActiveRouteMap
from ui.truck_status import truck_status, driving_reason
from ui.power_status import power_status
from telemetry.driving_scene import display_path
from ui.traffic_animation import TrafficAnimation
class TeslaFSDHUD:
def __init__(self, width=1280, height=720):
@@ -22,6 +23,7 @@ class TeslaFSDHUD:
self.mode = "dashboard" # "dashboard" or "cockpit_screen"
self.show_camera_input = False
self.route_map = ActiveRouteMap()
self.traffic_animation = TrafficAnimation()
# 3D projection parameters for Tesla Semi perspective
self.cam_height = 2.4 # Tesla Semi center cab height (meters)
@@ -483,7 +485,7 @@ class TeslaFSDHUD:
attached=policy.get('trailer_attached')
if isinstance(offset,(int,float)) and np.isfinite(offset):
load='TRAILER' if attached is True else 'BOBTAIL' if attached is False else 'LOAD ?'
nav_note=f'NAV: LIMIT +{offset:.0f} | {load}'
nav_note=f'NAV: LIMIT {offset:+.0f} | {load}'
else:
nav_note='NAV: automatic limit offset unavailable'
cv2.putText(canvas,nav_note,(36,268),cv2.FONT_HERSHEY_SIMPLEX,
@@ -721,7 +723,8 @@ class TeslaFSDHUD:
if report.get('sampled_at') is not None:
age=max(age,float(data.get('display_monotonic',time.monotonic()))-float(report['sampled_at']))
if (report.get('available') is not True or report.get('ego_geometry_available') is not True
or not 0<=age<=.3 or type(report.get('ego_trailer_attached')) is not bool):
or not 0<=age<=(.5 if report.get('display_animated') else .3)
or type(report.get('ego_trailer_attached')) is not bool):
return [fallback],'TRAILER STATE UNAVAILABLE'
tractor=report['ego_vehicle'];trailers=report['ego_trailers']
if not isinstance(tractor,dict) or not isinstance(trailers,list) or len(trailers)>4:
@@ -992,7 +995,7 @@ class TeslaFSDHUD:
if all(p is not None for p in footprint):shadows.append(np.asarray(footprint,np.int32))
mesh.extend(self.vehicle_mesh(actor,geometry))
shown += 1
traffic = f'{shown} nearby vehicles | coverage incomplete'
traffic = f'{shown} nearby vehicles | '+('updating traffic' if report.get('display_held') else 'coverage incomplete')
else:
traffic = 'TRAFFIC UNAVAILABLE / STALE'
# Dark truck avatar denotes the ego origin; its styling is illustrative.
@@ -1032,6 +1035,9 @@ class TeslaFSDHUD:
def render_cab_right(self, perception, data, engaged):
"""Compose at native cab resolution: no desktop text squeezed into a texture."""
if 'world_position' in data and 'world_rotation' in data:
data = dict(data, nearby_traffic=self.traffic_animation.snapshot(
data.get('nearby_traffic'), data, data.get('display_monotonic', time.monotonic())))
saved={name:getattr(self,name) for name in ('c_panel','c_text','c_muted','c_blue','c_lane','c_lead')}
self.c_panel=(247,248,250);self.c_text=(42,43,46);self.c_muted=(112,115,121)
self.c_blue=(220,133,38);self.c_lane=(152,156,163);self.c_lead=(100,158,216)
+89
View File
@@ -0,0 +1,89 @@
"""Bounded visual motion and brief read-gap continuity; never a control input."""
import math
class TrafficAnimation:
MAX_AGE_S = .5
MAX_PREDICTION_S = .15
def __init__(self):
self.reset()
def reset(self):
self.report = None
self.tracks = {}
self.last_at = None
self.last_ego = None
def snapshot(self, report, data, now):
try:
return self._snapshot(report, data, float(now))
except (TypeError, ValueError, KeyError, IndexError, OverflowError):
self.reset()
return dict(report or {}, available=False, actors=[], display_only=True,
usable_for_control=False, complete_coverage=False)
def _snapshot(self, report, data, now):
ego = tuple(float(v) for v in data['world_position'])
yaw = float(data['world_rotation'][0])*2*math.pi
if (len(ego) != 3 or not all(math.isfinite(v) for v in (*ego, yaw, now))
or not data.get('valid') or data.get('paused') or data.get('age', 0.) > .35):
raise ValueError('Fresh truck pose required')
if self.last_at is not None:
dt = now-self.last_at
if dt < 0 or dt > .5 or math.dist(ego, self.last_ego) > 5+70*dt:
self.reset()
dt = min(.1, max(0., now-self.last_at)) if self.last_at is not None else .1
self.last_at, self.last_ego = now, ego
fresh = isinstance(report, dict) and report.get('available') is True
if fresh:
stamp = float(report['sampled_at'])
age = max(float(report.get('age_s', 0.)), now-stamp)
fresh = math.isfinite(stamp) and 0 <= age <= self.MAX_AGE_S and stamp <= now+.01
if fresh:
if self.report and stamp < self.report['sampled_at']:
self.tracks = {}
self.report = dict(report, age_s=age)
held = not fresh
if self.report is None or now-self.report['sampled_at'] > self.MAX_AGE_S:
self.tracks = {}
return dict(report or {}, available=False, actors=[], display_only=True,
usable_for_control=False, complete_coverage=False)
source = self.report
age = max(source['age_s'], now-source['sampled_at'], 0.)
fx, fz = -math.sin(yaw), -math.cos(yaw)
actors, seen = [], set()
for actor in source['actors'][:256]:
key = actor['id']
if key in seen:
raise ValueError('Duplicate actor')
seen.add(key)
position = tuple(float(v) for v in actor['world_position'])
heading = float(actor['world_heading_rad'] if 'world_heading_rad' in actor else
source.get('ego_world_yaw_rad', yaw)+actor['heading_delta_rad'])
dimensions = tuple(float(actor[k]) for k in ('length_m', 'width_m', 'height_m'))
if (len(position) != 3 or not all(math.isfinite(v) for v in (*position, heading, *dimensions))
or any(not .2 <= v <= 60 for v in dimensions)):
raise ValueError('Invalid actor geometry')
target = position
velocity = actor.get('world_velocity_mps')
if actor.get('motion_available') and isinstance(velocity, (list, tuple)) and len(velocity) == 3:
velocity = tuple(float(v) for v in velocity)
if all(math.isfinite(v) for v in velocity) and math.dist(velocity, (0, 0, 0)) <= 70:
target = tuple(p+v*min(age, self.MAX_PREDICTION_S) for p, v in zip(position, velocity))
track = self.tracks.get(key)
identity = (actor.get('type'), dimensions)
if track is None or track[2] != identity or math.dist(target, track[0]) > 5+70*dt:
visual, angle = target, heading
else:
alpha = 1-math.exp(-dt/.08)
visual = tuple(p+(q-p)*alpha for p, q in zip(track[0], target))
angle = track[1]+((heading-track[1]+math.pi)%(2*math.pi)-math.pi)*alpha
self.tracks[key] = visual, angle, identity
dx, dz = visual[0]-ego[0], visual[2]-ego[2]
actors.append(dict(actor, world_position=list(visual), forward_m=dx*fx+dz*fz,
left_m=dx*fz-dz*fx, heading_delta_rad=(angle-yaw+math.pi)%(2*math.pi)-math.pi))
self.tracks = {key: value for key, value in self.tracks.items() if key in seen}
return dict(source, actors=actors, age_s=age, display_only=True, usable_for_control=False,
complete_coverage=False, display_held=held, display_animated=True,
position_method='bounded visual prediction and smoothing; original observation timestamp retained')
+3 -2
View File
@@ -12,6 +12,7 @@ import re
import cv2
import numpy as np
from telemetry.native_runtime_work import cooperative_json_dumps
def recording_snapshot(telemetry):
@@ -346,7 +347,7 @@ class CalibrationRecorder:
self.next_image = now + self.image_interval
self.last_obstructed = obstructed
try:
encoded = json.dumps(row, allow_nan=False)
encoded = cooperative_json_dumps(row, allow_nan=False)
except (ValueError, TypeError):
# Keep the normal write path cheap; invalid SDK/model numerics and
# numpy scalar diagnostics need normalization only when present.
@@ -354,7 +355,7 @@ class CalibrationRecorder:
row = _json_evidence(row,nonfinite=nonfinite)
if nonfinite:
row['nonfinite_fields'] = nonfinite
encoded = json.dumps(row, allow_nan=False)
encoded = cooperative_json_dumps(row, allow_nan=False)
self.stream.write(encoded + "\n")
self.stream.flush()
if not self.async_write: