Add prepared urban route guidance to Gaussian simulation planning

Introduce a content-bound scene route provider, advisory runtime graph and plan-preview-launch workflow. Preserve live sensing authority and retire blocked intermediate goals without discarding final-arrival evidence. Bound native visual context losslessly and provide verified cache relocation. Full Maroseyka route qualification remains open.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-08 23:42:26 +03:00
parent 2e85d95c71
commit 31b74e4571
34 changed files with 1451 additions and 83 deletions
+6
View File
@@ -6,6 +6,7 @@ bundle alone is not evidence of which cached USD the renderer will load.
import hashlib
import json
import shutil
import uuid
from pathlib import Path
@@ -83,6 +84,11 @@ def prepare_gaussian(source, convert, recipe, *, cache_root=None):
if valid is not None:
return output, valid
directory.mkdir(parents=True, exist_ok=True)
# USD retains all SH coefficients and is slightly larger than its PLY.
# Refuse before conversion rather than filling the Worker volume midway.
required = int(identity["source_bytes"] * 1.25) + 4 * 1024**3
if shutil.disk_usage(directory).free < required:
raise RuntimeError("Недостаточно места для Gaussian USD-кэша: освободите диск или перенесите кэш.")
token = uuid.uuid4().hex
temporary = directory / (token + ".part.usd")
receipt_temporary = directory / (token + ".part.json")
+35 -18
View File
@@ -23,7 +23,7 @@ def digest(path):
return hashlib.file_digest(stream, "sha256").hexdigest()
def prepare_project(client, run, state, episode, job, pulse):
def prepare_project(client, run, state, episode, job, pulse, isaac):
world = run["world"]
package = client.request("/worker/worlds/" + world["world_id"] + "/project-assets")
if package["world_sha256"] != world["sha256"]:
@@ -86,13 +86,20 @@ def prepare_project(client, run, state, episode, job, pulse):
# Keep 12 m of surrounding visual context in every direction. A saved route
# bounds the adaptation. Retain LOD0 and all SH bands without a count ceiling.
points = run["plan"]["points"]
prior = run["plan"].get("prepared_route")
if prior:
# A curved A/B route needs its entire preview, not just its endpoints.
# Unselected graph branches must not force the whole city into RTX.
# Long detours outside this visual region require spatial streaming;
# the graph never substitutes for live support in such an area.
points = points + [{"position": p} for p in prior["preview_xyz"]]
xyz = [[p["position"][0], p["position"][2], -p["position"][1]] for p in points]
bounds = [min(p[i] for p in xyz) - 12 for i in range(3)] + [
max(p[i] for p in xyz) + 12 for i in range(3)
]
key = hashlib.sha256(
json.dumps(
{"world": world["sha256"], "bounds": bounds, "adapter": digest(Path(__file__))},
{"world": world["sha256"], "bounds": bounds, "adapter": digest(Path(__file__)), "region_adapter": digest(Path(__file__).with_name("route_region.py"))},
sort_keys=True,
).encode()
).hexdigest()
@@ -136,23 +143,33 @@ def prepare_project(client, run, state, episode, job, pulse):
"0,0,180",
str(temporary),
]
commands = [command]
filtered = temporary.with_suffix(".region.ply")
if prior:
region = episode / "visual-region.json"
write_json(region, {"route_xz": [[p[0],-p[1]] for p in prior["preview_xyz"]],
"radius_m": 12, "authority": "visual-context-only"})
commands.append([str(isaac / "python.bat"), str(Path(__file__).with_name("route_region.py")),
"--source",str(temporary),"--output",str(filtered),"--region",str(region)])
with (episode / "project-preparation.log").open("wb") as log:
process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT)
job.assign(process)
deadline = time.monotonic() + 600
try:
while process.poll() is None:
pulse()
if time.monotonic() > deadline:
raise TimeoutError("Project preparation timed out")
time.sleep(1)
if process.returncode:
raise RuntimeError("SOG adaptation failed; inspect Worker evidence")
finally:
if process.poll() is None:
from worker import terminate_episode
terminate_episode(process)
for command in commands:
process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT)
job.assign(process)
deadline = time.monotonic() + 600
try:
while process.poll() is None:
pulse()
if time.monotonic() > deadline:
raise TimeoutError("Project preparation timed out")
time.sleep(1)
if process.returncode:
raise RuntimeError("SOG adaptation failed; inspect Worker evidence")
finally:
if process.poll() is None:
from worker import terminate_episode
terminate_episode(process)
if prior:
filtered.replace(temporary)
with temporary.open("rb") as f:
header = f.read(65536).split(b"end_header", 1)[0].decode("ascii")
count = int(re.search(r"element vertex (\d+)", header)[1])
+19 -1
View File
@@ -236,7 +236,10 @@ def main():
).encode()
).hexdigest(),
}
from k1link.simulation.ai_polygon.route_preparation import provider_identity
hello = {
"route_provider_sha256": provider_identity(),
"worker_id": "worker-006-ai-polygon",
"instance_id": instance,
"runtime": "isaac-sim-6.1",
@@ -320,10 +323,15 @@ def main():
raise
connect()
editor_marker = args.state / "editor-active.json"
route_marker = args.state / "route-active.json"
while True:
try:
# A prior coordinator's Windows Job killed all native descendants on exit.
# Retain the marker until Core accepts that resource-release receipt.
if route_marker.exists():
key = read_json(route_marker)["key"]
client.request("/worker/route-preparations/" + key, {"action": "release"})
route_marker.unlink()
if editor_marker.exists():
key = read_json(editor_marker)["key"]
client.request("/worker/editor-cache/" + key, {"action": "release"})
@@ -335,6 +343,16 @@ def main():
if polled["action"] == "idle":
time.sleep(0.5)
continue
if polled["action"] == "route-preparation":
from route_preparer import prepare_route
route_job = NativeJob()
write_json(route_marker, {"key": polled["preparation"]["key"]})
try:
prepare_route(client, polled["preparation"], args.state, args.isaac, route_job)
finally:
route_job.close()
continue
if polled["action"] == "editor-cache":
from editor_assets import prepare_editor
@@ -391,7 +409,7 @@ def main():
from project_assets import prepare_project
source, terrain_path = prepare_project(
client, run, args.state, episode, job, preparation_pulse
client, run, args.state, episode, job, preparation_pulse, args.isaac
)
else:
terrain_path = prepare_terrain(
+94
View File
@@ -0,0 +1,94 @@
"""Artifact-owned bounded CPU route job on the existing Worker reservation."""
import hashlib
import json
import logging
import os
import re
import shutil
import subprocess
import time
from contextlib import suppress
from pathlib import Path
from urllib.parse import quote
from local_state import write_json
from model_stack import ROOT
from worker import terminate_episode
def sha(path):
with path.open('rb') as stream:
return hashlib.file_digest(stream,'sha256').hexdigest()
def prepare_route(client, request, state, isaac, job):
if not re.fullmatch(r"[a-f0-9]{64}", request["key"]):
raise ValueError("Invalid route preparation identity")
endpoint='/worker/route-preparations/'+request['key']
last_pulse=-float('inf')
def pulse():
nonlocal last_pulse
if time.monotonic()-last_pulse>=1:
client.request('/worker/heartbeat',{'instance_id':client.instance})
last_pulse=time.monotonic()
target=state.parent/'assets/route-preparations'/request['key']
target.mkdir(parents=True,exist_ok=True)
def execute(command, limit):
with (target/'preparation.log').open('ab') as log:
child=subprocess.Popen(command,stdout=log,stderr=subprocess.STDOUT,
env={**os.environ,"OPENBLAS_NUM_THREADS":"2","OMP_NUM_THREADS":"2"})
job.assign(child)
deadline=time.monotonic()+limit
try:
while child.poll() is None:
pulse()
if time.monotonic()>deadline:
raise TimeoutError('Route preparation timed out')
time.sleep(.5)
if child.returncode:
raise RuntimeError('Route preparation process failed')
finally:
if child.poll() is None:
terminate_episode(child)
try:
world=request['world']
package=client.request('/worker/worlds/'+world['world_id']+'/project-assets')
if package['world_sha256']!=world['sha256']:
raise ValueError('Route world changed')
item=next(a for a in package['artifacts'] if a['logical_path']==package['collision_path'])
if item['sha256']!=request['identity']['collider_sha256']:
raise ValueError('Route collider changed')
sources=state.parent/'assets/route-sources'
sources.mkdir(parents=True,exist_ok=True)
packed=sources/(item['sha256']+'.glb')
if not packed.exists() or sha(packed)!=item['sha256']:
if shutil.disk_usage(sources).free < item['byte_length']+512*1024**2:
raise RuntimeError('Insufficient route preparation space')
client.download_asset('/api/v1/simulation-worlds/projects/'+package['project_id']+
'/artifacts/'+quote(item['logical_path'],safe='/'),item,packed,pulse=pulse)
decoder=ROOT/'decode_collision.cjs'
decoded=sources/(digest_name(item['sha256'],sha(decoder))+'.decoded.glb')
receipt=decoded.with_suffix('.json')
if not (decoded.exists() and receipt.exists() and json.loads(receipt.read_text())['sha256']==sha(decoded)):
temporary=decoded.with_suffix('.part.glb')
execute([shutil.which('node'),str(decoder),str(packed),str(temporary)],60)
temporary.replace(decoded)
write_json(receipt,{'sha256':sha(decoded),'source_sha256':item['sha256'],'decoder_sha256':sha(decoder)})
request_file=target/'request.json'
write_json(request_file,request)
result_file=target/'result.json'
execute([str(isaac/'python.bat'),str(ROOT/'scene_route_field.py'),
'--request',str(request_file),'--collider',str(decoded),
'--output',str(result_file),'--field-cache',str(state.parent/'assets/route-fields')],480)
if result_file.stat().st_size>4*1024**2:
raise ValueError('Route artifact exceeds transport budget')
result=json.loads(result_file.read_text(encoding='utf-8'))
client.request(endpoint,{'action':'complete','result':result})
except Exception:
logging.exception('Route preparation failed')
with suppress(Exception):
client.request(endpoint,{'action':'fail'})
def digest_name(*parts):
return hashlib.sha256(':'.join(parts).encode()).hexdigest()
+74
View File
@@ -0,0 +1,74 @@
"""Lossless record selection for the spatial context of a curved route.
No count budget, LOD, opacity filter, SH truncation, reordering or requantization.
The selected region is a conservative superset of the 12 m route neighbourhood.
"""
import json
import math
from pathlib import Path
import numpy as np
from scipy.spatial import cKDTree
def route_samples(points, spacing=2.):
points=np.asarray(points,dtype=float)
if points.ndim!=2 or points.shape[1]!=2 or len(points)<2 or not np.isfinite(points).all():
raise ValueError('Invalid route region')
samples=[points[0]]
for a,b in zip(points,points[1:]):
count=max(1,math.ceil(float(np.linalg.norm(b-a))/spacing))
samples.extend(np.linspace(a,b,count+1)[1:])
return np.asarray(samples)
def select_region(source,output,points,radius=12.,chunk=250000):
tree=cKDTree(route_samples(points))
# Any point within radius of a segment is at most this far from a sample.
# Keeping a small superset avoids removing context between sample centres.
bound=math.hypot(radius,1.)
retained=0
with Path(source).open('rb') as src:
lines=[]
while sum(map(len,lines))<65536:
line=src.readline();lines.append(line)
if line.strip()==b'end_header':break
if not line:raise ValueError('Incomplete PLY header')
else:raise ValueError('PLY header exceeds budget')
text=[s.decode('ascii').strip() for s in lines]
if text[:2]!=['ply','format binary_little_endian 1.0']:
raise ValueError('Expected binary float Gaussian PLY')
elements=[i for i,s in enumerate(text) if s.startswith('element ')]
if len(elements)!=1 or not text[elements[0]].startswith('element vertex '):
raise ValueError('Expected a single Gaussian vertex element')
count=int(text[elements[0]].split()[-1]);properties=[s.split() for s in text if s.startswith('property ')]
if any(len(s)!=3 or s[1]!='float' for s in properties):
raise ValueError('Expected float Gaussian attributes')
names=[s[2] for s in properties];xi,zi=names.index('x'),names.index('z')
stride=len(names)*4
if Path(source).stat().st_size!=src.tell()+count*stride:
raise ValueError('PLY record size differs from its header')
def header(total):
return b''.join((f'element vertex {total:020d}\n'.encode() if i==elements[0] else line)
for i,line in enumerate(lines))
with Path(output).open('wb') as dst:
dst.write(header(0))
for start in range(0,count,chunk):
raw=src.read(min(chunk,count-start)*stride)
values=np.frombuffer(raw,dtype='<f4').reshape(-1,len(names))
xy=values[:,[xi,zi]]
if not np.isfinite(xy).all():raise ValueError('Nonfinite Gaussian position')
distance,_=tree.query(xy,workers=2,distance_upper_bound=bound)
keep=np.isfinite(distance)
dst.write(values[keep].tobytes());retained+=int(keep.sum())
if not retained:raise ValueError('Route context contains no Gaussians')
dst.seek(0);dst.write(header(retained))
return dict(source_count=count,retained_count=retained,all_attributes_preserved=True,
radius_m=radius,sampling_superset_radius_m=bound,decimated=False)
if __name__=='__main__':
import argparse
p=argparse.ArgumentParser()
for name in ('source','output','region'):p.add_argument('--'+name,type=Path,required=True)
args=p.parse_args();region=json.loads(args.region.read_text())
print(json.dumps(select_region(args.source,args.output,region['route_xz'],region['radius_m'])),flush=True)
+223
View File
@@ -0,0 +1,223 @@
"""Offline, replaceable geometric route prior. Worker CPU only.
The envelope describes likely connected ground, not a pedestrian/legal map.
Small enclosed occlusions are UNKNOWN, never asserted free. Their obstacle
silhouettes do not sculpt the global route. Live perception remains mandatory.
No prepared field, mesh or inferred height enters the local sensor pipeline.
"""
import json
import hashlib
import math
from pathlib import Path
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "src"))
import numpy as np
from scipy import ndimage
from scipy.sparse import coo_matrix
from scipy.sparse.csgraph import connected_components
from terrain import load_glb
from k1link.simulation.ai_polygon.route_graph import build_route, PRIOR_MAP_SCHEMA
from k1link.simulation.ai_polygon.route_preparation import SCHEMA, provider_identity
from k1link.simulation.ai_polygon.run_inputs import digest, robot_geometry
CELL = .5
STRIDE = 4 # 2 m graph; the runtime receives coalesced direction segments.
MAX_CELLS = 2_000_000
MAX_NODES = 16384
def ground_envelope(vertices, faces, seed):
triangles = vertices[faces]
normal = np.cross(triangles[:,1]-triangles[:,0],triangles[:,2]-triangles[:,0])
length = np.linalg.norm(normal,axis=1)
flat = np.abs(normal[:,2]) >= np.maximum(1e-8,length)*math.cos(math.radians(25))
samples = np.concatenate((triangles[flat].reshape(-1,3),triangles[flat].mean(axis=1)))
if not len(samples):
raise ValueError("No ground candidates in scene")
origin = np.floor(vertices[:,:2].min(axis=0)/CELL)*CELL-CELL
shape = np.ceil((vertices[:,:2].max(axis=0)-origin)/CELL).astype(int)+2
if int(np.prod(shape)) > MAX_CELLS:
raise ValueError("Scene exceeds route preparation cell budget")
# Lower surface is a declared single-level approximation. Raised roofs are
# disconnected by height, not identified as cars/buildings by their size.
ij = np.floor((samples[:,:2]-origin)/CELL).astype(int)
height = np.full(tuple(shape),np.inf)
np.minimum.at(height,(ij[:,0],ij[:,1]),samples[:,2])
valid = np.isfinite(height)
seed_cell = np.floor((np.asarray(seed[:2])-origin)/CELL).astype(int)
nearby = np.argwhere(valid & (np.abs(height-seed[2]) <= .6))
if not len(nearby):
raise ValueError("Start has no matching ground layer")
nearest = nearby[np.argmin(np.linalg.norm(nearby-seed_cell,axis=1))]
if np.linalg.norm(nearest-seed_cell)*CELL > 1:
raise ValueError("Start outside mapped surface")
# Height connectivity removes roofs and keeps the selected terrain layer.
labels = np.full(height.shape,-1,dtype=np.int32)
labels[valid] = np.arange(np.count_nonzero(valid))
rows,cols = [],[]
for axis in (0,1):
a = (slice(None,-1),slice(None)) if axis==0 else (slice(None),slice(None,-1))
b = (slice(1,None),slice(None)) if axis==0 else (slice(None),slice(1,None))
with np.errstate(invalid='ignore'):
adjacent = valid[a]&valid[b]&(np.abs(height[a]-height[b]) <= .1+CELL*math.tan(math.radians(25)))
rows.extend(labels[a][adjacent]); cols.extend(labels[b][adjacent])
matrix = coo_matrix((np.ones(len(rows),dtype=np.uint8),(rows,cols)),shape=(np.count_nonzero(valid),)*2).tocsr()
_,components = connected_components(matrix,directed=False)
ground = np.zeros(height.shape,dtype=bool)
ground[valid] = components == components[labels[tuple(nearest)]]
# Close only bounded, enclosed holes. No connection across open terrain,
# a scene boundary, a long wall or an unobserved street is invented.
holes = ndimage.binary_fill_holes(ground)&~ground
regions,count = ndimage.label(holes)
unknown = np.zeros(height.shape,dtype=bool)
for index,sl in enumerate(ndimage.find_objects(regions),1):
if sl is None:
continue
local = regions[sl]==index
span = max(s.stop-s.start for s in sl)*CELL
if span > 6 or np.count_nonzero(local)*CELL**2 > 24:
continue
region = regions==index
rim = ndimage.binary_dilation(region)&ground
heights = height[rim]
if not len(heights) or np.ptp(heights) > .8:
continue
unknown |= region
envelope = ground|unknown
nearest_ground = ndimage.distance_transform_edt(~ground,return_distances=False,return_indices=True)
height[unknown] = height[tuple(nearest_ground[:,unknown])]
return origin,height,envelope,unknown
def route_graph(origin, height, envelope, unknown, positions, source, world_sha256):
clearance = ndimage.distance_transform_edt(envelope)*CELL
ids = np.full(envelope.shape,-1,dtype=np.int32)
cells = np.argwhere(envelope & (clearance >= .75))
cells = cells[(cells[:,0]%STRIDE==0)&(cells[:,1]%STRIDE==0)]
if not 1 <= len(cells) <= MAX_NODES-len(positions):
raise ValueError("Route graph exceeds node budget or has no ground")
nodes = []
for i,(x,y) in enumerate(cells):
ids[x,y] = i
nodes.append(dict(id=str(i),xy=(origin+(np.array([x,y])+.5)*CELL).tolist(),z=float(height[x,y])))
edges = []
def line(a,b):
n=max(2,int(np.linalg.norm(b-a)*2)+1)
ij=np.rint(np.linspace(a,b,n)).astype(int)
if np.any(ij<0) or np.any(ij>=np.array(envelope.shape)):
return None
if not envelope[ij[:,0],ij[:,1]].all():
return None
# Keep boundaries expensive. The route follows broad ground structure,
# with a bounded preference that cannot outweigh a long useful detour.
width=float(np.min(clearance[ij[:,0],ij[:,1]]))
z=height[ij[:,0],ij[:,1]]
if np.any(np.abs(np.diff(z))>.5):
return None
return width
def connect(i,j,a,b):
width=line(a,b)
if width is None or width < .5:
return
endpoints=np.rint(np.array([a,b])).astype(int)
actual_height=height[endpoints[:,0],endpoints[:,1]]
if np.any(np.abs(actual_height-np.array([nodes[i]["z"],nodes[j]["z"]]))>.6):
return
length=math.dist(nodes[i]["xy"],nodes[j]["xy"])
if length < .05:
return
edges.append(dict(id=str(len(edges)),start=str(i),end=str(j),half_width_m=min(20,width),
bidirectional=True,cost_m=length*(1+2/max(.5,width))))
for i,a in enumerate(cells):
for dx,dy in ((STRIDE,0),(0,STRIDE),(STRIDE,STRIDE),(STRIDE,-STRIDE)):
b=a+[dx,dy]
if np.any(b<0) or np.any(b>=np.array(envelope.shape)):
continue
j=int(ids[tuple(b)])
if j>=0:
connect(i,j,a,b)
goals=[]
for position in positions:
cell=(np.asarray(position[:2])-origin)/CELL-.5
index=len(nodes)
nodes.append(dict(id=str(index),xy=position[:2],z=position[2]))
distances=np.linalg.norm(cells-cell,axis=1)*CELL
added=len(edges)
for j in np.argsort(distances)[:12]:
if distances[j]>3:
break
connect(index,int(j),cell,cells[j])
if added==len(edges):
raise ValueError("Endpoint is outside connected ground envelope")
goals.append(str(index))
if len(edges)>65536:
raise ValueError("Route graph edge budget exceeded")
graph=dict(schema_version=PRIOR_MAP_SCHEMA,frame="world-xy-metres",world_sha256=world_sha256,
nodes=nodes,edges=edges,no_go=[],corridor_policy="advisory",source=source)
graph["sha256"]=digest(graph)
return dict(map=graph,start_node=goals[0],goal_nodes=goals[1:],blocked_edges=[])
def prepare(request, collider, output, field_cache):
identity=request["identity"]
if identity["provider_sha256"] != provider_identity():
raise ValueError("Installed route provider changed")
world=request["world"]
positions=[p["position"] for p in identity["points"]]
# Terrain extraction is independent of A/B; selection of a height component
# uses the declared start layer and is therefore explicitly cache-bound.
field_identity=dict(world=world["sha256"],collider=identity["collider_sha256"],
provider=identity["provider_sha256"],seed=positions[0],
rotation=world["local_scene"]["collision_rotation"])
cache=Path(field_cache)/(digest(field_identity)+'.npz')
cache.parent.mkdir(parents=True,exist_ok=True)
receipt=cache.with_suffix(".json")
valid_cache=cache.exists() and receipt.exists()
if valid_cache:
with cache.open("rb") as stream:
valid_cache=json.loads(receipt.read_text()).get("sha256")==hashlib.file_digest(stream,"sha256").hexdigest()
if valid_cache:
with np.load(cache,allow_pickle=False) as value:
origin,height,envelope,unknown=(value[k] for k in ('origin','height','envelope','unknown'))
else:
vertices,faces=load_glb(collider,world["local_scene"]["collision_rotation"])
origin,height,envelope,unknown=ground_envelope(vertices,faces,positions[0])
np.savez_compressed(cache,origin=origin,height=height,envelope=envelope,unknown=unknown)
with cache.open("rb") as stream:
receipt.write_text(json.dumps({"sha256":hashlib.file_digest(stream,"sha256").hexdigest(),"identity":field_identity}))
source={k:identity[k] for k in ('provider','provider_sha256','collider_sha256')}
routing=route_graph(origin,height,envelope,unknown,positions,source,world['sha256'])
inputs=dict(routing=routing,mission={"route_xy":[p[:2] for p in positions[1:]]},
robot={"geometry":robot_geometry(request['robot'])},sha256=request['key'])
route=build_route(inputs)
if any(leg['status']!='ready' for leg in route['legs']):
raise ValueError("No complete route between all task points")
node_z={tuple(n['xy']):n['z'] for n in routing['map']['nodes']}
preview=[positions[0]]
for leg in route['legs']:
for segment in leg['segments']:
xy=segment['end_xy']; preview.append([*xy,node_z[tuple(xy)]])
result=dict(schema_version=SCHEMA,identity=identity,routing=routing,preview_xyz=preview,
length_m=sum(leg['length_m'] for leg in route['legs']),
evidence=dict(field_sha256=digest(field_identity),cell_m=CELL,
mapped_cells=int(envelope.sum()),uncertain_cells=int(unknown.sum()),
authority='route-intent-only',
limitations=['geometric-prior-not-pedestrian-map','single-ground-layer',
'small-enclosed-occlusions-unknown','live-sensors-required']))
result['sha256']=digest(result)
Path(output).write_text(json.dumps(result,allow_nan=False,separators=(",",":")),encoding='utf-8')
if __name__=='__main__':
import argparse
parser=argparse.ArgumentParser()
for name in ('request','collider','output','field-cache'):
parser.add_argument('--'+name,required=True)
args=parser.parse_args()
prepare(json.loads(Path(args.request).read_text(encoding='utf-8')),args.collider,args.output,args.field_cache)