File size: 8,209 Bytes
8ca7ba0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
from __future__ import annotations

import hashlib
import json
import os
import shutil
import uuid
from pathlib import Path

from packages.core.contracts import SceneBundle, canonical_sha256
from packages.core.files import atomic_write_text
from packages.robots.profiles import get_robot_profile
from packages.runtime.isaac.contracts import RobotInjectionSpec


def _sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(4 * 1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def _usd_identifier(value: str) -> str:
    sanitized = "".join(
        character if character.isalnum() or character == "_" else "_"
        for character in value
    )
    if not sanitized:
        raise ValueError("USD identifier cannot be empty")
    return sanitized if not sanitized[0].isdigit() else f"_{sanitized}"


def _usd_path(path: str | Path) -> str:
    return str(path).replace("\\", "/").replace("@", "%40")


def load_and_verify_bundle(bundle_root: Path) -> SceneBundle:
    bundle_root = bundle_root.resolve()
    manifest = bundle_root / "manifests" / "scene_bundle.json"
    if not manifest.is_file():
        raise FileNotFoundError(f"SceneBundle manifest is missing: {manifest}")
    bundle = SceneBundle.model_validate_json(manifest.read_text(encoding="utf-8"))
    hashes = bundle.provenance.get("artifact_sha256")
    if not isinstance(hashes, dict) or not hashes:
        raise ValueError("SceneBundle provenance has no artifact SHA-256 ledger")
    for relative, expected in hashes.items():
        if not isinstance(relative, str) or not isinstance(expected, str):
            raise ValueError("SceneBundle artifact ledger must map paths to hashes")
        path = (bundle_root / relative).resolve()
        if not path.is_relative_to(bundle_root):
            raise ValueError(f"SceneBundle artifact path escapes bundle root: {relative}")
        if not path.is_file():
            raise FileNotFoundError(f"SceneBundle artifact is missing: {relative}")
        actual = _sha256(path)
        if actual != expected:
            raise ValueError(
                f"SceneBundle artifact hash differs for {relative}: {actual} != {expected}"
            )
    root = (bundle_root / bundle.layer_uris["root"]).resolve()
    if not root.is_relative_to(bundle_root) or not root.is_file():
        raise ValueError("SceneBundle root layer is missing or escapes bundle root")
    return bundle


def _robot_layer(
    *,
    robot_id: str,
    robot_reference: str,
    translation_m: tuple[float, float, float],
    yaw_deg: float,
) -> str:
    return (
        '#usda 1.0\n(\n    metersPerUnit = 1\n    upAxis = "Z"\n)\n\n'
        'over Xform "World" {\n'
        f'    def Xform "Robot" (\n        prepend references = @{_usd_path(robot_reference)}@\n'
        "    ) {\n"
        f'        custom string robothousegen_robot_id = "{robot_id}"\n'
        f"        double3 xformOp:translate = ({translation_m[0]:.9g}, "
        f"{translation_m[1]:.9g}, {translation_m[2]:.9g})\n"
        f"        float xformOp:rotateZ = {yaw_deg:.9g}\n"
        '        uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateZ"]\n'
        "    }\n}\n"
    )


def _composed_root(robot_layer: str, base_root: str) -> str:
    return (
        '#usda 1.0\n(\n    defaultPrim = "World"\n    metersPerUnit = 1\n'
        f"    subLayers = [\n        @{_usd_path(robot_layer)}@,\n"
        f"        @{_usd_path(base_root)}@\n    ]\n"
        '    upAxis = "Z"\n)\n\nover Xform "World" {}\n'
    )


class IsaacRobotInjector:
    version = "1.0"

    def inject(
        self,
        *,
        bundle_root: Path,
        output_dir: Path,
        robot_id: str,
        robot_asset: Path,
        robot_asset_sha256: str,
        stage_robot_asset: bool = True,
    ) -> RobotInjectionSpec:
        bundle_root = bundle_root.resolve()
        output_dir = output_dir.resolve()
        robot_asset = robot_asset.resolve()
        if output_dir.exists():
            raise FileExistsError(f"refusing to overwrite Isaac injection output: {output_dir}")
        bundle = load_and_verify_bundle(bundle_root)
        profile = get_robot_profile(robot_id)
        missing_capabilities = (
            bundle.scene_requirements.required_robot_capabilities - profile.capabilities
        )
        if missing_capabilities:
            raise ValueError(
                f"robot {robot_id} lacks required capabilities: {sorted(missing_capabilities)}"
            )
        if not robot_asset.is_file():
            raise FileNotFoundError(f"robot asset is missing: {robot_asset}")
        actual_robot_hash = _sha256(robot_asset)
        if actual_robot_hash != robot_asset_sha256:
            raise ValueError(
                f"robot asset hash differs: {actual_robot_hash} != {robot_asset_sha256}"
            )
        declared_hash = profile.metadata.get("scene_asset_sha256")
        if isinstance(declared_hash, str) and declared_hash != robot_asset_sha256:
            raise ValueError(
                f"robot profile hash differs for {robot_id}: {declared_hash} != "
                f"{robot_asset_sha256}"
            )

        output_dir.parent.mkdir(parents=True, exist_ok=True)
        staging = output_dir.parent / f".{output_dir.name}.tmp-{uuid.uuid4().hex[:12]}"
        layers = staging / "layers"
        manifests = staging / "manifests"
        layers.mkdir(parents=True)
        manifests.mkdir()
        if stage_robot_asset:
            asset_root = staging / "assets" / "robots" / _usd_identifier(robot_id)
            shutil.copytree(robot_asset.parent, asset_root)
            packaged_robot = asset_root / robot_asset.name
            if _sha256(packaged_robot) != robot_asset_sha256:
                raise ValueError("packaged robot asset hash differs after staging")
            robot_reference = os.path.relpath(packaged_robot, start=layers).replace("\\", "/")
        else:
            packaged_robot = robot_asset
            robot_reference = robot_asset.as_posix()
        injection_layer = layers / "robot.usda"
        atomic_write_text(
            injection_layer,
            _robot_layer(
                robot_id=robot_id,
                robot_reference=robot_reference,
                translation_m=bundle.robot_start.translation_m,
                yaw_deg=bundle.robot_start.yaw_deg,
            ),
        )
        base_root = (bundle_root / bundle.layer_uris["root"]).resolve()
        relative_base = os.path.relpath(base_root, start=staging).replace("\\", "/")
        atomic_write_text(staging / "root.usda", _composed_root("layers/robot.usda", relative_base))
        spec = RobotInjectionSpec.for_bundle(
            bundle,
            robot_id=robot_id,
            robot_asset_uri=str(packaged_robot),
            robot_asset_sha256=robot_asset_sha256,
            robot_profile_version=profile.model_version,
            injection_layer_uri="layers/robot.usda",
        )
        atomic_write_text(
            manifests / "robot_injection.json",
            spec.model_dump_json(indent=2) + "\n",
        )
        atomic_write_text(
            manifests / "injection_provenance.json",
            json.dumps(
                {
                    "schema_version": "1.0",
                    "injector": f"IsaacRobotInjector/{self.version}",
                    "scene_bundle_manifest": str(
                        bundle_root / "manifests" / "scene_bundle.json"
                    ),
                    "scene_bundle_sha256": bundle.content_hash,
                    "robot_injection_sha256": canonical_sha256(spec),
                    "robot_asset_source": str(robot_asset),
                    "robot_asset_staged": stage_robot_asset,
                    "base_bundle_modified": False,
                },
                indent=2,
                sort_keys=True,
            )
            + "\n",
        )
        if output_dir.exists():
            raise FileExistsError(
                f"Isaac injection destination appeared during build: {output_dir}"
            )
        os.replace(staging, output_dir)
        return spec