Download sharpa11_20261107/scripts/sharpa11_build.py from JoeyYuzy/humanoidBench: direct link, hf CLI and curl.
- Browser
- Download file 10.5 kB
-
https://huggingface.co/datasets/JoeyYuzy/humanoidBench/resolve/main/sharpa11_20261107/scripts/sharpa11_build.py
- Command line
-
hf download hf://datasets/JoeyYuzy/humanoidBench/sharpa11_20261107/scripts/sharpa11_build.py
-
curl -L -o sharpa11_build.py https://huggingface.co/datasets/JoeyYuzy/humanoidBench/resolve/main/sharpa11_20261107/scripts/sharpa11_build.py
10.5 kB
| """Build portable native Gaussian USD environments with static scan collisions.""" | |
| from pathlib import Path | |
| import argparse | |
| import gc | |
| import hashlib | |
| import json | |
| import time | |
| import runpy | |
| import fast_simplification | |
| import numpy as np | |
| from plyfile import PlyData | |
| from pxr import Gf, Sdf, Usd, UsdGeom, UsdPhysics, UsdShade, UsdVol, Vt | |
| ROOT = Path(__file__).resolve().parents[1] | |
| SOURCE = Path('/media/joey/ZhuoyuanSSD/sharpa11_20261107') | |
| OUT = ROOT / 'outputs/sharpa11_20261107' | |
| def save(path, data): | |
| path.write_text(json.dumps(data, ensure_ascii=False, indent=2)) | |
| def load_ply(path, mesh=False): | |
| # Fixed triangle lengths keep millions of Python objects out of memory. | |
| return PlyData.read(str(path), known_list_len={'face': {'vertex_indices': 3}} if mesh else {}) | |
| def columns(data, names): | |
| return np.column_stack([data[k] for k in names]).astype(np.float32) | |
| def cameras(result, floor): | |
| trajectory = json.loads((result / 'trajectory.json').read_text()) | |
| frames = [f for m in trajectory['mf_files'].values() for f in m['frames']] | |
| poses = np.array([f['cam2world_pose'] for f in frames]) | |
| # Capture cameras are pitched down. Level their yaw for architectural views. | |
| eyes = poses[:, :3, 3].copy() | |
| directions = poses[:, :3, 2].copy() | |
| directions[:, 1] = 0 | |
| directions /= np.maximum(np.linalg.norm(directions, axis=1, keepdims=True), 1e-8) | |
| eyes[:, 1] = floor - 1.40 | |
| features = np.c_[eyes[:, [0, 2]] / 2.0, directions[:, [0, 2]] * 1.1] | |
| picked = [int(np.argmin(np.linalg.norm(features - np.median(features, axis=0), axis=1)))] | |
| distance = np.full(len(features), np.inf) | |
| for _ in range(47): | |
| distance = np.minimum(distance, np.linalg.norm(features - features[picked[-1]], axis=1)) | |
| picked.append(int(np.argmax(distance))) | |
| records = [] | |
| for n, index in enumerate(picked): | |
| eye = eyes[index] | |
| target = eye + directions[index] * 3.0 | |
| target[1] += .22 # gentle downward pitch, keeps furniture in frame | |
| def world(p): | |
| return [float(p[0]), float(p[2]), float(floor - p[1])] | |
| records.append(dict(index=n, name=f'view_{n:02d}', frame_id=frames[index]['frame_id'], | |
| trajectory_index=index, eye=world(eye), target=world(target), | |
| focal_length_mm=21.5, horizontal_aperture_mm=36.0)) | |
| return records, poses | |
| def build(folder): | |
| start = time.monotonic() | |
| result = folder / 'v001/result' | |
| dest = OUT / folder.name.split('_')[0] | |
| dest.mkdir(parents=True, exist_ok=True) | |
| if (dest / 'build.json').exists(): | |
| print('SKIP', folder.name, flush=True) | |
| return | |
| print('LOAD', folder.name, flush=True) | |
| data = load_ply(result / 'gaussian.ply')['vertex'].data | |
| xyz = columns(data, 'xyz') | |
| raw = json.loads((result / 'trajectory.json').read_text()) | |
| poses = np.array([f['cam2world_pose'] for m in raw['mf_files'].values() for f in m['frames']]) | |
| lo = poses[:, :3, 3].min(0) - [1.8, 0, 1.8] | |
| hi = poses[:, :3, 3].max(0) + [1.8, 0, 1.8] | |
| near = (xyz[:, 0] > lo[0]) & (xyz[:, 0] < hi[0]) & (xyz[:, 2] > lo[2]) & (xyz[:, 2] < hi[2]) | |
| near &= (data['opacity'] > 1.0) | |
| eye_y = float(np.median(poses[:, 1, 3])) | |
| hist, edges = np.histogram(xyz[near, 1], bins=np.arange(eye_y + .65, eye_y + 2.5, .015)) | |
| floor = float(edges[np.argmax(hist)] + .0075) | |
| floor_pts = xyz[near & (abs(xyz[:, 1] - floor) < .025)] | |
| floor = float(np.median(floor_pts[:, 1])) | |
| views, poses = cameras(result, floor) | |
| save(dest / 'candidate_cameras.json', views) | |
| stage = Usd.Stage.CreateNew(str(dest / 'scene.usdc')) | |
| world = UsdGeom.Xform.Define(stage, '/World') | |
| stage.SetDefaultPrim(world.GetPrim()) | |
| UsdGeom.SetStageUpAxis(stage, 'Z') | |
| UsdGeom.SetStageMetersPerUnit(stage, 1.0) | |
| scan = UsdGeom.Xform.Define(stage, '/World/Scan') | |
| # Row-vector USD matrix: (x,y,z) -> (x,z,floor-y), a proper rotation. | |
| matrix = np.array([[1, 0, 0, 0], [0, 0, -1, 0], [0, 1, 0, 0], [0, 0, floor, 1]], float) | |
| scan.MakeMatrixXform().Set(Gf.Matrix4d(matrix.tolist())) | |
| field = UsdVol.ParticleField3DGaussianSplat.Define(stage, '/World/Scan/Gaussians') | |
| field.CreatePositionsAttr(Vt.Vec3fArray.FromNumpy(xyz)) | |
| rotations = columns(data, [f'rot_{i}' for i in range(4)]) | |
| rotations /= np.maximum(np.linalg.norm(rotations, axis=1, keepdims=True), 1e-12) | |
| # Vt's numpy storage is xyzw; Gaussian PLY uses wxyz. | |
| field.CreateOrientationsAttr(Vt.QuatfArray.FromNumpy(rotations[:, [1, 2, 3, 0]].copy())) | |
| scales = np.exp(columns(data, [f'scale_{i}' for i in range(3)])) | |
| assert np.isfinite(scales).all() and np.isfinite(xyz).all() | |
| field.CreateScalesAttr(Vt.Vec3fArray.FromNumpy(scales)) | |
| alpha = 1.0 / (1.0 + np.exp(-np.clip(data['opacity'], -80, 80))) | |
| field.CreateOpacitiesAttr(Vt.FloatArray.FromNumpy(alpha.astype('f'))) | |
| field.CreateRadianceSphericalHarmonicsDegreeAttr(0) | |
| coeff = field.CreateRadianceSphericalHarmonicsCoefficientsAttr(Vt.Vec3fArray.FromNumpy(columns(data, [f'f_dc_{i}' for i in range(3)]))) | |
| coeff.SetMetadata('elementSize', 1) | |
| field.CreateProjectionModeHintAttr('perspective') | |
| field.CreateSortingModeHintAttr('rayHitDistance') | |
| field.GetPrim().CreateAttribute('colorSpace:name', Sdf.ValueTypeNames.Token).Set('srgb_rec709_display') | |
| UsdShade.MaterialBindingAPI.Apply(field.GetPrim()) | |
| bind = runpy.run_path(str(ROOT / 'threedgrut/export/usd/writers/omni_material.py'))['bind_particlefield_emissive_material'] | |
| bind(stage, field.GetPrim()) | |
| # Include Gaussian support in the bound, even for large background splats. | |
| extent = np.array([(xyz - scales * 3).min(0), (xyz + scales * 3).max(0)], np.float32) | |
| field.CreateExtentAttr(Vt.Vec3fArray.FromNumpy(extent)) | |
| source_count = len(data) | |
| del rotations, scales, alpha, xyz, data | |
| gc.collect() | |
| print('GAUSSIANS', dest.name, source_count, 'floor', floor, flush=True) | |
| mesh = load_ply(result / 'mesh.ply', mesh=True) | |
| vertices = columns(mesh['vertex'].data, 'xyz') | |
| face_data = mesh['face'].data['vertex_indices'] | |
| faces = (np.stack(face_data) if face_data.dtype == object else np.asarray(face_data)).astype(np.int32) | |
| source_faces = len(faces) | |
| valid = np.isfinite(vertices).all(1)[faces].all(1) | |
| faces = faces[valid] | |
| del mesh | |
| if len(faces) > 900000: | |
| vertices, faces = fast_simplification.simplify(vertices.astype('d'), faces, | |
| target_count=900000, agg=5.0, preserve_border=True) | |
| vertices = vertices.astype('f') | |
| faces = faces.astype(np.int32) | |
| triangles = vertices[faces] | |
| cross = np.cross(triangles[:, 1] - triangles[:, 0], triangles[:, 2] - triangles[:, 0]) | |
| faces = faces[np.linalg.norm(cross, axis=1) > 1e-10] | |
| del cross, triangles | |
| centers = vertices[faces].mean(1) | |
| cells = np.floor(centers[:, [0, 2]] / 3).astype(int) | |
| tiles, groups = np.unique(cells, axis=0, return_inverse=True) | |
| material = UsdShade.Material.Define(stage, '/World/PhysicsMaterial') | |
| physics = UsdPhysics.MaterialAPI.Apply(material.GetPrim()) | |
| physics.CreateStaticFrictionAttr(.7) | |
| physics.CreateDynamicFrictionAttr(.5) | |
| physics.CreateRestitutionAttr(0.0) | |
| chunks = [] | |
| for i, tile in enumerate(tiles): | |
| ids, remap = np.unique(faces[groups == i], return_inverse=True) | |
| points = vertices[ids] | |
| geom = UsdGeom.Mesh.Define(stage, f'/World/Scan/Collisions/Tile_{i:03d}') | |
| geom.CreatePointsAttr(Vt.Vec3fArray.FromNumpy(points)) | |
| geom.CreateFaceVertexCountsAttr(Vt.IntArray.FromNumpy(np.full(len(remap) // 3, 3, np.int32))) | |
| geom.CreateFaceVertexIndicesAttr(Vt.IntArray.FromNumpy(remap.astype(np.int32))) | |
| geom.CreateSubdivisionSchemeAttr('none') | |
| geom.CreateDoubleSidedAttr(True) | |
| geom.CreateVisibilityAttr('invisible') | |
| geom.CreatePurposeAttr('guide') | |
| geom.CreateExtentAttr(Vt.Vec3fArray.FromNumpy(np.array([points.min(0), points.max(0)], 'f'))) | |
| prim = geom.GetPrim() | |
| UsdPhysics.CollisionAPI.Apply(prim).CreateCollisionEnabledAttr(True) | |
| UsdPhysics.MeshCollisionAPI.Apply(prim).CreateApproximationAttr('none') | |
| prim.AddAppliedSchema('PhysxCollisionAPI') | |
| prim.CreateAttribute('physxCollision:contactOffset', Sdf.ValueTypeNames.Float).Set(.008) | |
| prim.CreateAttribute('physxCollision:restOffset', Sdf.ValueTypeNames.Float).Set(0.) | |
| UsdShade.MaterialBindingAPI.Apply(prim).Bind(material, materialPurpose='physics') | |
| chunks.append(dict(path=str(prim.GetPath()), triangles=len(remap) // 3)) | |
| scene = UsdPhysics.Scene.Define(stage, '/World/PhysicsScene') | |
| scene.CreateGravityDirectionAttr(Gf.Vec3f(0, 0, -1)) | |
| scene.CreateGravityMagnitudeAttr(9.81) | |
| for view in views: | |
| camera = UsdGeom.Camera.Define(stage, f'/World/Cameras/View_{view["index"]:02d}') | |
| camera.CreateFocalLengthAttr(view['focal_length_mm']) | |
| camera.CreateHorizontalApertureAttr(36.) | |
| camera.CreateVerticalApertureAttr(24.) | |
| camera.CreateClippingRangeAttr(Gf.Vec2f(.03, 1000.)) | |
| camera.MakeMatrixXform().Set(Gf.Matrix4d().SetLookAt(Gf.Vec3d(*view['eye']), Gf.Vec3d(*view['target']), Gf.Vec3d(0, 0, 1)).GetInverse()) | |
| stage.GetRootLayer().Save() | |
| report = dict(scene=folder.name, entry='scene.usdc', gaussian_count=source_count, sh_degree=0, | |
| source_mesh_triangles=source_faces, collision_triangles=len(faces), collision_tiles=chunks, | |
| collision_method='static concave triangle mesh, quadric simplification with preserved borders; no apartment convex hull', | |
| source_to_world_matrix=matrix.tolist(), floor_source_y=floor, meters_per_unit=1., up_axis='Z', | |
| original_gaussian_arrays_preserved=True, normalized_quaternions=True, | |
| source_gaussian_sha256=hashlib.file_digest((result / 'gaussian.ply').open('rb'), 'sha256').hexdigest(), | |
| source_mesh_sha256=hashlib.file_digest((result / 'mesh.ply').open('rb'), 'sha256').hexdigest(), | |
| elapsed_s=time.monotonic() - start) | |
| save(dest / 'build.json', report) | |
| print('BUILT', dest.name, 'triangles', len(faces), 'seconds', round(report['elapsed_s']), flush=True) | |
| if __name__ == '__main__': | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument('scenes', nargs='*') | |
| args = parser.parse_args() | |
| OUT.mkdir(parents=True, exist_ok=True) | |
| for folder in sorted(SOURCE.iterdir()): | |
| if not args.scenes or folder.name.split('_')[0] in args.scenes: | |
| build(folder) | |
| gc.collect() | |