humanoidBench / sharpa11_20261107 /scripts /sharpa11_render.py
JoeyYuzy's picture
Add 11 Sharpa Gaussian homes with repaired flat floors, collision and 44 RTX views
bf3194a verified
Raw History Blame Contribute Delete
13.2 kB
"""Render native USD Gaussians and exercise the delivered PhysX colliders."""
from pathlib import Path
import argparse
import json
import time
parser = argparse.ArgumentParser()
parser.add_argument('scenes', nargs='*')
parser.add_argument('--final', action='store_true')
parser.add_argument('--views', default='')
parser.add_argument('--physics', action='store_true')
parser.add_argument('--before-floor', action='store_true')
parser.add_argument('--debug-simple-transform', action='store_true')
parser.add_argument('--emissive', action='store_true')
parser.add_argument('--comparison', action='store_true')
parser.add_argument('--replace-slot', type=int, choices=[1,2,3,4])
parser.add_argument('--refine', action='store_true')
args = parser.parse_args()
ROOT = Path(__file__).resolve().parents[1]
BASE = ROOT / 'outputs/sharpa11_20261107'
WORK = ROOT / 'outputs/sharpa11_20261107_work'
width, height = (2400, 1600) if args.final else (768, 512)
if args.comparison:
width, height = 1200, 800
from isaacsim import SimulationApp
app = SimulationApp({'headless': True, 'width': width, 'height': height,
'disable_viewport_updates': True, 'multi_gpu': False, 'renderer': 'RayTracedLighting',
'extra_args': ['--/exts/isaacsim.core.simulation_manager/default_engine=physx',
'--/exts/isaacsim.physics.newton/auto_switch_on_startup=false']})
import carb
import numpy as np
import omni.usd
import omni.replicator.core as rep
from PIL import Image, ImageDraw
from pxr import Gf, Sdf, UsdGeom, UsdPhysics
def settings():
s = carb.settings.get_settings()
for key, value in [('/rtx/rtpt/gaussian/skipTonemapping/enabled', True),
('/rtx/post/tonemap/op', 0), ('/rtx/post/aa/op', 2),
('/rtx/hydra/geometrySyncLoads', True),
('/rtx-transient/hydra/geometrystreaming/syncLoad', True),
('/rtx/hydra/readTransformsFromFabricInRenderDelegate', False)]:
s.set(key, value)
def physics_check(stage, directory, views):
import omni.physx
from isaacsim.core.api import World
world = World(physics_dt=1/120, rendering_dt=1/12, stage_units_in_meters=1.)
world.reset()
world.step(render=False)
query = omni.physx.get_physx_scene_query_interface()
hits = []
drops = []
vec = lambda v: carb.Float3(*map(float, v))
for view in views:
eye = np.array(view['eye'])
h = query.raycast_closest(vec(eye), vec([0, 0, -1]), 3.5, True)
if h.get('hit'):
hits.append(dict(camera=view['index'], collision=h['collision'], distance=float(h['distance']),
position=list(map(float, h['position'])), normal=list(map(float, h['normal']))))
p = np.array(h['position'])
# Pick only broad, horizontal surfaces with local support.
if abs(h['normal'][2]) < .9 or p[2] > .35 or len(drops) >= 8:
continue
if any(np.linalg.norm(p[:2] - np.array(x['surface'])[:2]) < 1.2 for x in drops):
continue
supported = True
for delta in [[.12, 0], [-.12, 0], [0, .12], [0, -.12]]:
q = eye.copy(); q[:2] += delta
h2 = query.raycast_closest(vec(q), vec([0, 0, -1]), 3.5, True)
if not h2.get('hit') or abs(h2['position'][2] - p[2]) > .045:
supported = False
if supported:
path = f'/World/Validation/Drop_{len(drops)}'
sphere = UsdGeom.Sphere.Define(stage, path)
sphere.CreateRadiusAttr(.065)
sphere.AddTranslateOp().Set(Gf.Vec3d(*(p + [0, 0, .45])))
UsdPhysics.CollisionAPI.Apply(sphere.GetPrim())
UsdPhysics.RigidBodyAPI.Apply(sphere.GetPrim())
UsdPhysics.MassAPI.Apply(sphere.GetPrim()).CreateMassAttr(1.)
drops.append(dict(path=path, surface=p.tolist()))
assert len(hits) >= 32, ('too few floor ray hits', len(hits))
assert len(drops) >= 3, ('too few floor probes', len(drops))
wall_hits = []
for view in views[::3]:
origin = np.array(view['eye']); origin[2] = .85
for theta in np.linspace(0, 2*np.pi, 12, endpoint=False):
h = query.raycast_closest(vec(origin), vec([np.cos(theta), np.sin(theta), 0]), 6., True)
if h.get('hit') and abs(h['normal'][2]) < .35:
wall_hits.append(dict(camera=view['index'], collision=h['collision'], distance=float(h['distance'])))
assert len(wall_hits) >= 24, ('too few wall/furniture ray hits', len(wall_hits))
world.reset()
for _ in range(480):
world.step(render=False)
interface = omni.physx.get_physx_interface()
for row in drops:
position = interface.get_rigidbody_transformation(row['path'])['position']
row['settled_position'] = list(map(float, position))
row['height_error_m'] = float(position[2] - row['surface'][2] - .065)
row['passed'] = abs(row['height_error_m']) < .01
world.stop()
stage.RemovePrim('/World/Validation')
World.clear_instance()
report = dict(backend='PhysX', physics_dt=1/120, floor_raycast_hits=hits, wall_and_furniture_raycast_hits=wall_hits, sphere_drop_tests=drops,
height_tolerance_m=.01, maximum_sphere_height_error_m=max(abs(x['height_error_m']) for x in drops),
passed=all(x['passed'] for x in drops))
(directory / 'physics_validation.json').write_text(json.dumps(report, indent=2))
assert report['passed'], report
print('PHYSICS_PASS', directory.name, len(hits), 'rays', len(drops), 'drops', flush=True)
try:
for directory in sorted(BASE.iterdir()):
if not (directory / 'build.json').is_file() or (args.scenes and directory.name not in args.scenes):
continue
refinements = json.loads((WORK/'refinements.json').read_text()) if args.refine else {}
if args.refine and directory.name not in refinements:
continue
replace_slot = refinements[directory.name]['slot'] if args.refine else args.replace_slot
views = json.loads((directory / 'candidate_cameras.json').read_text())
selected = json.loads((WORK / 'selection.json').read_text())[directory.name] if args.final else list(range(len(views)))
if args.comparison:
final_views = json.loads((directory/'renders/cameras.json').read_text())
selected = [27 if directory.name == 'F013' else final_views[0]['index']]
if args.views:
selected = [int(i) for i in args.views.split(',')]
if args.refine:
selected = [refinements[directory.name]['view']]
output = directory / 'renders' if args.final else WORK / directory.name / 'candidates'
if args.before_floor:
output = WORK / directory.name / 'before_renders'
output.mkdir(parents=True, exist_ok=True)
print('OPEN', directory.name, flush=True)
ctx = omni.usd.get_context()
ctx.open_stage(str(WORK / directory.name / 'before_flat_floor.usdc' if args.before_floor else directory / 'scene.usdc'))
for _ in range(12):
app.update()
stage = ctx.get_stage()
stage.SetEditTarget(stage.GetSessionLayer())
settings()
if args.emissive:
import runpy
bind_particlefield_emissive_material = runpy.run_path(str(ROOT/'threedgrut/export/usd/writers/omni_material.py'))['bind_particlefield_emissive_material']
bind_particlefield_emissive_material(stage, stage.GetPrimAtPath('/World/Scan/Gaussians'))
if args.debug_simple_transform:
xform = UsdGeom.Xformable(stage.GetPrimAtPath('/World/Scan'))
old_M = np.array(xform.GetOrderedXformOps()[0].Get())
new_M = np.array([[1,0,0,0],[0,0,-1,0],[0,1,0,0],[0,0,1.2952302694320679,1.]])
xform.GetOrderedXformOps()[0].Set(Gf.Matrix4d(new_M.tolist()))
for view in views:
for name in ['eye', 'target']:
view[name] = (np.r_[view[name],1] @ np.linalg.inv(old_M) @ new_M)[:3].tolist()
if args.physics:
physics_check(stage, directory, views)
ctx.close_stage()
for _ in range(8):
app.update()
continue
camera = UsdGeom.Camera.Define(stage, '/World/CaptureCamera')
camera.CreateFocalLengthAttr(21.5)
camera.CreateHorizontalApertureAttr(36.)
camera.CreateVerticalApertureAttr(24.)
camera.CreateClippingRangeAttr(Gf.Vec2f(.03, 1000.))
transform = camera.MakeMatrixXform()
product = rep.create.render_product(str(camera.GetPath()), (width, height))
rgb = rep.AnnotatorRegistry.get_annotator('rgb')
rgb.attach([product])
rep.orchestrator.set_capture_on_play(False)
records = []
reserved_views = set()
if replace_slot:
existing_views = json.loads((output/'cameras.json').read_text())
reserved_views = {r['index'] for j,r in enumerate(existing_views) if j != replace_slot-1}
alternatives = {
'F009':[45,39,16,17], 'F010':[29,16,34,18], 'F011':[18,17,20,30],
'F012':[32,34,38,43], 'F013':[3,9,16,46], 'F014':[18,11,9,20],
'F017':[9,20,17,0], 'F025':[11,14,9,20], 'F026':[18,17,40,22],
'F029':[5,35,0,27], 'S069':[28,20,13,46]}
for sequence, i in enumerate(selected):
if args.final and not args.comparison and len(records) == 4:
break
view = views[i]
transform.Set(Gf.Matrix4d().SetLookAt(Gf.Vec3d(*view['eye']), Gf.Vec3d(*view['target']), Gf.Vec3d(0, 0, 1)).GetInverse())
settings()
for _ in range(24 if sequence == 0 or args.final else 5):
app.update()
rep.orchestrator.step(rt_subframes=16 if args.final else 3, delta_time=0., pause_timeline=True)
data = np.asarray(rgb.get_data())
assert data.shape[:2] == (height, width), data.shape
for retry in range(3):
if float(data[:, :, :3].mean()) > 4:
break
print('RETRY_CAPTURE', directory.name, i, retry+1, flush=True)
for _ in range(12):
app.update()
rep.orchestrator.step(rt_subframes=8, delta_time=0., pause_timeline=True)
data = np.asarray(rgb.get_data())
print('PIXELS', directory.name, i, float(data[:, :, :3].mean()), flush=True)
if args.final and not args.comparison and float(data[:, :, :3].mean()) <= 4:
remaining = [v for v in alternatives[directory.name] if v not in selected and v not in reserved_views]
assert remaining, ('no clear alternate view', directory.name, i)
selected.append(remaining[0])
print('ALTERNATE_VIEW', directory.name, i, 'replace_with', remaining[0], flush=True)
continue
assert float(data[:, :, :3].mean()) > 4, ('empty/dark render', directory.name, i)
name = f'{replace_slot or len(records)+1:02d}.png' if args.final else f'{i:02d}.jpg'
im = Image.fromarray(data[:, :, :3])
im.save(output / name, **({} if args.final else {'quality': 93}))
records.append(dict(**view, file=name, resolution=[width, height], renderer='Isaac Sim RTX native Gaussian',
dark_fraction=float((data[:, :, :3].max(2) < 8).mean())))
print('CAPTURE', directory.name, i, name, round(float(data[:, :, :3].mean()), 2), flush=True)
if args.final and not args.comparison:
if replace_slot:
assert len(records) == 1
existing = json.loads((output/'cameras.json').read_text())
existing[replace_slot-1] = records[0]
records = existing
assert len(records) == 4, (directory.name, len(records))
(output / 'cameras.json').write_text(json.dumps(records, indent=2))
cols = 2 if args.final else 8
thumb_w, thumb_h = (600, 400) if args.final else (256, 171)
sheet = Image.new('RGB', (cols*thumb_w, ((len(records)+cols-1)//cols)*(thumb_h+24)), (28, 31, 36))
draw = ImageDraw.Draw(sheet)
for j, record in enumerate(records):
im = Image.open(output / record['file']).resize((thumb_w, thumb_h), Image.Resampling.LANCZOS)
x, y = (j % cols)*thumb_w, (j // cols)*(thumb_h+24)
sheet.paste(im, (x, y))
draw.text((x+5, y+thumb_h+4), f'{directory.name} / {record["index"]:02d}', fill='white')
sheet_path = (WORK / directory.name / 'before_contact.jpg') if args.before_floor else ((directory / 'contact_sheet.jpg') if args.final else WORK / directory.name / 'candidates.jpg')
sheet.save(sheet_path, quality=94)
rgb.detach([product])
product.destroy()
ctx.close_stage()
for _ in range(8):
app.update()
print('DONE', directory.name, flush=True)
except BaseException:
import traceback
traceback.print_exc()
raise
finally:
app.close()