diff --git a/.github/workflows/prerequisites.yml b/.github/workflows/prerequisites.yml new file mode 100644 index 0000000..51e17a8 --- /dev/null +++ b/.github/workflows/prerequisites.yml @@ -0,0 +1,88 @@ +name: Skill prerequisites +on: + push: + pull_request: + workflow_dispatch: +permissions: + contents: read +concurrency: + group: prerequisites-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true +jobs: + native-development: + name: CPU development cases / Linux / Python 3.12 + runs-on: ubuntu-latest + timeout-minutes: 20 + env: + OPENBLAS_NUM_THREADS: "1" + OMP_NUM_THREADS: "1" + PYTHONUNBUFFERED: "1" + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 + with: + persist-credentials: false + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 + with: + python-version: "3.12" + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 + with: + node-version: "22" + - name: Reproduce the pinned replay viewer + run: | + npm ci --ignore-scripts --prefix viewer + npm run --prefix viewer build:prerequisites + git diff --exit-code -- src/dvidia_training/prerequisite_lab.bundle.js + - name: Provision pinned native PiPER mechanics + run: | + python -m pip install '.[arm]' + python -m pip check + dvidia-prerequisites --help + dvidia-robot-sim fetch piper --output runs/prerequisite-assets-ci + dvidia-robot-sim audit piper runs/prerequisite-assets-ci + - name: Check native development cases and evidence contracts + env: + DVIDIA_ROBOT_PROFILE_ASSETS: runs/prerequisite-assets-ci + run: python -m unittest tests.test_hinged_shoebox tests.test_tool_reach tests.test_prerequisite_benchmark -v + - name: Retain every development attempt and its replay + run: >- + dvidia-prerequisites --assets runs/prerequisite-assets-ci + --output runs/prerequisites-development-ci --split development + --source-commit "$GITHUB_SHA" + - name: Verify exported receipts and checksums + run: | + python - <<'PY' + from hashlib import sha256 + import json + from pathlib import Path + root = Path('runs/prerequisites-development-ci') + protocol = json.loads((root / 'protocol.json').read_text()) + report = json.loads((root / 'benchmark.json').read_text()) + assert protocol['split'] == report['split'] == 'development' + expected = {row['id'] for row in protocol['attempts']} + assert expected == {row['id'] for row in report['attempts']} + assert len(report['attempts']) == len(expected) + assert all(row['valid'] for row in report['attempts']), 'A native or export error is not an expected task failure' + assert (root / 'benchmark.json').stat().st_size <= 8 * 1024 * 1024, 'Viewer index exceeds its fetch limit' + for row in report['attempts']: + receipt = json.loads((root / 'trials' / (row['id'] + '.json')).read_text()) + assert receipt['case']['split'] == 'development' + assert receipt['success'] == row['success'] and receipt['valid'] == row['valid'] + assert receipt['native_trace'] and receipt['native_trace_columns'] + times = [sample[0] for sample in receipt['native_trace']] + assert all(abs((b - a) - .002) < 1e-8 for a, b in zip(times, times[1:])), 'Dense trace lost a native step' + assert all((root / value).is_file() for value in row['replay'].values()) + integrity = json.loads((root / 'integrity.json').read_text()) + for name, expected_file in integrity['files'].items(): + content = (root / name).read_bytes() + assert len(content) == expected_file['bytes'] + assert sha256(content).hexdigest() == expected_file['sha256'], name + print(json.dumps({'attempts_retained': len(expected), 'groups': report['groups'], + 'scope': 'Development regression only; no heldout run or hardware qualification.'})) + PY + - name: Retain evidence even when a check fails + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: skill-prerequisites-development + path: runs/prerequisites-development-ci + if-no-files-found: ignore diff --git a/README.md b/README.md index ae575cd..cc53538 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,16 @@ **Research alpha.** The recorded demo covers the original one-scene simulation pilot; the frozen benchmark is a separate experiment. Training runs locally. No human-video action bridge or hardware skill is established. +**[Explore the two skill-prerequisite experiments](https://research.dvidia.org/papers/skill-prerequisites-v01/).** +The hinged shoe box and out-of-reach shoe now have runnable native MuJoCo scenes, +recorded 3D replays and all sixteen held-out attempts. A lid guard avoids two +simulated collisions while completion stays at 2/4. A mounted rake brings 3/4 +shoes into an intermediate reach checkpoint, but all subsequent retained lifts +fail. These authored policies make failures measurable; they are not learned or +hardware-qualified skills. [Run locally](docs/prerequisite-simulations.md) · +[Frozen results](benchmarks/skill-prerequisites-20261013/README.md) · +[Hugging Face](https://huggingface.co/spaces/Dvidia/robot-simulation-lab). + **[Open the live PiPER shoe workstation](https://dvidia-robot-simulation-lab.static.hf.space/workstation/v01/index.html).** Drag the tool target, move the native gripper, nudge a free shoe and inspect the resulting contacts. MuJoCo 3.15.0 runs locally in a browser worker; a warm 3D diff --git a/benchmarks/skill-prerequisites-20261013/README.md b/benchmarks/skill-prerequisites-20261013/README.md new file mode 100644 index 0000000..85a8afb --- /dev/null +++ b/benchmarks/skill-prerequisites-20261013/README.md @@ -0,0 +1,111 @@ +# Skill prerequisites v0.1 + +Two small native MuJoCo experiments expose whether an action is possible before +attempting it: a passive shoe-box lid, and a shoe beyond the controller's usable +workspace. These are authored PiPER controllers with simulator observations, +synthetic rigid objects and real native contacts. They are not learned skills +or hardware qualification. + +[Research and limitations](https://research.dvidia.org/papers/skill-prerequisites-v01/) +· [Inspect every trial](https://research.dvidia.org/downloads/topics/physical-grounding/runs/2026-10-13-skill-prerequisites-v01/lab/) +· [Hugging Face](https://huggingface.co/spaces/Dvidia/robot-simulation-lab) +· [Run locally](../../docs/prerequisite-simulations.md) + +## Frozen result + +Source was committed as `756306a2beda60ac54567971626080a56227e781` before this +single held-out run. All **16/16 attempts were valid** and retained. Four scene +conditions per task were run with both approaches. These are declared parameter +holdouts, not independent real-world reliability trials. No controller was +tuned after viewing these results. + +| Experiment | Baseline | Feedback and recovery | +| --- | --- | --- | +| Hinged box: task completion | 2/4 | 2/4 | +| Hinged box: lid contact over 0.5 N | 2/4 | 0/4 | +| Shoe: reaches retrieval checkpoint | 0/4 | 3/4 | +| Shoe: unsupported retained lift | 0/4 | 0/4 | + +The lid task is an inspection/access waypoint followed by withdrawal, **not +shoe extraction**. The guard avoids the two baseline lid contacts (75.15 N and +51.78 N peak normal force) by withdrawing and requesting help. Those tasks stay +unfinished. In the transient case it withdraws, waits, resumes, and completes in +2.30 s; the baseline already completed without contact in 1.60 s, so the guard +adds a 0.70 s nuisance delay. The 0.5 N threshold is a synthetic evaluation +criterion, not an injury limit. Hazards begin at reset; zero logged response +delay is an initial-state decision, not measured sudden-hazard or sensor latency. + +The rake is explicitly **pre-mounted**; selection and pickup are not tested. +The baseline has no tool, so this compares combined capability and strategy, +not an isolated policy effect. “Out of reach” means beyond a configured 0.54 m +controller x envelope, not a proof of the arm's global kinematic reach limit. +The short-tool case defers. Retrieval is a checkpoint at 6.6 s, not final +retention in the workspace. No shoe is welded, teleported or externally forced +during rollout. + +## What failed after retrieval + +- **Light shoe:** both fingers contact it, but it never meaningfully leaves the + table. Bilateral contact ends at 10.944 s; this is failed acquisition. +- **Offset shoe:** it rotates roughly 29 degrees during retrieval, only one + finger contacts during acquisition, and it ends at x=0.5624 m outside the + configured envelope. Reaching the earlier checkpoint did not remain true. +- **Heavy shoe:** it achieves an unsupported bilateral hold for roughly 606 ms, + then tips and loses the grip. World support returns at 12.454 s. Its raised + origin alone would misleadingly suggest a lift while its toe is supported. + +The scorer requires the **final 500 ms** to satisfy height, bilateral finger +contact, and absence of rake/world support. None passes. The current controller +checks lift success at the end, not continuously: the help request follows +the first bilateral-contact break by 1.656 s for the light case and 204 ms for +the heavy case. These simulated intervals do not measure hardware latency. + +The next development step is to recheck pose and workspace margin after clearing +the rake, require bilateral acquisition before a short test lift, verify that +the shoe follows while table support unloads, and monitor the grip throughout +the lift. New policies need a new untouched confirmation cohort; this result +remains a regression record. + +## Speed and evidence + +On the tested Darwin arm64 host, Python 3.12.9 and MuJoCo 3.15.0, 108.4 simulated +seconds took 5.496 s of summed native execution time, including initialization +and recording (about **19.7× simulated time**). Export added 12.970 s. Rendering, +network downloads, real perception and actuator latency are excluded. This is +one sequential run, not a universal hardware minimum or performance guarantee. +Native execution is CPU-only; browser replay requires WebGL2. Initial package +and model downloads need network access; native reruns can then be offline. + +Physics observations are retained every 2 ms, commands/replay poses every +20 ms. Trial receipts contain full native traces; motion files retain joint +state, issued controls, requested targets and body poses. Every failed task +remains visible. The browser plays recorded native poses; it does not run +physics. No raw human footage or credentials are included. + +This directory contains byte-identical compact [results](benchmark.json), +[frozen protocol](protocol.json), and [full export inventory](integrity.json). +All trial receipts, compressed geometry and motion are in the linked research +and Hugging Face export. Checksums establish artifact consistency, not physical +accuracy or authenticity. + +Validation: 19 native/evidence tests, 13 publication tests, pinned reproducible +viewer build, desktop and 390/320 px browser checks. GitHub CI reruns development +cases only and retains unsuccessful attempts. DVIDIA code and synthetic objects +are MIT; upstream PiPER, MuJoCo, renderer and font notices are preserved. + +## Reproduce + +```sh +git clone https://github.com/Dvidia-Inference/dvidia-training.git +cd dvidia-training +git checkout 756306a2beda60ac54567971626080a56227e781 +python3.12 -m venv .venv +.venv/bin/python -m pip install '.[arm]' +.venv/bin/dvidia-robot-sim fetch piper --output robot-assets +.venv/bin/dvidia-prerequisites --assets robot-assets --output results \ + --split heldout --source-commit 756306a2beda60ac54567971626080a56227e781 +.venv/bin/python -m http.server 8000 --bind 127.0.0.1 --directory results +``` + +Use `--split development` when changing a controller. Never overwrite the frozen +results or use this confirmation cohort as an unseen test after tuning on it. diff --git a/benchmarks/skill-prerequisites-20261013/benchmark.json b/benchmarks/skill-prerequisites-20261013/benchmark.json new file mode 100644 index 0000000..9a67ddc --- /dev/null +++ b/benchmarks/skill-prerequisites-20261013/benchmark.json @@ -0,0 +1,5824 @@ +{ + "schema": "dvidia.skill-prerequisites/v1", + "scope": "Authored PiPER policies in native MuJoCo with synthetic rigid objects and privileged simulator observations. Browser replay uses recorded poses; no learned policy, hardware safety qualification or real-world transfer result.", + "source": { + "commit": "756306a2beda60ac54567971626080a56227e781", + "protocol_sha256": "addb85407392ad8581861e53e4265b1e73eefd4753e7df835879f84c02ca4754", + "mujoco": "3.15.0", + "robot_assets": { + "profile": "piper", + "repository": "https://github.com/google-deepmind/mujoco_menagerie", + "commit": "0059d4335f8156206f63a35662313385f7ad6d74", + "files_verified": 90, + "bytes_verified": 34562302, + "lock_sha256": "4b2ee2ca675aceb2f826983cb3082a3e08e9aa0ff419b23078abcff08ebcc6fe", + "simulation_asset_license": "MIT" + } + }, + "split": "heldout", + "host": { + "system": "Darwin", + "machine": "arm64", + "python": "3.12.9", + "compute": "CPU native simulation; no GPU required for benchmark. Browser replay needs WebGL2." + }, + "learned_policy": false, + "hardware_validated": false, + "attempts": [ + { + "id": "hinged-box-open-medium-baseline", + "task": "hinged-box", + "policy": "baseline", + "case": { + "id": "open-medium", + "lid_angle_deg": 105.0, + "lid_velocity_rad_s": 0.0, + "lid_mass_kg": 0.18, + "hinge_damping": 0.04, + "split": "heldout" + }, + "valid": true, + "success": true, + "metrics": { + "outcome": "completed", + "task_success": true, + "inspection_waypoint_reached": true, + "return_completed": true, + "safe_abort": false, + "help_requested": false, + "resumed_count": 0, + "recovery_count": 0, + "intervention_count": 0, + "missed_interventions": 0, + "false_interventions": null, + "predicate_mismatch_interventions": 0, + "false_intervention_definition": "Not identifiable from the treated rollout alone. Compare this case against baseline: a withdrawal when baseline completes without contact is a counterfactual nuisance interruption, not proven necessary avoidance.", + "missed_intervention_definition": "At least one observed descending-lid predicate with no withdrawal command; this is guard coverage, not calibrated danger classification.", + "lid_robot_collision": false, + "other_environment_robot_collision": false, + "peak_contact_force_n": 0.0, + "peak_lid_robot_normal_force_n": 0.0, + "peak_other_environment_robot_force_n": 0.0, + "lid_robot_peak_force_time_integral_ns": 0.0, + "contact_duration_s": 0.0, + "hazard_duration_s": 0.0, + "first_hazard_s": null, + "first_intervention_s": null, + "first_command_s": null, + "first_contact_s": null, + "detection_time_s": null, + "command_time_s": null, + "reaction_measurement_scope": "Privileged native predicate sampled at 2 ms; authored command at 20 ms. No sensor, transport or actuator-response latency included.", + "first_response_latency_s": null, + "completion_time_s": 1.6, + "withdrawal_duration_s": null, + "simulated_seconds": 5.999999999999561, + "wall_seconds": 0.12938083289191127, + "physics_realtime_factor": 46.374720782730975, + "decision_latency_p50_ms": 0.025250017642974854, + "decision_latency_p95_ms": 0.05266699008643627, + "decision_latency_max_ms": 0.6882909219712019, + "native_steps": 3000, + "state_action_frame_timing": "Frame state and issued_ctrl are observed at t before the next native step; requested_joint_target is the authored 20 ms decision subsequently rate-limited into issued_ctrl.", + "state_action_units": { + "qpos_rad_m": { + "0:6": "arm rad", + "6:8": "finger m", + "8:11": "shoe position m", + "11:15": "shoe quaternion wxyz dimensionless", + "15": "hinge rad" + }, + "qvel_rad_m_s": { + "0:6": "arm rad/s", + "6:8": "finger m/s", + "8:11": "shoe linear m/s", + "11:14": "shoe angular rad/s", + "14": "hinge rad/s" + }, + "issued_ctrl": { + "0:6": "arm rad", + "6": "jaw m" + }, + "requested_joint_target": { + "0:6": "arm rad", + "6": "jaw m" + } + }, + "terminal_phase": "done", + "failure_reason": null, + "solver_warnings": 0 + }, + "events": [ + { + "t": 0.82, + "type": "inspection_waypoint_reached", + "message": "Inspection waypoint held for 200 ms; no shoe grasp attempted." + }, + { + "t": 1.6, + "type": "return_complete", + "message": "Arm returned from the box." + } + ], + "errors": [], + "wall_seconds": 0.3934882921166718, + "native_trace_columns": [ + "t", + "lid_angle_rad", + "lid_velocity_rad_s", + "lid_robot_normal_force_n", + "risk", + "other_environment_robot_force_n" + ], + "replay": { + "model": "trials/hinged-box-open-medium-baseline.model.json", + "motion": "trials/hinged-box-open-medium-baseline.motion.json" + }, + "export_seconds": 0.8064577919431031 + }, + { + "id": "hinged-box-open-medium-recovery", + "task": "hinged-box", + "policy": "recovery", + "case": { + "id": "open-medium", + "lid_angle_deg": 105.0, + "lid_velocity_rad_s": 0.0, + "lid_mass_kg": 0.18, + "hinge_damping": 0.04, + "split": "heldout" + }, + "valid": true, + "success": true, + "metrics": { + "outcome": "completed", + "task_success": true, + "inspection_waypoint_reached": true, + "return_completed": true, + "safe_abort": false, + "help_requested": false, + "resumed_count": 0, + "recovery_count": 0, + "intervention_count": 0, + "missed_interventions": 0, + "false_interventions": null, + "predicate_mismatch_interventions": 0, + "false_intervention_definition": "Not identifiable from the treated rollout alone. Compare this case against baseline: a withdrawal when baseline completes without contact is a counterfactual nuisance interruption, not proven necessary avoidance.", + "missed_intervention_definition": "At least one observed descending-lid predicate with no withdrawal command; this is guard coverage, not calibrated danger classification.", + "lid_robot_collision": false, + "other_environment_robot_collision": false, + "peak_contact_force_n": 0.0, + "peak_lid_robot_normal_force_n": 0.0, + "peak_other_environment_robot_force_n": 0.0, + "lid_robot_peak_force_time_integral_ns": 0.0, + "contact_duration_s": 0.0, + "hazard_duration_s": 0.0, + "first_hazard_s": null, + "first_intervention_s": null, + "first_command_s": null, + "first_contact_s": null, + "detection_time_s": null, + "command_time_s": null, + "reaction_measurement_scope": "Privileged native predicate sampled at 2 ms; authored command at 20 ms. No sensor, transport or actuator-response latency included.", + "first_response_latency_s": null, + "completion_time_s": 1.6, + "withdrawal_duration_s": null, + "simulated_seconds": 5.999999999999561, + "wall_seconds": 0.11501841596327722, + "physics_realtime_factor": 52.165559312825394, + "decision_latency_p50_ms": 0.022166874259710312, + "decision_latency_p95_ms": 0.031250063329935074, + "decision_latency_max_ms": 0.38862484507262707, + "native_steps": 3000, + "state_action_frame_timing": "Frame state and issued_ctrl are observed at t before the next native step; requested_joint_target is the authored 20 ms decision subsequently rate-limited into issued_ctrl.", + "state_action_units": { + "qpos_rad_m": { + "0:6": "arm rad", + "6:8": "finger m", + "8:11": "shoe position m", + "11:15": "shoe quaternion wxyz dimensionless", + "15": "hinge rad" + }, + "qvel_rad_m_s": { + "0:6": "arm rad/s", + "6:8": "finger m/s", + "8:11": "shoe linear m/s", + "11:14": "shoe angular rad/s", + "14": "hinge rad/s" + }, + "issued_ctrl": { + "0:6": "arm rad", + "6": "jaw m" + }, + "requested_joint_target": { + "0:6": "arm rad", + "6": "jaw m" + } + }, + "terminal_phase": "done", + "failure_reason": null, + "solver_warnings": 0 + }, + "events": [ + { + "t": 0.82, + "type": "inspection_waypoint_reached", + "message": "Inspection waypoint held for 200 ms; no shoe grasp attempted." + }, + { + "t": 1.6, + "type": "return_complete", + "message": "Arm returned from the box." + } + ], + "errors": [], + "wall_seconds": 0.26466808398254216, + "native_trace_columns": [ + "t", + "lid_angle_rad", + "lid_velocity_rad_s", + "lid_robot_normal_force_n", + "risk", + "other_environment_robot_force_n" + ], + "replay": { + "model": "trials/hinged-box-open-medium-recovery.model.json", + "motion": "trials/hinged-box-open-medium-recovery.motion.json" + }, + "export_seconds": 0.7667194160167128 + }, + { + "id": "hinged-box-falling-medium-baseline", + "task": "hinged-box", + "policy": "baseline", + "case": { + "id": "falling-medium", + "lid_angle_deg": 78.0, + "lid_velocity_rad_s": -0.15, + "lid_mass_kg": 0.18, + "hinge_damping": 0.04, + "split": "heldout" + }, + "valid": true, + "success": false, + "metrics": { + "outcome": "failed", + "task_success": false, + "inspection_waypoint_reached": false, + "return_completed": false, + "safe_abort": false, + "help_requested": false, + "resumed_count": 0, + "recovery_count": 0, + "intervention_count": 0, + "missed_interventions": 1, + "false_interventions": null, + "predicate_mismatch_interventions": 0, + "false_intervention_definition": "Not identifiable from the treated rollout alone. Compare this case against baseline: a withdrawal when baseline completes without contact is a counterfactual nuisance interruption, not proven necessary avoidance.", + "missed_intervention_definition": "At least one observed descending-lid predicate with no withdrawal command; this is guard coverage, not calibrated danger classification.", + "lid_robot_collision": true, + "other_environment_robot_collision": false, + "peak_contact_force_n": 75.14902957054223, + "peak_lid_robot_normal_force_n": 75.14902957054223, + "peak_other_environment_robot_force_n": 0.0, + "lid_robot_peak_force_time_integral_ns": 141.26438586923018, + "contact_duration_s": 5.756, + "hazard_duration_s": 0.254, + "first_hazard_s": 0.0, + "first_intervention_s": null, + "first_command_s": null, + "first_contact_s": 0.2460000000000002, + "detection_time_s": 0.0, + "command_time_s": null, + "reaction_measurement_scope": "Privileged native predicate sampled at 2 ms; authored command at 20 ms. No sensor, transport or actuator-response latency included.", + "first_response_latency_s": null, + "completion_time_s": null, + "withdrawal_duration_s": null, + "simulated_seconds": 5.999999999999561, + "wall_seconds": 0.12782333395443857, + "physics_realtime_factor": 46.93978645665904, + "decision_latency_p50_ms": 0.023333122953772545, + "decision_latency_p95_ms": 0.03620889037847519, + "decision_latency_max_ms": 0.5125841125845909, + "native_steps": 3000, + "state_action_frame_timing": "Frame state and issued_ctrl are observed at t before the next native step; requested_joint_target is the authored 20 ms decision subsequently rate-limited into issued_ctrl.", + "state_action_units": { + "qpos_rad_m": { + "0:6": "arm rad", + "6:8": "finger m", + "8:11": "shoe position m", + "11:15": "shoe quaternion wxyz dimensionless", + "15": "hinge rad" + }, + "qvel_rad_m_s": { + "0:6": "arm rad/s", + "6:8": "finger m/s", + "8:11": "shoe linear m/s", + "11:14": "shoe angular rad/s", + "14": "hinge rad/s" + }, + "issued_ctrl": { + "0:6": "arm rad", + "6": "jaw m" + }, + "requested_joint_target": { + "0:6": "arm rad", + "6": "jaw m" + } + }, + "terminal_phase": "access", + "failure_reason": "lid_robot_contact", + "solver_warnings": 0 + }, + "events": [ + { + "t": 0.0, + "type": "hazard_started", + "message": "hazard started", + "lid_angle_rad": 1.361356816555577, + "lid_velocity_rad_s": -0.15 + }, + { + "t": 0.246, + "type": "hazardous_contact", + "message": "Lid contacted the robot above the synthetic benchmark threshold.", + "normal_force_n": 75.14902957054223 + }, + { + "t": 0.256, + "type": "hazard_cleared", + "message": "hazard cleared", + "lid_angle_rad": 1.1018116616821287, + "lid_velocity_rad_s": 0.03589133175633971 + } + ], + "errors": [], + "wall_seconds": 0.21409979090094566, + "native_trace_columns": [ + "t", + "lid_angle_rad", + "lid_velocity_rad_s", + "lid_robot_normal_force_n", + "risk", + "other_environment_robot_force_n" + ], + "replay": { + "model": "trials/hinged-box-falling-medium-baseline.model.json", + "motion": "trials/hinged-box-falling-medium-baseline.motion.json" + }, + "export_seconds": 0.7660804591141641 + }, + { + "id": "hinged-box-falling-medium-recovery", + "task": "hinged-box", + "policy": "recovery", + "case": { + "id": "falling-medium", + "lid_angle_deg": 78.0, + "lid_velocity_rad_s": -0.15, + "lid_mass_kg": 0.18, + "hinge_damping": 0.04, + "split": "heldout" + }, + "valid": true, + "success": false, + "metrics": { + "outcome": "safe_abort", + "task_success": false, + "inspection_waypoint_reached": false, + "return_completed": false, + "safe_abort": true, + "help_requested": true, + "resumed_count": 0, + "recovery_count": 0, + "intervention_count": 1, + "missed_interventions": 0, + "false_interventions": null, + "predicate_mismatch_interventions": 0, + "false_intervention_definition": "Not identifiable from the treated rollout alone. Compare this case against baseline: a withdrawal when baseline completes without contact is a counterfactual nuisance interruption, not proven necessary avoidance.", + "missed_intervention_definition": "At least one observed descending-lid predicate with no withdrawal command; this is guard coverage, not calibrated danger classification.", + "lid_robot_collision": false, + "other_environment_robot_collision": false, + "peak_contact_force_n": 0.0, + "peak_lid_robot_normal_force_n": 0.0, + "peak_other_environment_robot_force_n": 0.0, + "lid_robot_peak_force_time_integral_ns": 0.0, + "contact_duration_s": 0.0, + "hazard_duration_s": 0.234, + "first_hazard_s": 0.0, + "first_intervention_s": 0.0, + "first_command_s": 0.0, + "first_contact_s": null, + "detection_time_s": 0.0, + "command_time_s": 0.0, + "reaction_measurement_scope": "Privileged native predicate sampled at 2 ms; authored command at 20 ms. No sensor, transport or actuator-response latency included.", + "first_response_latency_s": 0.0, + "completion_time_s": null, + "withdrawal_duration_s": 0.24, + "simulated_seconds": 5.999999999999561, + "wall_seconds": 0.22258195793256164, + "physics_realtime_factor": 26.956362751636206, + "decision_latency_p50_ms": 0.026250025257468224, + "decision_latency_p95_ms": 0.0813750084489584, + "decision_latency_max_ms": 0.2531670033931732, + "native_steps": 3000, + "state_action_frame_timing": "Frame state and issued_ctrl are observed at t before the next native step; requested_joint_target is the authored 20 ms decision subsequently rate-limited into issued_ctrl.", + "state_action_units": { + "qpos_rad_m": { + "0:6": "arm rad", + "6:8": "finger m", + "8:11": "shoe position m", + "11:15": "shoe quaternion wxyz dimensionless", + "15": "hinge rad" + }, + "qvel_rad_m_s": { + "0:6": "arm rad/s", + "6:8": "finger m/s", + "8:11": "shoe linear m/s", + "11:14": "shoe angular rad/s", + "14": "hinge rad/s" + }, + "issued_ctrl": { + "0:6": "arm rad", + "6": "jaw m" + }, + "requested_joint_target": { + "0:6": "arm rad", + "6": "jaw m" + } + }, + "terminal_phase": "help", + "failure_reason": null, + "solver_warnings": 0 + }, + "events": [ + { + "t": 0.0, + "type": "hazard_started", + "message": "hazard started", + "lid_angle_rad": 1.361356816555577, + "lid_velocity_rad_s": -0.15 + }, + { + "t": 0.0, + "type": "withdrawal_started", + "message": "Lid descending. Withdraw from the access path.", + "reason": "descending_lid_in_access_volume" + }, + { + "t": 0.236, + "type": "hazard_cleared", + "message": "hazard cleared", + "lid_angle_rad": 1.1249947528113922, + "lid_velocity_rad_s": -1.7849407292489452 + }, + { + "t": 0.24, + "type": "withdrawal_complete", + "message": "Arm has reached the withdrawal waypoint." + }, + { + "t": 0.62, + "type": "help_requested", + "message": "Box closed. Stop here and request help reopening it.", + "reason": "closed_box_requires_reopening" + } + ], + "errors": [], + "wall_seconds": 0.30864725005812943, + "native_trace_columns": [ + "t", + "lid_angle_rad", + "lid_velocity_rad_s", + "lid_robot_normal_force_n", + "risk", + "other_environment_robot_force_n" + ], + "replay": { + "model": "trials/hinged-box-falling-medium-recovery.model.json", + "motion": "trials/hinged-box-falling-medium-recovery.motion.json" + }, + "export_seconds": 0.7754464999306947 + }, + { + "id": "hinged-box-falling-low-baseline", + "task": "hinged-box", + "policy": "baseline", + "case": { + "id": "falling-low", + "lid_angle_deg": 58.0, + "lid_velocity_rad_s": -0.25, + "lid_mass_kg": 0.1, + "hinge_damping": 0.02, + "split": "heldout" + }, + "valid": true, + "success": false, + "metrics": { + "outcome": "failed", + "task_success": false, + "inspection_waypoint_reached": false, + "return_completed": false, + "safe_abort": false, + "help_requested": false, + "resumed_count": 0, + "recovery_count": 0, + "intervention_count": 0, + "missed_interventions": 1, + "false_interventions": null, + "predicate_mismatch_interventions": 0, + "false_intervention_definition": "Not identifiable from the treated rollout alone. Compare this case against baseline: a withdrawal when baseline completes without contact is a counterfactual nuisance interruption, not proven necessary avoidance.", + "missed_intervention_definition": "At least one observed descending-lid predicate with no withdrawal command; this is guard coverage, not calibrated danger classification.", + "lid_robot_collision": true, + "other_environment_robot_collision": false, + "peak_contact_force_n": 51.77904813874703, + "peak_lid_robot_normal_force_n": 51.77904813874703, + "peak_other_environment_robot_force_n": 0.0, + "lid_robot_peak_force_time_integral_ns": 35.06363574717156, + "contact_duration_s": 5.704, + "hazard_duration_s": 0.22, + "first_hazard_s": 0.0, + "first_intervention_s": null, + "first_command_s": null, + "first_contact_s": 0.1440000000000001, + "detection_time_s": 0.0, + "command_time_s": null, + "reaction_measurement_scope": "Privileged native predicate sampled at 2 ms; authored command at 20 ms. No sensor, transport or actuator-response latency included.", + "first_response_latency_s": null, + "completion_time_s": null, + "withdrawal_duration_s": null, + "simulated_seconds": 5.999999999999561, + "wall_seconds": 0.1349219169933349, + "physics_realtime_factor": 44.47016566104645, + "decision_latency_p50_ms": 0.023667002096772194, + "decision_latency_p95_ms": 0.03770901821553707, + "decision_latency_max_ms": 0.11012493632733822, + "native_steps": 3000, + "state_action_frame_timing": "Frame state and issued_ctrl are observed at t before the next native step; requested_joint_target is the authored 20 ms decision subsequently rate-limited into issued_ctrl.", + "state_action_units": { + "qpos_rad_m": { + "0:6": "arm rad", + "6:8": "finger m", + "8:11": "shoe position m", + "11:15": "shoe quaternion wxyz dimensionless", + "15": "hinge rad" + }, + "qvel_rad_m_s": { + "0:6": "arm rad/s", + "6:8": "finger m/s", + "8:11": "shoe linear m/s", + "11:14": "shoe angular rad/s", + "14": "hinge rad/s" + }, + "issued_ctrl": { + "0:6": "arm rad", + "6": "jaw m" + }, + "requested_joint_target": { + "0:6": "arm rad", + "6": "jaw m" + } + }, + "terminal_phase": "access", + "failure_reason": "lid_robot_contact", + "solver_warnings": 0 + }, + "events": [ + { + "t": 0.0, + "type": "hazard_started", + "message": "hazard started", + "lid_angle_rad": 1.0122909661567112, + "lid_velocity_rad_s": -0.25 + }, + { + "t": 0.144, + "type": "hazardous_contact", + "message": "Lid contacted the robot above the synthetic benchmark threshold.", + "normal_force_n": 35.22383160509549 + }, + { + "t": 0.152, + "type": "hazard_cleared", + "message": "hazard cleared", + "lid_angle_rad": 0.7556852374942964, + "lid_velocity_rad_s": 0.08377058703362945 + }, + { + "t": 5.72, + "type": "lid_robot_contact_cleared", + "message": "lid robot contact cleared", + "normal_force_n": 0.0 + }, + { + "t": 5.726, + "type": "hazard_started", + "message": "hazard started", + "lid_angle_rad": 0.9240317836515525, + "lid_velocity_rad_s": -0.034359912565580755 + }, + { + "t": 5.726, + "type": "hazardous_contact", + "message": "Lid contacted the robot above the synthetic benchmark threshold.", + "normal_force_n": 6.474981028989265 + }, + { + "t": 5.728, + "type": "hazard_cleared", + "message": "hazard cleared", + "lid_angle_rad": 0.9242084106743222, + "lid_velocity_rad_s": 0.08831351138488996 + }, + { + "t": 5.732, + "type": "lid_robot_contact_cleared", + "message": "lid robot contact cleared", + "normal_force_n": 0.0 + }, + { + "t": 5.744, + "type": "hazard_started", + "message": "hazard started", + "lid_angle_rad": 0.9262706217411357, + "lid_velocity_rad_s": -0.07544176595926405 + }, + { + "t": 5.744, + "type": "hazardous_contact", + "message": "Lid contacted the robot above the synthetic benchmark threshold.", + "normal_force_n": 6.642775348164384 + }, + { + "t": 5.746, + "type": "hazard_cleared", + "message": "hazard cleared", + "lid_angle_rad": 0.9268129188990644, + "lid_velocity_rad_s": 0.2711485789643087 + }, + { + "t": 5.748, + "type": "lid_robot_contact_cleared", + "message": "lid robot contact cleared", + "normal_force_n": 0.0 + }, + { + "t": 5.766, + "type": "hazard_started", + "message": "hazard started", + "lid_angle_rad": 0.9320129773978277, + "lid_velocity_rad_s": -0.03558062235379913 + }, + { + "t": 5.768, + "type": "hazardous_contact", + "message": "Lid contacted the robot above the synthetic benchmark threshold.", + "normal_force_n": 3.460224732794111 + }, + { + "t": 5.77, + "type": "hazard_cleared", + "message": "hazard cleared", + "lid_angle_rad": 0.9325243505922517, + "lid_velocity_rad_s": 0.3532802761037329 + }, + { + "t": 5.77, + "type": "lid_robot_contact_cleared", + "message": "lid robot contact cleared", + "normal_force_n": 0.0 + }, + { + "t": 5.778, + "type": "hazardous_contact", + "message": "Lid contacted the robot above the synthetic benchmark threshold.", + "normal_force_n": 2.1687000521378224 + }, + { + "t": 5.78, + "type": "lid_robot_contact_cleared", + "message": "lid robot contact cleared", + "normal_force_n": 0.0 + }, + { + "t": 5.796, + "type": "hazard_started", + "message": "hazard started", + "lid_angle_rad": 0.9372082735755632, + "lid_velocity_rad_s": -0.07914753630848893 + }, + { + "t": 5.8, + "type": "hazardous_contact", + "message": "Lid contacted the robot above the synthetic benchmark threshold.", + "normal_force_n": 3.083021668315596 + }, + { + "t": 5.802, + "type": "hazard_cleared", + "message": "hazard cleared", + "lid_angle_rad": 0.936865919226627, + "lid_velocity_rad_s": 0.1689586720461404 + }, + { + "t": 5.804, + "type": "lid_robot_contact_cleared", + "message": "lid robot contact cleared", + "normal_force_n": 0.0 + }, + { + "t": 5.82, + "type": "hazard_started", + "message": "hazard started", + "lid_angle_rad": 0.9401664179124709, + "lid_velocity_rad_s": -0.07259775591052274 + }, + { + "t": 5.828, + "type": "hazardous_contact", + "message": "Lid contacted the robot above the synthetic benchmark threshold.", + "normal_force_n": 3.347580132049067 + }, + { + "t": 5.83, + "type": "hazard_cleared", + "message": "hazard cleared", + "lid_angle_rad": 0.9385934416223872, + "lid_velocity_rad_s": 0.1026564403041449 + }, + { + "t": 5.832, + "type": "lid_robot_contact_cleared", + "message": "lid robot contact cleared", + "normal_force_n": 0.0 + }, + { + "t": 5.846, + "type": "hazard_started", + "message": "hazard started", + "lid_angle_rad": 0.9413740064811053, + "lid_velocity_rad_s": -0.04990953410785816 + }, + { + "t": 5.858, + "type": "hazardous_contact", + "message": "Lid contacted the robot above the synthetic benchmark threshold.", + "normal_force_n": 3.305622073956844 + }, + { + "t": 5.86, + "type": "hazard_cleared", + "message": "hazard cleared", + "lid_angle_rad": 0.9383167755684451, + "lid_velocity_rad_s": 0.021031417877421778 + }, + { + "t": 5.862, + "type": "lid_robot_contact_cleared", + "message": "lid robot contact cleared", + "normal_force_n": 0.0 + }, + { + "t": 5.874, + "type": "hazard_started", + "message": "hazard started", + "lid_angle_rad": 0.940391520253433, + "lid_velocity_rad_s": -0.04311313921121756 + }, + { + "t": 5.884, + "type": "hazardous_contact", + "message": "Lid contacted the robot above the synthetic benchmark threshold.", + "normal_force_n": 3.4994860199157354 + }, + { + "t": 5.886, + "type": "hazard_cleared", + "message": "hazard cleared", + "lid_angle_rad": 0.9384165025876424, + "lid_velocity_rad_s": 0.12806579659795506 + }, + { + "t": 5.888, + "type": "lid_robot_contact_cleared", + "message": "lid robot contact cleared", + "normal_force_n": 0.0 + }, + { + "t": 5.904, + "type": "hazard_started", + "message": "hazard started", + "lid_angle_rad": 0.9421341332446737, + "lid_velocity_rad_s": -0.050205300898568624 + }, + { + "t": 5.904, + "type": "hazardous_contact", + "message": "Lid contacted the robot above the synthetic benchmark threshold.", + "normal_force_n": 42.03594081853243 + }, + { + "t": 5.924, + "type": "hazard_cleared", + "message": "hazard cleared", + "lid_angle_rad": 0.9402487674027503, + "lid_velocity_rad_s": -0.027798914446549035 + } + ], + "errors": [], + "wall_seconds": 0.22275129100307822, + "native_trace_columns": [ + "t", + "lid_angle_rad", + "lid_velocity_rad_s", + "lid_robot_normal_force_n", + "risk", + "other_environment_robot_force_n" + ], + "replay": { + "model": "trials/hinged-box-falling-low-baseline.model.json", + "motion": "trials/hinged-box-falling-low-baseline.motion.json" + }, + "export_seconds": 0.767625791952014 + }, + { + "id": "hinged-box-falling-low-recovery", + "task": "hinged-box", + "policy": "recovery", + "case": { + "id": "falling-low", + "lid_angle_deg": 58.0, + "lid_velocity_rad_s": -0.25, + "lid_mass_kg": 0.1, + "hinge_damping": 0.02, + "split": "heldout" + }, + "valid": true, + "success": false, + "metrics": { + "outcome": "safe_abort", + "task_success": false, + "inspection_waypoint_reached": false, + "return_completed": false, + "safe_abort": true, + "help_requested": true, + "resumed_count": 0, + "recovery_count": 0, + "intervention_count": 1, + "missed_interventions": 0, + "false_interventions": null, + "predicate_mismatch_interventions": 0, + "false_intervention_definition": "Not identifiable from the treated rollout alone. Compare this case against baseline: a withdrawal when baseline completes without contact is a counterfactual nuisance interruption, not proven necessary avoidance.", + "missed_intervention_definition": "At least one observed descending-lid predicate with no withdrawal command; this is guard coverage, not calibrated danger classification.", + "lid_robot_collision": false, + "other_environment_robot_collision": false, + "peak_contact_force_n": 0.0, + "peak_lid_robot_normal_force_n": 0.0, + "peak_other_environment_robot_force_n": 0.0, + "lid_robot_peak_force_time_integral_ns": 0.0, + "contact_duration_s": 0.0, + "hazard_duration_s": 0.234, + "first_hazard_s": 0.0, + "first_intervention_s": 0.0, + "first_command_s": 0.0, + "first_contact_s": null, + "detection_time_s": 0.0, + "command_time_s": 0.0, + "reaction_measurement_scope": "Privileged native predicate sampled at 2 ms; authored command at 20 ms. No sensor, transport or actuator-response latency included.", + "first_response_latency_s": 0.0, + "completion_time_s": null, + "withdrawal_duration_s": 0.24, + "simulated_seconds": 5.999999999999561, + "wall_seconds": 0.2775578750297427, + "physics_realtime_factor": 21.617113185336965, + "decision_latency_p50_ms": 0.045082997530698776, + "decision_latency_p95_ms": 0.15316717326641083, + "decision_latency_max_ms": 1.6051670536398888, + "native_steps": 3000, + "state_action_frame_timing": "Frame state and issued_ctrl are observed at t before the next native step; requested_joint_target is the authored 20 ms decision subsequently rate-limited into issued_ctrl.", + "state_action_units": { + "qpos_rad_m": { + "0:6": "arm rad", + "6:8": "finger m", + "8:11": "shoe position m", + "11:15": "shoe quaternion wxyz dimensionless", + "15": "hinge rad" + }, + "qvel_rad_m_s": { + "0:6": "arm rad/s", + "6:8": "finger m/s", + "8:11": "shoe linear m/s", + "11:14": "shoe angular rad/s", + "14": "hinge rad/s" + }, + "issued_ctrl": { + "0:6": "arm rad", + "6": "jaw m" + }, + "requested_joint_target": { + "0:6": "arm rad", + "6": "jaw m" + } + }, + "terminal_phase": "help", + "failure_reason": null, + "solver_warnings": 0 + }, + "events": [ + { + "t": 0.0, + "type": "hazard_started", + "message": "hazard started", + "lid_angle_rad": 1.0122909661567112, + "lid_velocity_rad_s": -0.25 + }, + { + "t": 0.0, + "type": "withdrawal_started", + "message": "Lid descending. Withdraw from the access path.", + "reason": "descending_lid_in_access_volume" + }, + { + "t": 0.236, + "type": "hazard_cleared", + "message": "hazard cleared", + "lid_angle_rad": 0.4240051705403173, + "lid_velocity_rad_s": -4.354716345155209 + }, + { + "t": 0.24, + "type": "withdrawal_complete", + "message": "Arm has reached the withdrawal waypoint." + }, + { + "t": 0.38, + "type": "help_requested", + "message": "Box closed. Stop here and request help reopening it.", + "reason": "closed_box_requires_reopening" + } + ], + "errors": [], + "wall_seconds": 0.36826050002127886, + "native_trace_columns": [ + "t", + "lid_angle_rad", + "lid_velocity_rad_s", + "lid_robot_normal_force_n", + "risk", + "other_environment_robot_force_n" + ], + "replay": { + "model": "trials/hinged-box-falling-low-recovery.model.json", + "motion": "trials/hinged-box-falling-low-recovery.motion.json" + }, + "export_seconds": 0.804564957972616 + }, + { + "id": "hinged-box-transient-damped-baseline", + "task": "hinged-box", + "policy": "baseline", + "case": { + "id": "transient-damped", + "lid_angle_deg": 110.0, + "lid_velocity_rad_s": -0.35, + "lid_mass_kg": 0.2, + "hinge_damping": 0.06, + "split": "heldout" + }, + "valid": true, + "success": true, + "metrics": { + "outcome": "completed", + "task_success": true, + "inspection_waypoint_reached": true, + "return_completed": true, + "safe_abort": false, + "help_requested": false, + "resumed_count": 0, + "recovery_count": 0, + "intervention_count": 0, + "missed_interventions": 1, + "false_interventions": null, + "predicate_mismatch_interventions": 0, + "false_intervention_definition": "Not identifiable from the treated rollout alone. Compare this case against baseline: a withdrawal when baseline completes without contact is a counterfactual nuisance interruption, not proven necessary avoidance.", + "missed_intervention_definition": "At least one observed descending-lid predicate with no withdrawal command; this is guard coverage, not calibrated danger classification.", + "lid_robot_collision": false, + "other_environment_robot_collision": false, + "peak_contact_force_n": 0.0, + "peak_lid_robot_normal_force_n": 0.0, + "peak_other_environment_robot_force_n": 0.0, + "lid_robot_peak_force_time_integral_ns": 0.0, + "contact_duration_s": 0.0, + "hazard_duration_s": 0.014, + "first_hazard_s": 0.0, + "first_intervention_s": null, + "first_command_s": null, + "first_contact_s": null, + "detection_time_s": 0.0, + "command_time_s": null, + "reaction_measurement_scope": "Privileged native predicate sampled at 2 ms; authored command at 20 ms. No sensor, transport or actuator-response latency included.", + "first_response_latency_s": null, + "completion_time_s": 1.6, + "withdrawal_duration_s": null, + "simulated_seconds": 5.999999999999561, + "wall_seconds": 0.11456795805133879, + "physics_realtime_factor": 52.37066368339143, + "decision_latency_p50_ms": 0.022249994799494743, + "decision_latency_p95_ms": 0.033999793231487274, + "decision_latency_max_ms": 0.380875077098608, + "native_steps": 3000, + "state_action_frame_timing": "Frame state and issued_ctrl are observed at t before the next native step; requested_joint_target is the authored 20 ms decision subsequently rate-limited into issued_ctrl.", + "state_action_units": { + "qpos_rad_m": { + "0:6": "arm rad", + "6:8": "finger m", + "8:11": "shoe position m", + "11:15": "shoe quaternion wxyz dimensionless", + "15": "hinge rad" + }, + "qvel_rad_m_s": { + "0:6": "arm rad/s", + "6:8": "finger m/s", + "8:11": "shoe linear m/s", + "11:14": "shoe angular rad/s", + "14": "hinge rad/s" + }, + "issued_ctrl": { + "0:6": "arm rad", + "6": "jaw m" + }, + "requested_joint_target": { + "0:6": "arm rad", + "6": "jaw m" + } + }, + "terminal_phase": "done", + "failure_reason": null, + "solver_warnings": 0 + }, + "events": [ + { + "t": 0.0, + "type": "hazard_started", + "message": "hazard started", + "lid_angle_rad": 1.9198621771937625, + "lid_velocity_rad_s": -0.35 + }, + { + "t": 0.016, + "type": "hazard_cleared", + "message": "hazard cleared", + "lid_angle_rad": 1.9172280498496113, + "lid_velocity_rad_s": -0.029336570903247795 + }, + { + "t": 0.82, + "type": "inspection_waypoint_reached", + "message": "Inspection waypoint held for 200 ms; no shoe grasp attempted." + }, + { + "t": 1.6, + "type": "return_complete", + "message": "Arm returned from the box." + } + ], + "errors": [], + "wall_seconds": 0.20038624992594123, + "native_trace_columns": [ + "t", + "lid_angle_rad", + "lid_velocity_rad_s", + "lid_robot_normal_force_n", + "risk", + "other_environment_robot_force_n" + ], + "replay": { + "model": "trials/hinged-box-transient-damped-baseline.model.json", + "motion": "trials/hinged-box-transient-damped-baseline.motion.json" + }, + "export_seconds": 0.7702044169418514 + }, + { + "id": "hinged-box-transient-damped-recovery", + "task": "hinged-box", + "policy": "recovery", + "case": { + "id": "transient-damped", + "lid_angle_deg": 110.0, + "lid_velocity_rad_s": -0.35, + "lid_mass_kg": 0.2, + "hinge_damping": 0.06, + "split": "heldout" + }, + "valid": true, + "success": true, + "metrics": { + "outcome": "recovered", + "task_success": true, + "inspection_waypoint_reached": true, + "return_completed": true, + "safe_abort": false, + "help_requested": false, + "resumed_count": 1, + "recovery_count": 1, + "intervention_count": 1, + "missed_interventions": 0, + "false_interventions": null, + "predicate_mismatch_interventions": 0, + "false_intervention_definition": "Not identifiable from the treated rollout alone. Compare this case against baseline: a withdrawal when baseline completes without contact is a counterfactual nuisance interruption, not proven necessary avoidance.", + "missed_intervention_definition": "At least one observed descending-lid predicate with no withdrawal command; this is guard coverage, not calibrated danger classification.", + "lid_robot_collision": false, + "other_environment_robot_collision": false, + "peak_contact_force_n": 0.0, + "peak_lid_robot_normal_force_n": 0.0, + "peak_other_environment_robot_force_n": 0.0, + "lid_robot_peak_force_time_integral_ns": 0.0, + "contact_duration_s": 0.0, + "hazard_duration_s": 0.014, + "first_hazard_s": 0.0, + "first_intervention_s": 0.0, + "first_command_s": 0.0, + "first_contact_s": null, + "detection_time_s": 0.0, + "command_time_s": 0.0, + "reaction_measurement_scope": "Privileged native predicate sampled at 2 ms; authored command at 20 ms. No sensor, transport or actuator-response latency included.", + "first_response_latency_s": 0.0, + "completion_time_s": 2.3, + "withdrawal_duration_s": 0.24, + "simulated_seconds": 5.999999999999561, + "wall_seconds": 0.11370991682633758, + "physics_realtime_factor": 52.76584635237229, + "decision_latency_p50_ms": 0.022458145394921303, + "decision_latency_p95_ms": 0.03174995072185993, + "decision_latency_max_ms": 0.06879214197397232, + "native_steps": 3000, + "state_action_frame_timing": "Frame state and issued_ctrl are observed at t before the next native step; requested_joint_target is the authored 20 ms decision subsequently rate-limited into issued_ctrl.", + "state_action_units": { + "qpos_rad_m": { + "0:6": "arm rad", + "6:8": "finger m", + "8:11": "shoe position m", + "11:15": "shoe quaternion wxyz dimensionless", + "15": "hinge rad" + }, + "qvel_rad_m_s": { + "0:6": "arm rad/s", + "6:8": "finger m/s", + "8:11": "shoe linear m/s", + "11:14": "shoe angular rad/s", + "14": "hinge rad/s" + }, + "issued_ctrl": { + "0:6": "arm rad", + "6": "jaw m" + }, + "requested_joint_target": { + "0:6": "arm rad", + "6": "jaw m" + } + }, + "terminal_phase": "done", + "failure_reason": null, + "solver_warnings": 0 + }, + "events": [ + { + "t": 0.0, + "type": "hazard_started", + "message": "hazard started", + "lid_angle_rad": 1.9198621771937625, + "lid_velocity_rad_s": -0.35 + }, + { + "t": 0.0, + "type": "withdrawal_started", + "message": "Lid descending. Withdraw from the access path.", + "reason": "descending_lid_in_access_volume" + }, + { + "t": 0.016, + "type": "hazard_cleared", + "message": "hazard cleared", + "lid_angle_rad": 1.9172280498496113, + "lid_velocity_rad_s": -0.029336570903247795 + }, + { + "t": 0.24, + "type": "withdrawal_complete", + "message": "Arm has reached the withdrawal waypoint." + }, + { + "t": 0.5, + "type": "access_resumed", + "message": "Lid aperture stable. Resume the inspection waypoint." + }, + { + "t": 1.52, + "type": "inspection_waypoint_reached", + "message": "Inspection waypoint held for 200 ms; no shoe grasp attempted." + }, + { + "t": 2.3, + "type": "return_complete", + "message": "Arm returned from the box." + } + ], + "errors": [], + "wall_seconds": 0.2058854578062892, + "native_trace_columns": [ + "t", + "lid_angle_rad", + "lid_velocity_rad_s", + "lid_robot_normal_force_n", + "risk", + "other_environment_robot_force_n" + ], + "replay": { + "model": "trials/hinged-box-transient-damped-recovery.model.json", + "motion": "trials/hinged-box-transient-damped-recovery.motion.json" + }, + "export_seconds": 0.7687181672081351 + }, + { + "id": "tool-reach-reach-heldout-light-baseline", + "task": "tool-reach", + "policy": "baseline", + "case": { + "id": "reach-heldout-light", + "shoe_x": 0.705, + "shoe_y": -0.09, + "mass": 0.22, + "friction": 0.45, + "tool_length": 0.34, + "lateral_error": 0.025, + "split": "heldout" + }, + "valid": true, + "success": false, + "metrics": { + "retrieval_success": false, + "grasp_attempted": true, + "retained_lift_success": false, + "final_shoe_speed_m_s": 1.7242212129766392e-12, + "shoe_displacement_x_m": 2.2724116033323583e-08, + "final_shoe_position_m": [ + 0.7049999772758839, + -0.09000005199336013, + -0.00010773877982213599 + ], + "peak_lift_m": 0.0, + "recovery_attempts": 0, + "help_requested": false, + "peak_tool_shoe_force_n": 0.0, + "peak_tool_shoe_force_time_s": 0.0, + "tool_shoe_impulse_ns": 0.0, + "tool_shoe_contact_ticks": 0, + "physics_timestep_s": 0.002, + "policy_interval_s": 0.02, + "max_joint_command_delta_rad": 0.0030000000000001137, + "max_tracking_error_m": 0.13176365447794705, + "simulation_seconds": 5.399999999999627, + "wall_seconds": 0.3661736659705639, + "solver_warnings": 0, + "native_steps": 2700, + "shoe_external_force_used": false, + "shoe_equality_constraints": 0, + "recovery_count": 0, + "intervention_count": 0, + "peak_contact_force_n": 0.0, + "contact_force_scope": "sum of normal shoe-to-robot/tool forces, excluding table", + "force_peak_by_phase_n": { + "settle": 0.0, + "direct_reach": 0.0, + "direct_close": 0.0, + "direct_lift": 0.0 + }, + "policy_compute_p50_ms": 0.024666544049978256, + "policy_compute_p95_ms": 0.05205823108553884, + "policy_compute_max_ms": 0.3849589265882969, + "wall_includes_model_compile": true, + "recorded_state_scope": "privileged native state; qpos has 6 arm radians, 2 jaw metres, shoe XYZ metres and quaternion wxyz; qvel has 6 arm rad/s, 2 jaw m/s, shoe linear m/s and angular rad/s; controls are 6 joint radians plus jaw metres; requested targets update every20ms and issued controls are rate limited every2ms", + "retention_criterion": "shoe bottom >35 mm with both fingers contacting, tool and world force each <0.01 N for final 500 ms", + "no_tool_baseline": true, + "tool_pre_equipped": false, + "outcome": "failed_direct_reach", + "real_time_factor": 14.747100902755045 + }, + "events": [ + { + "t": 0.0, + "type": "assumptions", + "message": "assumptions", + "pre_equipped_rigid_tool": false, + "privileged_observations": true, + "shoe_attachment": false, + "controller_reach_limit_x_m": 0.54, + "tool_acquisition_tested": false + }, + { + "t": 0.0, + "type": "phase", + "message": "settle", + "name": "settle", + "target": [ + 0.36, + -0.06, + 0.27 + ] + }, + { + "t": 0.4, + "type": "direct_reach_attempt", + "message": "direct reach attempt", + "desired_x_m": 0.7049999772540483, + "clipped_x_m": 0.54 + }, + { + "t": 0.4, + "type": "phase", + "message": "direct reach", + "name": "direct_reach", + "target": [ + 0.54, + -0.09, + 0.075 + ] + }, + { + "t": 2.9, + "type": "phase", + "message": "direct close", + "name": "direct_close", + "target": [ + 0.54, + -0.09, + 0.075 + ] + }, + { + "t": 3.9, + "type": "phase", + "message": "direct lift", + "name": "direct_lift", + "target": [ + 0.5, + -0.09, + 0.2 + ] + }, + { + "t": 5.4, + "type": "direct_reach_failed", + "message": "direct reach failed", + "shoe_x_m": 0.7049999772758839 + } + ], + "errors": [], + "wall_seconds": 0.3671923750080168, + "native_trace_columns": [ + "t_s", + "tool_shoe_force_n", + "shoe_robot_force_n", + "left_finger_force_n", + "right_finger_force_n", + "shoe_x_m", + "shoe_y_m", + "shoe_z_m", + "world_shoe_force_n" + ], + "control_compute_ms": [ + 0.030166003853082657, + 0.04570791497826576, + 0.05520787090063095, + 0.033125048503279686, + 0.03316602669656277, + 0.02591707743704319, + 0.07958291098475456, + 0.039250124245882034, + 0.02933293581008911, + 0.027499860152602196, + 0.02670893445611, + 0.03691599704325199, + 0.03441609442234039, + 0.029582995921373367, + 0.050208065658807755, + 0.08904095739126205, + 0.027999980375170708, + 0.24062511511147022, + 0.07624994032084942, + 0.0316668301820755, + 0.03087497316300869, + 0.026416964828968048, + 0.14566699974238873, + 0.02695806324481964, + 0.02987496554851532, + 0.056541990488767624, + 0.037582824006676674, + 0.027208123356103897, + 0.029207905754446983, + 0.0285410787910223, + 0.027583912014961243, + 0.028999987989664078, + 0.02866680733859539, + 0.04020892083644867, + 0.02837507054209709, + 0.027999980375170708, + 0.02350006252527237, + 0.023166881874203682, + 0.022624852135777473, + 0.02291589044034481, + 0.022207852452993393, + 0.0227498821914196, + 0.027125002816319466, + 0.02350006252527237, + 0.024042092263698578, + 0.02254103310406208, + 0.023750122636556625, + 0.022999942302703857, + 0.024999957531690598, + 0.02133287489414215, + 0.022582942619919777, + 0.02233288250863552, + 0.023416010662913322, + 0.02308306284248829, + 0.022499822080135345, + 0.02245907671749592, + 0.027291011065244675, + 0.030542025342583656, + 0.02808310091495514, + 0.023042084649205208, + 0.024957815185189247, + 0.022666994482278824, + 0.034041935577988625, + 0.02429191954433918, + 0.023958971723914146, + 0.024707987904548645, + 0.029374845325946808, + 0.03258301876485348, + 0.036207959055900574, + 0.07829209789633751, + 0.038917176425457, + 0.04487484693527222, + 0.04470907151699066, + 0.042750034481287, + 0.02966681495308876, + 0.027542002499103546, + 0.023333122953772545, + 0.02283393405377865, + 0.022124964743852615, + 0.02437504008412361, + 0.02150004729628563, + 0.021458137780427933, + 0.021707965061068535, + 0.023582950234413147, + 0.02233288250863552, + 0.024499837309122086, + 0.02391589805483818, + 0.06400002166628838, + 0.03474997356534004, + 0.02587493509054184, + 0.02454104833304882, + 0.024792039766907692, + 0.24445797316730022, + 0.037207966670393944, + 0.02629193477332592, + 0.024416018277406693, + 0.024624867364764214, + 0.02600019797682762, + 0.024707987904548645, + 0.02345792017877102, + 0.03695790655910969, + 0.02474989742040634, + 0.023290980607271194, + 0.02308306284248829, + 0.023250002413988113, + 0.024417182430624962, + 0.024584122002124786, + 0.024625100195407867, + 0.02666609361767769, + 0.026624882593750954, + 0.02891593612730503, + 0.029625138267874718, + 0.03824988380074501, + 0.02645794302225113, + 0.02474989742040634, + 0.029959017410874367, + 0.022541964426636696, + 0.022500054910779, + 0.02774992026388645, + 0.021541956812143326, + 0.022166874259710312, + 0.027292175218462944, + 0.023292144760489464, + 0.022707972675561905, + 0.02745911478996277, + 0.02591707743704319, + 0.028165988624095917, + 0.023042084649205208, + 0.025250017642974854, + 0.027125002816319466, + 0.02154218964278698, + 0.021459069103002548, + 0.021415995433926582, + 0.02195802517235279, + 0.02150004729628563, + 0.028416980057954788, + 0.023625092580914497, + 0.02245907671749592, + 0.023208092898130417, + 0.02129189670085907, + 0.021582935005426407, + 0.021250220015645027, + 0.02095801755785942, + 0.021124957129359245, + 0.022166874259710312, + 0.024833017960190773, + 0.022624852135777473, + 0.022208085283637047, + 0.021958956494927406, + 0.021958956494927406, + 0.02150004729628563, + 0.03091711550951004, + 0.026167137548327446, + 0.023167114704847336, + 0.028125010430812836, + 0.025999965146183968, + 0.02154218964278698, + 0.02187490463256836, + 0.022791791707277298, + 0.03004097379744053, + 0.02550007775425911, + 0.023541972041130066, + 0.022584106773138046, + 0.02254219725728035, + 0.02187490463256836, + 0.0213750172406435, + 0.02208305522799492, + 0.02133287489414215, + 0.021208077669143677, + 0.021707965061068535, + 0.021207844838500023, + 0.021792016923427582, + 0.021082814782857895, + 0.021207844838500023, + 0.021832995116710663, + 0.021249987185001373, + 0.02108304761350155, + 0.02429191954433918, + 0.02170889638364315, + 0.024041859433054924, + 0.021082814782857895, + 0.02095801755785942, + 0.3849589265882969, + 0.041041988879442215, + 0.02774992026388645, + 0.032250070944428444, + 0.023292144760489464, + 0.022750115022063255, + 0.02329191192984581, + 0.025916844606399536, + 0.022666994482278824, + 0.03087497316300869, + 0.02900022082030773, + 0.025042099878191948, + 0.023750122636556625, + 0.02491706982254982, + 0.0316668301820755, + 0.024999957531690598, + 0.0238749198615551, + 0.024541979655623436, + 0.030208146199584007, + 0.026332912966609, + 0.02604094333946705, + 0.024124979972839355, + 0.02391589805483818, + 0.025875167921185493, + 0.02337503246963024, + 0.023624859750270844, + 0.022666994482278824, + 0.02329191192984581, + 0.023207860067486763, + 0.03083399496972561, + 0.02329191192984581, + 0.02245907671749592, + 0.022416934370994568, + 0.027708010748028755, + 0.023124972358345985, + 0.02529192715883255, + 0.0227498821914196, + 0.022583873942494392, + 0.02383394166827202, + 0.02337503246963024, + 0.023416010662913322, + 0.02437504008412361, + 0.023541972041130066, + 0.027624890208244324, + 0.025084009394049644, + 0.052582938224077225, + 0.0274579506367445, + 0.025999965146183968, + 0.0314170029014349, + 0.03287498839199543, + 0.026250025257468224, + 0.028792070224881172, + 0.10037492029368877, + 0.03758398815989494, + 0.0644167885184288, + 0.037708086892962456, + 0.027042115107178688, + 0.027540838345885277, + 0.02395804040133953, + 0.02245907671749592, + 0.022582942619919777, + 0.025084009394049644, + 0.026124995201826096, + 0.024584122002124786, + 0.027667032554745674, + 0.026333145797252655, + 0.022625084966421127, + 0.02987496554851532, + 0.022666994482278824, + 0.022249994799494743, + 0.021875137463212013, + 0.021792016923427582, + 0.049625057727098465, + 0.026582973077893257, + 0.02487492747604847, + 0.04270789213478565, + 0.02904096618294716, + 0.024625100195407867, + 0.023250002413988113, + 0.023207860067486763, + 0.022999942302703857, + 0.02208305522799492, + 0.021832995116710663, + 0.02291705459356308, + 0.033624935895204544, + 0.025292159989476204, + 0.051416922360658646, + 0.028125010430812836 + ], + "replay": { + "model": "trials/tool-reach-reach-heldout-light-baseline.model.json", + "motion": "trials/tool-reach-reach-heldout-light-baseline.motion.json" + }, + "export_seconds": 0.7911238339729607 + }, + { + "id": "tool-reach-reach-heldout-light-recovery", + "task": "tool-reach", + "policy": "recovery", + "case": { + "id": "reach-heldout-light", + "shoe_x": 0.705, + "shoe_y": -0.09, + "mass": 0.22, + "friction": 0.45, + "tool_length": 0.34, + "lateral_error": 0.025, + "split": "heldout" + }, + "valid": true, + "success": false, + "metrics": { + "retrieval_success": true, + "grasp_attempted": true, + "retained_lift_success": false, + "final_shoe_speed_m_s": 1.896499766886143e-12, + "shoe_displacement_x_m": 0.28656510630532395, + "final_shoe_position_m": [ + 0.418434893694676, + -0.08818088242472046, + -0.00010773877982250796 + ], + "peak_lift_m": 1.0635365403159685e-06, + "recovery_attempts": 0, + "help_requested": true, + "peak_tool_shoe_force_n": 9.909911341959821, + "peak_tool_shoe_force_time_s": 3.01199999999989, + "tool_shoe_impulse_ns": 4.087742735838765, + "tool_shoe_contact_ticks": 1579, + "physics_timestep_s": 0.002, + "policy_interval_s": 0.02, + "max_joint_command_delta_rad": 0.0030000000000001137, + "max_tracking_error_m": 0.1799793021294707, + "simulation_seconds": 12.600000000000877, + "wall_seconds": 0.6967847920022905, + "solver_warnings": 0, + "native_steps": 6300, + "shoe_external_force_used": false, + "shoe_equality_constraints": 0, + "recovery_count": 0, + "intervention_count": 1, + "peak_contact_force_n": 16.11354148622675, + "contact_force_scope": "sum of normal shoe-to-robot/tool forces, excluding table", + "force_peak_by_phase_n": { + "settle": 0.0, + "approach_tool": 0.0, + "lower_tool": 9.909911341959821, + "pull_shoe": 2.8634868463419054, + "verify_pull": 0.9784170344898813, + "clear_rake": 1.2820732058853357, + "grasp_approach": 15.627302242958207, + "close_jaws": 16.11354148622675, + "lift": 16.033238859853576 + }, + "policy_compute_p50_ms": 0.02806249540299177, + "policy_compute_p95_ms": 0.14826083788648223, + "policy_compute_max_ms": 0.4645420704036951, + "wall_includes_model_compile": true, + "recorded_state_scope": "privileged native state; qpos has 6 arm radians, 2 jaw metres, shoe XYZ metres and quaternion wxyz; qvel has 6 arm rad/s, 2 jaw m/s, shoe linear m/s and angular rad/s; controls are 6 joint radians plus jaw metres; requested targets update every20ms and issued controls are rate limited every2ms", + "retention_criterion": "shoe bottom >35 mm with both fingers contacting, tool and world force each <0.01 N for final 500 ms", + "no_tool_baseline": false, + "tool_pre_equipped": true, + "outcome": "retrieved_lift_failed", + "real_time_factor": 18.083058276563904 + }, + "events": [ + { + "t": 0.0, + "type": "assumptions", + "message": "assumptions", + "pre_equipped_rigid_tool": true, + "privileged_observations": true, + "shoe_attachment": false, + "controller_reach_limit_x_m": 0.54, + "tool_acquisition_tested": false + }, + { + "t": 0.0, + "type": "phase", + "message": "settle", + "name": "settle", + "target": [ + 0.36, + -0.06, + 0.27 + ] + }, + { + "t": 0.4, + "type": "phase", + "message": "approach tool", + "name": "approach_tool", + "target": [ + 0.5299999772540482, + -0.06500005186998242, + 0.25 + ] + }, + { + "t": 2.2, + "type": "phase", + "message": "lower tool", + "name": "lower_tool", + "target": [ + 0.5299999772540482, + -0.06500005186998242, + 0.075 + ] + }, + { + "t": 3.2, + "type": "phase", + "message": "pull shoe", + "name": "pull_shoe", + "target": [ + 0.2, + -0.06500005186998242, + 0.075 + ] + }, + { + "t": 6.2, + "type": "phase", + "message": "verify pull", + "name": "verify_pull", + "target": [ + 0.2, + -0.06500005186998242, + 0.075 + ] + }, + { + "t": 6.6, + "type": "retrieval_check", + "message": "retrieval check", + "attempt": 1, + "retrieved": true, + "shoe_x_m": 0.39683146231299493, + "displacement_m": 0.30816853768700503 + }, + { + "t": 6.6, + "type": "phase", + "message": "clear rake", + "name": "clear_rake", + "target": [ + 0.24, + -0.09, + 0.25 + ] + }, + { + "t": 7.8, + "type": "phase", + "message": "grasp approach", + "name": "grasp_approach", + "target": [ + 0.35085077229346334, + -0.08969928519158654, + 0.06 + ] + }, + { + "t": 9.6, + "type": "phase", + "message": "close jaws", + "name": "close_jaws", + "target": [ + 0.35085077229346334, + -0.08969928519158654, + 0.06 + ] + }, + { + "t": 10.6, + "type": "phase", + "message": "lift", + "name": "lift", + "target": [ + 0.35085077229346334, + -0.08969928519158654, + 0.28 + ] + }, + { + "t": 12.6, + "type": "lift_check", + "message": "lift check", + "retained": false, + "shoe_bottom_z_m": -0.00010773877982250796 + }, + { + "t": 12.6, + "type": "help_requested", + "message": "retrieved but jaw lift not retained", + "reason": "retrieved_but_jaw_lift_not_retained" + } + ], + "errors": [], + "wall_seconds": 0.697494792053476, + "native_trace_columns": [ + "t_s", + "tool_shoe_force_n", + "shoe_robot_force_n", + "left_finger_force_n", + "right_finger_force_n", + "shoe_x_m", + "shoe_y_m", + "shoe_z_m", + "world_shoe_force_n" + ], + "control_compute_ms": [ + 0.023667002096772194, + 0.02833409234881401, + 0.02537504769861698, + 0.027291011065244675, + 0.03350013867020607, + 0.03629201091825962, + 0.03924989141523838, + 0.029792077839374542, + 0.03466685302555561, + 0.03770901821553707, + 0.04958314821124077, + 0.025916844606399536, + 0.024833017960190773, + 0.024124979972839355, + 0.024167122319340706, + 0.023916130885481834, + 0.023417174816131592, + 0.024290988221764565, + 0.022792024537920952, + 0.02295803278684616, + 0.023916130885481834, + 0.02445792779326439, + 0.026042107492685318, + 0.02395804040133953, + 0.023541972041130066, + 0.02291705459356308, + 0.03179209306836128, + 0.025957822799682617, + 0.02408307045698166, + 0.033709220588207245, + 0.025999965146183968, + 0.024207867681980133, + 0.023667002096772194, + 0.023165950551629066, + 0.032667070627212524, + 0.02687494270503521, + 0.02333289012312889, + 0.022417167201638222, + 0.022124964743852615, + 0.022541964426636696, + 0.021832995116710663, + 0.022041145712137222, + 0.022166874259710312, + 0.021666986867785454, + 0.05183299072086811, + 0.022042077034711838, + 0.030292198061943054, + 0.02687494270503521, + 0.03404216840863228, + 0.025582965463399887, + 0.023792032152414322, + 0.022249994799494743, + 0.02233288250863552, + 0.034667085856199265, + 0.02537504769861698, + 0.024333829060196877, + 0.023250002413988113, + 0.023124972358345985, + 0.024042092263698578, + 0.023292144760489464, + 0.022790860384702682, + 0.022540800273418427, + 0.02237502485513687, + 0.0227498821914196, + 0.021916814148426056, + 0.022541964426636696, + 0.022124964743852615, + 0.02295803278684616, + 0.022207852452993393, + 0.02183392643928528, + 0.023207860067486763, + 0.021791085600852966, + 0.02187490463256836, + 0.02191704697906971, + 0.021540792658925056, + 0.021582935005426407, + 0.025584129616618156, + 0.023042084649205208, + 0.02237502485513687, + 0.022042077034711838, + 0.02191704697906971, + 0.026582973077893257, + 0.02391706220805645, + 0.022541964426636696, + 0.02195802517235279, + 0.02829195000231266, + 0.03833300434052944, + 0.02412521280348301, + 0.02270890399813652, + 0.0227498821914196, + 0.022584106773138046, + 0.02254103310406208, + 0.021875137463212013, + 0.022292137145996094, + 0.0227498821914196, + 0.022792024537920952, + 0.02195802517235279, + 0.021875137463212013, + 0.022082822397351265, + 0.021625077351927757, + 0.022249994799494743, + 0.02229190431535244, + 0.023042084649205208, + 0.02354104071855545, + 0.023209024220705032, + 0.023165950551629066, + 0.034125056117773056, + 0.027750153094530106, + 0.026041874662041664, + 0.03150012344121933, + 0.027333153411746025, + 0.028207898139953613, + 0.024792039766907692, + 0.023541972041130066, + 0.023584114387631416, + 0.1038331538438797, + 0.029750168323516846, + 0.03129197284579277, + 0.02591707743704319, + 0.02395804040133953, + 0.02337503246963024, + 0.030749943107366562, + 0.024416949599981308, + 0.030291033908724785, + 0.04141614772379398, + 0.027624890208244324, + 0.034125056117773056, + 0.025707995519042015, + 0.030750175938010216, + 0.025791116058826447, + 0.023833010345697403, + 0.022833002731204033, + 0.023124972358345985, + 0.04320894367992878, + 0.027750153094530106, + 0.025541987270116806, + 0.024207867681980133, + 0.0288328155875206, + 0.025124987587332726, + 0.023416941985487938, + 0.023416010662913322, + 0.02308306284248829, + 0.02287491224706173, + 0.031542032957077026, + 0.025458168238401413, + 0.029750168323516846, + 0.025374814867973328, + 0.02737506292760372, + 0.024416018277406693, + 0.06308313459157944, + 0.026667024940252304, + 0.024582957848906517, + 0.02533290535211563, + 0.023667002096772194, + 0.02233288250863552, + 0.06812508217990398, + 0.05091610364615917, + 0.05650008097290993, + 0.06408290937542915, + 0.05233311094343662, + 0.05408283323049545, + 0.032250070944428444, + 0.03987504169344902, + 0.028125010430812836, + 0.030749943107366562, + 0.026042107492685318, + 0.024124979972839355, + 0.023791799321770668, + 0.031166942790150642, + 0.027125002816319466, + 0.026541994884610176, + 0.05691708065569401, + 0.031166011467576027, + 0.02595805563032627, + 0.02450007013976574, + 0.024042092263698578, + 0.022750115022063255, + 0.03629084676504135, + 0.03537489101290703, + 0.03379210829734802, + 0.03324984572827816, + 0.027207890525460243, + 0.026624882593750954, + 0.024999957531690598, + 0.0391670037060976, + 0.02691708505153656, + 0.027708010748028755, + 0.13458402827382088, + 0.12812507338821888, + 0.1652080100029707, + 0.12070802040398121, + 0.0749579630792141, + 0.1193750649690628, + 0.09179185144603252, + 0.07041683420538902, + 0.13583293184638023, + 0.28670812025666237, + 0.05729100666940212, + 0.2396248746663332, + 0.13449997641146183, + 0.094209099188447, + 0.04470790736377239, + 0.10362500324845314, + 0.12166681699454784, + 0.08862488903105259, + 0.13029109686613083, + 0.14120922423899174, + 0.10425015352666378, + 0.20404206588864326, + 0.1507920678704977, + 0.1793750561773777, + 0.12020906433463097, + 0.093833077698946, + 0.12454204261302948, + 0.08712499402463436, + 0.23945793509483337, + 0.054625095799565315, + 0.12616603635251522, + 0.14224997721612453, + 0.23099989630281925, + 0.12087495997548103, + 0.13691699132323265, + 0.09245797991752625, + 0.24116714484989643, + 0.10454189032316208, + 0.0719169620424509, + 0.12333318591117859, + 0.12470805086195469, + 0.12933299876749516, + 0.050625065341591835, + 0.11412519961595535, + 0.11433404870331287, + 0.0985411461442709, + 0.06591598503291607, + 0.20441622473299503, + 0.0838330015540123, + 0.13941689394414425, + 0.14395895414054394, + 0.14391704462468624, + 0.3064589109271765, + 0.13241590932011604, + 0.19091693684458733, + 0.17174985259771347, + 0.05312496796250343, + 0.03445800393819809, + 0.122416066005826, + 0.19195792265236378, + 0.11066603474318981, + 0.051042065024375916, + 0.11762487702071667, + 0.23454101756215096, + 0.08166697807610035, + 0.11987495236098766, + 0.12283283285796642, + 0.12858305126428604, + 0.134957954287529, + 0.2126670442521572, + 0.17362483777105808, + 0.4645420704036951, + 0.21754205226898193, + 0.1858340110629797, + 0.16141682863235474, + 0.2645829226821661, + 0.32229209318757057, + 0.11891708709299564, + 0.07041706703603268, + 0.4227920435369015, + 0.1277499832212925, + 0.13745902106165886, + 0.12800004333257675, + 0.1177079975605011, + 0.110250199213624, + 0.15754089690744877, + 0.25516701862215996, + 0.126624945551157, + 0.1141249667853117, + 0.08545815944671631, + 0.0399579294025898, + 0.05808286368846893, + 0.08654198609292507, + 0.06187497638165951, + 0.17604208551347256, + 0.07770908996462822, + 0.056999968364834785, + 0.04179193638265133, + 0.13120798394083977, + 0.08920906111598015, + 0.12945802882313728, + 0.08875015191733837, + 0.06483402103185654, + 0.046208035200834274, + 0.1577921211719513, + 0.15762518160045147, + 0.07841712795197964, + 0.04033301956951618, + 0.030374852940440178, + 0.09062490426003933, + 0.05520787090063095, + 0.0350000336766243, + 0.09737513028085232, + 0.14516711235046387, + 0.07179100066423416, + 0.13783411122858524, + 0.11979183182120323, + 0.13208412565290928, + 0.05254102870821953, + 0.03416696563363075, + 0.039624981582164764, + 0.049666035920381546, + 0.04058307968080044, + 0.07225014269351959, + 0.03887503407895565, + 0.03266683779656887, + 0.12791692279279232, + 0.11816597543656826, + 0.05775014869868755, + 0.042041996493935585, + 0.10970793664455414, + 0.05729217082262039, + 0.042125117033720016, + 0.0743749551475048, + 0.298250000923872, + 0.14391704462468624, + 0.15549990348517895, + 0.056625111028552055, + 0.05779205821454525, + 0.0477079302072525, + 0.032499898225069046, + 0.1119591761380434, + 0.12991693802177906, + 0.06716698408126831, + 0.0477079302072525, + 0.120542012155056, + 0.1794588752090931, + 0.0577499158680439, + 0.03216695040464401, + 0.028416980057954788, + 0.02629193477332592, + 0.042208004742860794, + 0.03495905548334122, + 0.09220908395946026, + 0.12204213999211788, + 0.06220908835530281, + 0.1330000814050436, + 0.11941604316234589, + 0.06504193879663944, + 0.049541937187314034, + 0.0539170578122139, + 0.03691692836582661, + 0.03991695120930672, + 0.040207989513874054, + 0.06741611286997795, + 0.03887503407895565, + 0.03295810893177986, + 0.03816699609160423, + 0.03145798109471798, + 0.050791073590517044, + 0.03545917570590973, + 0.04333304241299629, + 0.03191712312400341, + 0.028916867449879646, + 0.027041882276535034, + 0.025875167921185493, + 0.025207875296473503, + 0.02550007775425911, + 0.026667024940252304, + 0.026416033506393433, + 0.027582980692386627, + 0.027667032554745674, + 0.04595797508955002, + 0.03654183819890022, + 0.04650000482797623, + 0.04154094494879246, + 0.04433398135006428, + 0.06074993871152401, + 0.034041935577988625, + 0.06895815022289753, + 0.03975001163780689, + 0.030250055715441704, + 0.027999980375170708, + 0.026041874662041664, + 0.025042099878191948, + 0.024999957531690598, + 0.02500019036233425, + 0.026582973077893257, + 0.027709174901247025, + 0.04395795986056328, + 0.03774999640882015, + 0.031084055081009865, + 0.03133295103907585, + 0.029584160074591637, + 0.02624979242682457, + 0.025166897103190422, + 0.025084009394049644, + 0.02533290535211563, + 0.026833033189177513, + 0.02574990503489971, + 0.02545793540775776, + 0.0249580480158329, + 0.024834182113409042, + 0.025958986952900887, + 0.027208123356103897, + 0.02737506292760372, + 0.026708003133535385, + 0.02674991264939308, + 0.02750009298324585, + 0.026250025257468224, + 0.053999945521354675, + 0.04775007255375385, + 0.032333191484212875, + 0.0849999487400055, + 0.038708094507455826, + 0.03004097379744053, + 0.026999972760677338, + 0.02591707743704319, + 0.027082860469818115, + 0.025416025891900063, + 0.025458866730332375, + 0.04841713234782219, + 0.03091711550951004, + 0.02737506292760372, + 0.05670799873769283, + 0.031125033274292946, + 0.026833033189177513, + 0.025582965463399887, + 0.025792047381401062, + 0.025584129616618156, + 0.04054093733429909, + 0.030749943107366562, + 0.02724980004131794, + 0.027042115107178688, + 0.02637505531311035, + 0.026416964828968048, + 0.025582965463399887, + 0.026958994567394257, + 0.026041176170110703, + 0.02629193477332592, + 0.041084131225943565, + 0.04516704939305782, + 0.031250063329935074, + 0.028833048418164253, + 0.036833109334111214, + 0.028082868084311485, + 0.025999965146183968, + 0.02695806324481964, + 0.02929195761680603, + 0.025582965463399887, + 0.02587493509054184, + 0.025290995836257935, + 0.025667017325758934, + 0.02666609361767769, + 0.06862496957182884, + 0.03233388997614384, + 0.027416972443461418, + 0.0441248994320631, + 0.03529200330376625, + 0.032624928280711174, + 0.028125010430812836, + 0.02595805563032627, + 0.025250017642974854, + 0.025957822799682617, + 0.025124987587332726, + 0.024834182113409042, + 0.02537504769861698, + 0.02450007013976574, + 0.02474989742040634, + 0.028791138902306557, + 0.02845795825123787, + 0.03600004129111767, + 0.029416987672448158, + 0.027416972443461418, + 0.027499860152602196, + 0.027499860152602196, + 0.05270796827971935, + 0.03254180774092674, + 0.028458889573812485, + 0.026957830414175987, + 0.027041882276535034, + 0.026209047064185143, + 0.026958994567394257, + 0.028084032237529755, + 0.028208130970597267, + 0.027165981009602547, + 0.026291003450751305, + 0.02666679210960865, + 0.028042122721672058, + 0.026166904717683792, + 0.025750137865543365, + 0.02666609361767769, + 0.026124995201826096, + 0.026208115741610527, + 0.03200001083314419, + 0.026250025257468224, + 0.027125002816319466, + 0.026250025257468224, + 0.027416972443461418, + 0.04037492908537388, + 0.03333389759063721, + 0.028125010430812836, + 0.02704095095396042, + 0.02691708505153656, + 0.029542017728090286, + 0.0260830856859684, + 0.02550007775425911, + 0.025416957214474678, + 0.025374814867973328, + 0.025625107809901237, + 0.026042107492685318, + 0.02533290535211563, + 0.025207875296473503, + 0.025667017325758934, + 0.025624874979257584, + 0.025790883228182793, + 0.025250017642974854, + 0.024875160306692123, + 0.04091695882380009, + 0.03174995072185993, + 0.03779190592467785, + 0.03083283081650734, + 0.026708003133535385, + 0.028207898139953613, + 0.03320910036563873, + 0.0277077779173851, + 0.02637505531311035, + 0.03191595897078514, + 0.029125018045306206, + 0.025791116058826447, + 0.02804095856845379, + 0.02691592089831829, + 0.025707995519042015, + 0.03045797348022461, + 0.027084024623036385, + 0.02637505531311035, + 0.02537504769861698, + 0.027084024623036385, + 0.025416957214474678, + 0.025667017325758934, + 0.02687494270503521, + 0.047791050747036934, + 0.03200001083314419, + 0.027458183467388153, + 0.02724980004131794, + 0.026624882593750954, + 0.03975001163780689, + 0.03283307887613773, + 0.03424985334277153, + 0.02954108640551567, + 0.027708010748028755, + 0.028207898139953613, + 0.026750145480036736, + 0.026667024940252304, + 0.026166904717683792, + 0.025166897103190422, + 0.02483394928276539, + 0.024624867364764214, + 0.024791108444333076, + 0.025541987270116806, + 0.024792039766907692, + 0.024833017960190773, + 0.02516619861125946, + 0.024374807253479958, + 0.03154086880385876, + 0.038082944229245186, + 0.02937507815659046, + 0.02791592851281166, + 0.028082868084311485, + 0.02550007775425911, + 0.02945796586573124, + 0.02554105594754219, + 0.03787502646446228, + 0.029750168323516846, + 0.03416603431105614, + 0.031250063329935074, + 0.03095809370279312, + 0.0264591071754694, + 0.02783280797302723, + 0.025124987587332726, + 0.024916138499975204, + 0.024999957531690598, + 0.02458319067955017, + 0.02445909194648266, + 0.027708010748028755, + 0.025417190045118332, + 0.025792047381401062, + 0.025208108127117157, + 0.025124987587332726, + 0.02533290535211563, + 0.025082845240831375, + 0.02533290535211563, + 0.026833033189177513, + 0.025250017642974854, + 0.025499844923615456, + 0.02504093572497368, + 0.02566608600318432, + 0.025124987587332726, + 0.025624874979257584, + 0.027166912332177162, + 0.02591707743704319, + 0.02545909956097603, + 0.02491706982254982, + 0.027583912014961243, + 0.025250017642974854, + 0.03754207864403725, + 0.04591699689626694, + 0.03237486816942692, + 0.03141607157886028, + 0.027959002181887627, + 0.027166912332177162, + 0.026084017008543015, + 0.027208123356103897, + 0.03754207864403725, + 0.032084062695503235, + 0.0299159437417984, + 0.02558319829404354, + 0.02491706982254982, + 0.0249580480158329, + 0.027792062610387802, + 0.02550007775425911, + 0.02550007775425911, + 0.024458859115839005, + 0.024166889488697052, + 0.02412521280348301, + 0.024041859433054924, + 0.028167152777314186, + 0.039207981899380684, + 0.02787495031952858, + 0.028999987989664078, + 0.02487492747604847, + 0.028999987989664078, + 0.025916146114468575 + ], + "replay": { + "model": "trials/tool-reach-reach-heldout-light-recovery.model.json", + "motion": "trials/tool-reach-reach-heldout-light-recovery.motion.json" + }, + "export_seconds": 0.8837099170777947 + }, + { + "id": "tool-reach-reach-heldout-offset-baseline", + "task": "tool-reach", + "policy": "baseline", + "case": { + "id": "reach-heldout-offset", + "shoe_x": 0.725, + "shoe_y": -0.115, + "mass": 0.38, + "friction": 0.8, + "tool_length": 0.36, + "lateral_error": -0.075, + "split": "heldout" + }, + "valid": true, + "success": false, + "metrics": { + "retrieval_success": false, + "grasp_attempted": true, + "retained_lift_success": false, + "final_shoe_speed_m_s": 1.1867468292793283e-10, + "shoe_displacement_x_m": 2.2724155890330167e-08, + "final_shoe_position_m": [ + 0.7249999772758441, + -0.11500005199357714, + -0.0001077387798212695 + ], + "peak_lift_m": 0.0, + "recovery_attempts": 0, + "help_requested": false, + "peak_tool_shoe_force_n": 0.0, + "peak_tool_shoe_force_time_s": 0.0, + "tool_shoe_impulse_ns": 0.0, + "tool_shoe_contact_ticks": 0, + "physics_timestep_s": 0.002, + "policy_interval_s": 0.02, + "max_joint_command_delta_rad": 0.0030000000000001137, + "max_tracking_error_m": 0.1317299890075362, + "simulation_seconds": 5.399999999999627, + "wall_seconds": 0.2863289578817785, + "solver_warnings": 0, + "native_steps": 2700, + "shoe_external_force_used": false, + "shoe_equality_constraints": 0, + "recovery_count": 0, + "intervention_count": 0, + "peak_contact_force_n": 0.0, + "contact_force_scope": "sum of normal shoe-to-robot/tool forces, excluding table", + "force_peak_by_phase_n": { + "settle": 0.0, + "direct_reach": 0.0, + "direct_close": 0.0, + "direct_lift": 0.0 + }, + "policy_compute_p50_ms": 0.023625092580914497, + "policy_compute_p95_ms": 0.05440639797598123, + "policy_compute_max_ms": 0.43308292515575886, + "wall_includes_model_compile": true, + "recorded_state_scope": "privileged native state; qpos has 6 arm radians, 2 jaw metres, shoe XYZ metres and quaternion wxyz; qvel has 6 arm rad/s, 2 jaw m/s, shoe linear m/s and angular rad/s; controls are 6 joint radians plus jaw metres; requested targets update every20ms and issued controls are rate limited every2ms", + "retention_criterion": "shoe bottom >35 mm with both fingers contacting, tool and world force each <0.01 N for final 500 ms", + "no_tool_baseline": true, + "tool_pre_equipped": false, + "outcome": "failed_direct_reach", + "real_time_factor": 18.85942672354229 + }, + "events": [ + { + "t": 0.0, + "type": "assumptions", + "message": "assumptions", + "pre_equipped_rigid_tool": false, + "privileged_observations": true, + "shoe_attachment": false, + "controller_reach_limit_x_m": 0.54, + "tool_acquisition_tested": false + }, + { + "t": 0.0, + "type": "phase", + "message": "settle", + "name": "settle", + "target": [ + 0.36, + -0.06, + 0.27 + ] + }, + { + "t": 0.4, + "type": "direct_reach_attempt", + "message": "direct reach attempt", + "desired_x_m": 0.7249999772540483, + "clipped_x_m": 0.54 + }, + { + "t": 0.4, + "type": "phase", + "message": "direct reach", + "name": "direct_reach", + "target": [ + 0.54, + -0.115, + 0.075 + ] + }, + { + "t": 2.9, + "type": "phase", + "message": "direct close", + "name": "direct_close", + "target": [ + 0.54, + -0.115, + 0.075 + ] + }, + { + "t": 3.9, + "type": "phase", + "message": "direct lift", + "name": "direct_lift", + "target": [ + 0.5, + -0.115, + 0.2 + ] + }, + { + "t": 5.4, + "type": "direct_reach_failed", + "message": "direct reach failed", + "shoe_x_m": 0.7249999772758441 + } + ], + "errors": [], + "wall_seconds": 0.2875982499681413, + "native_trace_columns": [ + "t_s", + "tool_shoe_force_n", + "shoe_robot_force_n", + "left_finger_force_n", + "right_finger_force_n", + "shoe_x_m", + "shoe_y_m", + "shoe_z_m", + "world_shoe_force_n" + ], + "control_compute_ms": [ + 0.0296661164611578, + 0.04158401861786842, + 0.03258395008742809, + 0.06599980406463146, + 0.044665997847914696, + 0.038499943912029266, + 0.037250109016895294, + 0.0477079302072525, + 0.04591699689626694, + 0.05450006574392319, + 0.07400009781122208, + 0.07212487980723381, + 0.05429191514849663, + 0.05408399738371372, + 0.05474989302456379, + 0.060042133554816246, + 0.03441702574491501, + 0.027416972443461418, + 0.025042099878191948, + 0.024707987904548645, + 0.02537504769861698, + 0.02895807847380638, + 0.09816605597734451, + 0.026667024940252304, + 0.03400002606213093, + 0.03462517634034157, + 0.02595805563032627, + 0.02445792779326439, + 0.02454221248626709, + 0.024084001779556274, + 0.023208092898130417, + 0.02229190431535244, + 0.025541987270116806, + 0.03087497316300869, + 0.021750107407569885, + 0.02979184500873089, + 0.045082997530698776, + 0.03108312375843525, + 0.027875183150172234, + 0.025916146114468575, + 0.024833017960190773, + 0.025042099878191948, + 0.023833010345697403, + 0.024042092263698578, + 0.024541979655623436, + 0.023540807887911797, + 0.022416934370994568, + 0.022209016606211662, + 0.022208085283637047, + 0.021999934688210487, + 0.02174987457692623, + 0.0213750172406435, + 0.021790852770209312, + 0.021792016923427582, + 0.021666986867785454, + 0.022167107090353966, + 0.022582942619919777, + 0.022167107090353966, + 0.02150004729628563, + 0.023875152692198753, + 0.05124998278915882, + 0.03320886753499508, + 0.025792047381401062, + 0.024166889488697052, + 0.023499829694628716, + 0.022999942302703857, + 0.022416003048419952, + 0.022416003048419952, + 0.022165942937135696, + 0.43308292515575886, + 0.022540800273418427, + 0.021666986867785454, + 0.02154218964278698, + 0.021416926756501198, + 0.02133403904736042, + 0.021458137780427933, + 0.021084211766719818, + 0.021666986867785454, + 0.021290965378284454, + 0.021166866645216942, + 0.021624844521284103, + 0.021416926756501198, + 0.02308306284248829, + 0.02400018274784088, + 0.026584137231111526, + 0.026124995201826096, + 0.026791822165250778, + 0.023083994165062904, + 0.03258301876485348, + 0.025999965146183968, + 0.024582957848906517, + 0.024250010028481483, + 0.024250010028481483, + 0.022290972992777824, + 0.02195802517235279, + 0.021666986867785454, + 0.021792016923427582, + 0.02187490463256836, + 0.02166605554521084, + 0.06029196083545685, + 0.02587493509054184, + 0.023333122953772545, + 0.022249994799494743, + 0.02195918932557106, + 0.025292159989476204, + 0.0213750172406435, + 0.021415995433926582, + 0.021541956812143326, + 0.021292129531502724, + 0.02166605554521084, + 0.021792016923427582, + 0.021625077351927757, + 0.04287506453692913, + 0.0299159437417984, + 0.02629193477332592, + 0.025624874979257584, + 0.024750130251049995, + 0.02337503246963024, + 0.022707972675561905, + 0.022209016606211662, + 0.022124964743852615, + 0.02195802517235279, + 0.02191704697906971, + 0.021249987185001373, + 0.022208085283637047, + 0.022333115339279175, + 0.021584099158644676, + 0.021999934688210487, + 0.022416934370994568, + 0.02408307045698166, + 0.028165988624095917, + 0.03133388236165047, + 0.02650008536875248, + 0.024667009711265564, + 0.024541979655623436, + 0.023625092580914497, + 0.02345908433198929, + 0.02345908433198929, + 0.023041851818561554, + 0.028749927878379822, + 0.023916829377412796, + 0.028957845643162727, + 0.02487492747604847, + 0.02258317545056343, + 0.022416934370994568, + 0.024207867681980133, + 0.023499829694628716, + 0.02195802517235279, + 0.02216617576777935, + 0.02187490463256836, + 0.021249987185001373, + 0.02129189670085907, + 0.021249987185001373, + 0.021209008991718292, + 0.02466607838869095, + 0.02133403904736042, + 0.021415995433926582, + 0.021459069103002548, + 0.021624844521284103, + 0.0213750172406435, + 0.021750107407569885, + 0.02170889638364315, + 0.022209016606211662, + 0.027708010748028755, + 0.02374988980591297, + 0.022333813831210136, + 0.0227498821914196, + 0.022207852452993393, + 0.02345908433198929, + 0.02329191192984581, + 0.02287491224706173, + 0.02270820550620556, + 0.021625077351927757, + 0.022208085283637047, + 0.18812506459653378, + 0.033125048503279686, + 0.02374988980591297, + 0.055958982557058334, + 0.026708003133535385, + 0.027165981009602547, + 0.02850010059773922, + 0.02829195000231266, + 0.06308313459157944, + 0.02641580067574978, + 0.021750107407569885, + 0.022209016606211662, + 0.021625077351927757, + 0.022082822397351265, + 0.021750107407569885, + 0.021541956812143326, + 0.022292137145996094, + 0.02133287489414215, + 0.02170819789171219, + 0.02174987457692623, + 0.021416926756501198, + 0.023875152692198753, + 0.022417167201638222, + 0.0227498821914196, + 0.02312520518898964, + 0.02291705459356308, + 0.024208100512623787, + 0.02750009298324585, + 0.02537504769861698, + 0.025124987587332726, + 0.02474989742040634, + 0.027041882276535034, + 0.024958979338407516, + 0.024374807253479958, + 0.02450007013976574, + 0.030458206310868263, + 0.02533290535211563, + 0.022792024537920952, + 0.022624852135777473, + 0.02808310091495514, + 0.025416025891900063, + 0.028167152777314186, + 0.05566701292991638, + 0.04008319228887558, + 0.03133295103907585, + 0.03124983049929142, + 0.03658398054540157, + 0.032125040888786316, + 0.0302919652312994, + 0.029999995604157448, + 0.02695806324481964, + 0.02774992026388645, + 0.02587493509054184, + 0.0599580816924572, + 0.028583919629454613, + 0.026458874344825745, + 0.025750137865543365, + 0.02687494270503521, + 0.02674991264939308, + 0.030167168006300926, + 0.026416964828968048, + 0.026333844289183617, + 0.025957822799682617, + 0.026207882910966873, + 0.032916897907853127, + 0.02520880661904812, + 0.024250010028481483, + 0.023707980290055275, + 0.02304092049598694, + 0.023167114704847336, + 0.023167114704847336, + 0.02354104071855545, + 0.023209024220705032, + 0.023458153009414673, + 0.03520818427205086, + 0.032708048820495605, + 0.026833033189177513, + 0.02333289012312889, + 0.021875137463212013, + 0.02237502485513687, + 0.02266606315970421, + 0.022666994482278824, + 0.022124964743852615, + 0.02154102548956871, + 0.021416926756501198, + 0.02445792779326439, + 0.021167099475860596, + 0.02154218964278698, + 0.023041153326630592, + 0.023042084649205208, + 0.023458851501345634, + 0.023250002413988113, + 0.022792024537920952, + 0.02283393405377865, + 0.023208092898130417, + 0.023625092580914497 + ], + "replay": { + "model": "trials/tool-reach-reach-heldout-offset-baseline.model.json", + "motion": "trials/tool-reach-reach-heldout-offset-baseline.motion.json" + }, + "export_seconds": 0.8120468340348452 + }, + { + "id": "tool-reach-reach-heldout-offset-recovery", + "task": "tool-reach", + "policy": "recovery", + "case": { + "id": "reach-heldout-offset", + "shoe_x": 0.725, + "shoe_y": -0.115, + "mass": 0.38, + "friction": 0.8, + "tool_length": 0.36, + "lateral_error": -0.075, + "split": "heldout" + }, + "valid": true, + "success": false, + "metrics": { + "retrieval_success": true, + "grasp_attempted": true, + "retained_lift_success": false, + "final_shoe_speed_m_s": 9.419111885078495e-12, + "shoe_displacement_x_m": 0.1625735729126947, + "final_shoe_position_m": [ + 0.5624264270873053, + -0.07295874733728529, + -0.00010773877981951383 + ], + "peak_lift_m": 0.0, + "recovery_attempts": 0, + "help_requested": true, + "peak_tool_shoe_force_n": 26.97259819786203, + "peak_tool_shoe_force_time_s": 3.0799999999998824, + "tool_shoe_impulse_ns": 5.698611326146804, + "tool_shoe_contact_ticks": 1053, + "physics_timestep_s": 0.002, + "policy_interval_s": 0.02, + "max_joint_command_delta_rad": 0.0030000000000001137, + "max_tracking_error_m": 0.19931044737155243, + "simulation_seconds": 12.600000000000877, + "wall_seconds": 0.5486553329974413, + "solver_warnings": 0, + "native_steps": 6300, + "shoe_external_force_used": false, + "shoe_equality_constraints": 0, + "recovery_count": 0, + "intervention_count": 1, + "peak_contact_force_n": 26.97259819786203, + "contact_force_scope": "sum of normal shoe-to-robot/tool forces, excluding table", + "force_peak_by_phase_n": { + "settle": 0.0, + "approach_tool": 0.0, + "lower_tool": 26.97259819786203, + "pull_shoe": 5.0732546522941755, + "verify_pull": 0.0, + "clear_rake": 7.3752520434051085, + "grasp_approach": 20.910415415883666, + "close_jaws": 19.537286406285634, + "lift": 18.20200202910332 + }, + "policy_compute_p50_ms": 0.024792039766907692, + "policy_compute_p95_ms": 0.03759391838684671, + "policy_compute_max_ms": 0.14925003051757812, + "wall_includes_model_compile": true, + "recorded_state_scope": "privileged native state; qpos has 6 arm radians, 2 jaw metres, shoe XYZ metres and quaternion wxyz; qvel has 6 arm rad/s, 2 jaw m/s, shoe linear m/s and angular rad/s; controls are 6 joint radians plus jaw metres; requested targets update every20ms and issued controls are rate limited every2ms", + "retention_criterion": "shoe bottom >35 mm with both fingers contacting, tool and world force each <0.01 N for final 500 ms", + "no_tool_baseline": false, + "tool_pre_equipped": true, + "outcome": "retrieved_lift_failed", + "real_time_factor": 22.965237449099284 + }, + "events": [ + { + "t": 0.0, + "type": "assumptions", + "message": "assumptions", + "pre_equipped_rigid_tool": true, + "privileged_observations": true, + "shoe_attachment": false, + "controller_reach_limit_x_m": 0.54, + "tool_acquisition_tested": false + }, + { + "t": 0.0, + "type": "phase", + "message": "settle", + "name": "settle", + "target": [ + 0.36, + -0.06, + 0.27 + ] + }, + { + "t": 0.4, + "type": "phase", + "message": "approach tool", + "name": "approach_tool", + "target": [ + 0.5299999772540483, + -0.1900000518699826, + 0.25 + ] + }, + { + "t": 2.2, + "type": "phase", + "message": "lower tool", + "name": "lower_tool", + "target": [ + 0.5299999772540483, + -0.1900000518699826, + 0.075 + ] + }, + { + "t": 3.2, + "type": "phase", + "message": "pull shoe", + "name": "pull_shoe", + "target": [ + 0.2, + -0.1900000518699826, + 0.075 + ] + }, + { + "t": 6.2, + "type": "phase", + "message": "verify pull", + "name": "verify_pull", + "target": [ + 0.2, + -0.1900000518699826, + 0.075 + ] + }, + { + "t": 6.6, + "type": "retrieval_check", + "message": "retrieval check", + "attempt": 1, + "retrieved": true, + "shoe_x_m": 0.5297153359629598, + "displacement_m": 0.19528466403704015 + }, + { + "t": 6.6, + "type": "phase", + "message": "clear rake", + "name": "clear_rake", + "target": [ + 0.24, + -0.115, + 0.25 + ] + }, + { + "t": 7.8, + "type": "phase", + "message": "grasp approach", + "name": "grasp_approach", + "target": [ + 0.4927601993423259, + -0.07553697238250397, + 0.06 + ] + }, + { + "t": 9.6, + "type": "phase", + "message": "close jaws", + "name": "close_jaws", + "target": [ + 0.4927601993423259, + -0.07553697238250397, + 0.06 + ] + }, + { + "t": 10.6, + "type": "phase", + "message": "lift", + "name": "lift", + "target": [ + 0.4927601993423259, + -0.07553697238250397, + 0.28 + ] + }, + { + "t": 12.6, + "type": "lift_check", + "message": "lift check", + "retained": false, + "shoe_bottom_z_m": -0.00010773877981951383 + }, + { + "t": 12.6, + "type": "help_requested", + "message": "retrieved but jaw lift not retained", + "reason": "retrieved_but_jaw_lift_not_retained" + } + ], + "errors": [], + "wall_seconds": 0.5493228749837726, + "native_trace_columns": [ + "t_s", + "tool_shoe_force_n", + "shoe_robot_force_n", + "left_finger_force_n", + "right_finger_force_n", + "shoe_x_m", + "shoe_y_m", + "shoe_z_m", + "world_shoe_force_n" + ], + "control_compute_ms": [ + 0.02654106356203556, + 0.029416056349873543, + 0.025625107809901237, + 0.05012517794966698, + 0.044082989916205406, + 0.029749935492873192, + 0.02750009298324585, + 0.026167137548327446, + 0.02695806324481964, + 0.025165965780615807, + 0.024416949599981308, + 0.024084001779556274, + 0.02570892684161663, + 0.02474989742040634, + 0.02554105594754219, + 0.026416033506393433, + 0.02629193477332592, + 0.025290995836257935, + 0.026166904717683792, + 0.0264591071754694, + 0.034125056117773056, + 0.030750175938010216, + 0.03612483851611614, + 0.0463330652564764, + 0.03179116174578667, + 0.04187482409179211, + 0.04283292219042778, + 0.03174995072185993, + 0.02691708505153656, + 0.025999965146183968, + 0.02587493509054184, + 0.027333851903676987, + 0.024416949599981308, + 0.02437504008412361, + 0.022791093215346336, + 0.02283393405377865, + 0.029999995604157448, + 0.029749935492873192, + 0.026999972760677338, + 0.045459019020199776, + 0.032916897907853127, + 0.026541994884610176, + 0.024208100512623787, + 0.02304092049598694, + 0.0719588715583086, + 0.029042130336165428, + 0.02691592089831829, + 0.02595805563032627, + 0.02574990503489971, + 0.02491590566933155, + 0.02529192715883255, + 0.024458859115839005, + 0.025041867047548294, + 0.02574990503489971, + 0.026583904400467873, + 0.024667009711265564, + 0.03474997356534004, + 0.02750009298324585, + 0.025582965463399887, + 0.02487492747604847, + 0.0238749198615551, + 0.02979184500873089, + 0.024958979338407516, + 0.02774992026388645, + 0.02391706220805645, + 0.023250002413988113, + 0.022999942302703857, + 0.04816683940589428, + 0.0310409814119339, + 0.034833094105124474, + 0.034207943826913834, + 0.027916161343455315, + 0.025792047381401062, + 0.02674991264939308, + 0.02545909956097603, + 0.024250010028481483, + 0.025624874979257584, + 0.025290995836257935, + 0.02429191954433918, + 0.024624867364764214, + 0.024250010028481483, + 0.025833025574684143, + 0.025124987587332726, + 0.024709152057766914, + 0.02408307045698166, + 0.02491590566933155, + 0.02466607838869095, + 0.02550007775425911, + 0.025625107809901237, + 0.026208115741610527, + 0.026166904717683792, + 0.026084017008543015, + 0.028542010113596916, + 0.029708025977015495, + 0.027999980375170708, + 0.03137486055493355, + 0.05587493069469929, + 0.033207936212420464, + 0.033708056434988976, + 0.02704095095396042, + 0.026834197342395782, + 0.02554105594754219, + 0.026708003133535385, + 0.026541994884610176, + 0.02666609361767769, + 0.03533298149704933, + 0.02937507815659046, + 0.02683396451175213, + 0.03837491385638714, + 0.038250116631388664, + 0.04512513987720013, + 0.034624943509697914, + 0.028665876016020775, + 0.03420887514948845, + 0.028833048418164253, + 0.027167145162820816, + 0.0399579294025898, + 0.029082875698804855, + 0.026667024940252304, + 0.02583395689725876, + 0.025250017642974854, + 0.024750130251049995, + 0.025042099878191948, + 0.024667009711265564, + 0.025499844923615456, + 0.023957807570695877, + 0.023958971723914146, + 0.024416949599981308, + 0.025290995836257935, + 0.02533290535211563, + 0.023999949917197227, + 0.03558304160833359, + 0.02670893445611, + 0.025416957214474678, + 0.025250017642974854, + 0.02429191954433918, + 0.023916130885481834, + 0.024250010028481483, + 0.025167129933834076, + 0.024625100195407867, + 0.04495796747505665, + 0.03033294342458248, + 0.03954209387302399, + 0.02845795825123787, + 0.028082868084311485, + 0.026875175535678864, + 0.025541987270116806, + 0.025416957214474678, + 0.02491706982254982, + 0.024374807253479958, + 0.023750122636556625, + 0.02445792779326439, + 0.024625100195407867, + 0.024167122319340706, + 0.02533290535211563, + 0.0249580480158329, + 0.023540807887911797, + 0.02354104071855545, + 0.024333130568265915, + 0.02412521280348301, + 0.03904104232788086, + 0.02808310091495514, + 0.025791116058826447, + 0.03541703335940838, + 0.030125025659799576, + 0.033333199098706245, + 0.04487507976591587, + 0.031125033274292946, + 0.026999972760677338, + 0.025957822799682617, + 0.024999957531690598, + 0.025499844923615456, + 0.024916836991906166, + 0.024791108444333076, + 0.02450007013976574, + 0.024416949599981308, + 0.041791005060076714, + 0.030624913051724434, + 0.02737506292760372, + 0.026625115424394608, + 0.025916844606399536, + 0.024707987904548645, + 0.024167122319340706, + 0.024290988221764565, + 0.02383394166827202, + 0.024124979972839355, + 0.023999949917197227, + 0.024333130568265915, + 0.025250017642974854, + 0.04700012505054474, + 0.0288328155875206, + 0.025707995519042015, + 0.024957815185189247, + 0.044082989916205406, + 0.036624958738684654, + 0.02895807847380638, + 0.026250025257468224, + 0.02474989742040634, + 0.02391706220805645, + 0.024958979338407516, + 0.02404092811048031, + 0.02445909194648266, + 0.0238749198615551, + 0.026208115741610527, + 0.023582950234413147, + 0.023209024220705032, + 0.023250002413988113, + 0.023833010345697403, + 0.023207860067486763, + 0.02550007775425911, + 0.02408307045698166, + 0.038250116631388664, + 0.028125010430812836, + 0.02650008536875248, + 0.026208115741610527, + 0.025124987587332726, + 0.02629193477332592, + 0.02333289012312889, + 0.02350006252527237, + 0.04795915447175503, + 0.031207920983433723, + 0.027084024623036385, + 0.025290995836257935, + 0.02450007013976574, + 0.024084001779556274, + 0.025165965780615807, + 0.02491590566933155, + 0.024709152057766914, + 0.0249580480158329, + 0.024458859115839005, + 0.024916138499975204, + 0.025667017325758934, + 0.024667009711265564, + 0.02474989742040634, + 0.02500019036233425, + 0.024791108444333076, + 0.024250010028481483, + 0.024667009711265564, + 0.025165965780615807, + 0.025207875296473503, + 0.02650008536875248, + 0.02466607838869095, + 0.024250010028481483, + 0.028665876016020775, + 0.038499943912029266, + 0.028166919946670532, + 0.02687494270503521, + 0.023292144760489464, + 0.023207860067486763, + 0.022208085283637047, + 0.025250017642974854, + 0.025583896785974503, + 0.022584106773138046, + 0.025582965463399887, + 0.025042099878191948, + 0.04175002686679363, + 0.0300002284348011, + 0.027165981009602547, + 0.026541994884610176, + 0.025792047381401062, + 0.025458168238401413, + 0.04612491466104984, + 0.03404100425541401, + 0.027583912014961243, + 0.026750145480036736, + 0.026250025257468224, + 0.025124987587332726, + 0.024792039766907692, + 0.03474997356534004, + 0.026625115424394608, + 0.02500019036233425, + 0.02245791256427765, + 0.022416934370994568, + 0.02229190431535244, + 0.02170819789171219, + 0.022208085283637047, + 0.021750107407569885, + 0.021707965061068535, + 0.024333130568265915, + 0.02474989742040634, + 0.026916852220892906, + 0.021916814148426056, + 0.025250017642974854, + 0.025875167921185493, + 0.02466607838869095, + 0.024124979972839355, + 0.023582950234413147, + 0.024999957531690598, + 0.02458319067955017, + 0.027125002816319466, + 0.02437504008412361, + 0.024582957848906517, + 0.032250070944428444, + 0.026790890842676163, + 0.025791814550757408, + 0.02450007013976574, + 0.027165981009602547, + 0.023916829377412796, + 0.023834174498915672, + 0.024582957848906517, + 0.025041867047548294, + 0.024792039766907692, + 0.023750122636556625, + 0.02408307045698166, + 0.026041874662041664, + 0.02900022082030773, + 0.02533290535211563, + 0.027999980375170708, + 0.025124987587332726, + 0.025416957214474678, + 0.025499844923615456, + 0.027667032554745674, + 0.0252497848123312, + 0.03287498839199543, + 0.02737506292760372, + 0.025709159672260284, + 0.028084032237529755, + 0.024624867364764214, + 0.026958994567394257, + 0.024792039766907692, + 0.026665860787034035, + 0.02445792779326439, + 0.025207875296473503, + 0.025207875296473503, + 0.02474989742040634, + 0.026291003450751305, + 0.02437504008412361, + 0.023958971723914146, + 0.02437504008412361, + 0.02383394166827202, + 0.02787495031952858, + 0.026625115424394608, + 0.024416018277406693, + 0.04287506453692913, + 0.030374852940440178, + 0.026750145480036736, + 0.02687494270503521, + 0.024041859433054924, + 0.02391589805483818, + 0.026625115424394608, + 0.023999949917197227, + 0.02354104071855545, + 0.022707972675561905, + 0.022750115022063255, + 0.022833002731204033, + 0.0249580480158329, + 0.024707987904548645, + 0.0247082207351923, + 0.024791806936264038, + 0.024625100195407867, + 0.028042122721672058, + 0.02737506292760372, + 0.048833899199962616, + 0.024582957848906517, + 0.02450007013976574, + 0.023875152692198753, + 0.024042092263698578, + 0.024124979972839355, + 0.03645801916718483, + 0.028250040486454964, + 0.025999965146183968, + 0.025916844606399536, + 0.025625107809901237, + 0.02474989742040634, + 0.024582957848906517, + 0.024417182430624962, + 0.024166889488697052, + 0.022124964743852615, + 0.023707980290055275, + 0.02229190431535244, + 0.02200016751885414, + 0.021875137463212013, + 0.021916814148426056, + 0.027957838028669357, + 0.02266606315970421, + 0.02195802517235279, + 0.022041844204068184, + 0.027959002181887627, + 0.025625107809901237, + 0.03316695801913738, + 0.02504093572497368, + 0.024499837309122086, + 0.025124987587332726, + 0.025999965146183968, + 0.024541979655623436, + 0.024624867364764214, + 0.024416949599981308, + 0.023834174498915672, + 0.02383394166827202, + 0.02350006252527237, + 0.02566608600318432, + 0.023875152692198753, + 0.02291705459356308, + 0.022790860384702682, + 0.024875160306692123, + 0.02345792017877102, + 0.02333289012312889, + 0.023124972358345985, + 0.023208092898130417, + 0.022625084966421127, + 0.023166881874203682, + 0.023083994165062904, + 0.023458153009414673, + 0.0252497848123312, + 0.023750122636556625, + 0.03483402542769909, + 0.027542002499103546, + 0.025084009394049644, + 0.02487492747604847, + 0.023792032152414322, + 0.024041859433054924, + 0.024167122319340706, + 0.023707980290055275, + 0.02550007775425911, + 0.024207867681980133, + 0.03258301876485348, + 0.025999965146183968, + 0.02700020559132099, + 0.024750130251049995, + 0.024209031835198402, + 0.02383394166827202, + 0.024124979972839355, + 0.02333289012312889, + 0.02287491224706173, + 0.02366607077419758, + 0.023209024220705032, + 0.023499829694628716, + 0.05454104393720627, + 0.03245798870921135, + 0.027082860469818115, + 0.025165965780615807, + 0.024250010028481483, + 0.024165958166122437, + 0.023792032152414322, + 0.023792032152414322, + 0.022290972992777824, + 0.022333115339279175, + 0.022166874259710312, + 0.022249994799494743, + 0.022124964743852615, + 0.02312520518898964, + 0.02195802517235279, + 0.021999934688210487, + 0.022124964743852615, + 0.14925003051757812, + 0.025165965780615807, + 0.024499837309122086, + 0.024209031835198402, + 0.023875152692198753, + 0.023707980290055275, + 0.033250078558921814, + 0.027625123038887978, + 0.030792085453867912, + 0.02645794302225113, + 0.025124987587332726, + 0.036250101402401924, + 0.027582980692386627, + 0.024250010028481483, + 0.022666994482278824, + 0.02258317545056343, + 0.022166874259710312, + 0.022666994482278824, + 0.022999942302703857, + 0.02245791256427765, + 0.021792016923427582, + 0.022292137145996094, + 0.025124987587332726, + 0.025582965463399887, + 0.02774992026388645, + 0.025209039449691772, + 0.03658304922282696, + 0.02591591328382492, + 0.025124987587332726, + 0.022082822397351265, + 0.021792016923427582, + 0.021665822714567184, + 0.02145790494978428, + 0.021583866328001022, + 0.021832995116710663, + 0.021541956812143326, + 0.03091595135629177, + 0.026499852538108826, + 0.024707987904548645, + 0.02537504769861698, + 0.02533290535211563, + 0.038999831303954124, + 0.02937507815659046, + 0.026708003133535385, + 0.025833025574684143, + 0.022666994482278824, + 0.02374988980591297, + 0.023041153326630592, + 0.02350006252527237, + 0.022625084966421127, + 0.023083994165062904, + 0.023750122636556625, + 0.022249994799494743, + 0.022165942937135696, + 0.024584122002124786, + 0.024417182430624962, + 0.024250010028481483, + 0.024208100512623787, + 0.02470891922712326, + 0.024833017960190773, + 0.024624867364764214, + 0.024707987904548645, + 0.033708056434988976, + 0.02491706982254982, + 0.02437504008412361, + 0.02395804040133953, + 0.023416941985487938, + 0.023625092580914497, + 0.02291589044034481, + 0.02350006252527237, + 0.02291705459356308, + 0.023042084649205208, + 0.02304092049598694, + 0.026541994884610176, + 0.022625084966421127, + 0.023167114704847336, + 0.02654106356203556, + 0.023416941985487938, + 0.032624928280711174, + 0.026499852538108826, + 0.02483394928276539, + 0.0249580480158329, + 0.023833010345697403, + 0.022041145712137222, + 0.022249994799494743, + 0.02191588282585144, + 0.022249994799494743, + 0.022625084966421127, + 0.021792016923427582, + 0.021333806216716766, + 0.022167107090353966, + 0.021999934688210487, + 0.022082822397351265, + 0.024541979655623436, + 0.025124987587332726, + 0.02445909194648266, + 0.024416949599981308, + 0.02454104833304882, + 0.026208115741610527, + 0.024792039766907692, + 0.024750130251049995, + 0.024250010028481483, + 0.03679189831018448, + 0.02691592089831829, + 0.02537504769861698, + 0.024792039766907692, + 0.02554105594754219, + 0.024999957531690598, + 0.024792039766907692, + 0.02454221248626709, + 0.024499837309122086, + 0.024167122319340706, + 0.024667009711265564, + 0.022292137145996094, + 0.02191588282585144, + 0.02187490463256836, + 0.02170819789171219, + 0.021750107407569885, + 0.021541956812143326, + 0.038416823372244835, + 0.027499860152602196, + 0.02450007013976574, + 0.02337503246963024, + 0.023207860067486763, + 0.022833002731204033, + 0.022750115022063255, + 0.02245907671749592, + 0.022833002731204033, + 0.022416934370994568, + 0.022707972675561905, + 0.022042077034711838, + 0.022499822080135345, + 0.02183392643928528, + 0.021792016923427582, + 0.02474989742040634, + 0.022750115022063255, + 0.022166874259710312, + 0.02195802517235279, + 0.021582935005426407, + 0.022208085283637047, + 0.022165942937135696, + 0.021834159269928932, + 0.021792016923427582, + 0.029749935492873192, + 0.028416048735380173, + 0.025541987270116806, + 0.05491706542670727, + 0.032250070944428444, + 0.023165950551629066, + 0.022290972992777824, + 0.024290988221764565, + 0.021999934688210487, + 0.021208077669143677, + 0.021249987185001373, + 0.021249987185001373, + 0.021167099475860596, + 0.0213750172406435, + 0.02183392643928528, + 0.0213750172406435, + 0.021249987185001373, + 0.023999949917197227, + 0.025499844923615456, + 0.024791108444333076, + 0.024458160623908043, + 0.02450007013976574, + 0.024084001779556274, + 0.024208100512623787, + 0.024250010028481483, + 0.02437504008412361, + 0.027167145162820816, + 0.024208100512623787, + 0.02754107117652893, + 0.03595906309783459, + 0.027916859835386276, + 0.026416964828968048, + 0.0260830856859684, + 0.0253340695053339, + 0.02474989742040634, + 0.024916836991906166, + 0.02433289773762226, + 0.024124979972839355, + 0.02170819789171219, + 0.02191704697906971, + 0.0213750172406435, + 0.021416926756501198, + 0.024624867364764214 + ], + "replay": { + "model": "trials/tool-reach-reach-heldout-offset-recovery.model.json", + "motion": "trials/tool-reach-reach-heldout-offset-recovery.motion.json" + }, + "export_seconds": 0.8266389579512179 + }, + { + "id": "tool-reach-reach-heldout-heavy-baseline", + "task": "tool-reach", + "policy": "baseline", + "case": { + "id": "reach-heldout-heavy", + "shoe_x": 0.735, + "shoe_y": -0.075, + "mass": 0.55, + "friction": 1.05, + "tool_length": 0.37, + "lateral_error": 0.035, + "split": "heldout" + }, + "valid": true, + "success": false, + "metrics": { + "retrieval_success": false, + "grasp_attempted": true, + "retained_lift_success": false, + "final_shoe_speed_m_s": 8.565574870044419e-12, + "shoe_displacement_x_m": 3.230177891833108e-08, + "final_shoe_position_m": [ + 0.7349999676982211, + -0.07500005201238114, + -0.00010785740843995813 + ], + "peak_lift_m": 0.0, + "recovery_attempts": 0, + "help_requested": false, + "peak_tool_shoe_force_n": 0.0, + "peak_tool_shoe_force_time_s": 0.0, + "tool_shoe_impulse_ns": 0.0, + "tool_shoe_contact_ticks": 0, + "physics_timestep_s": 0.002, + "policy_interval_s": 0.02, + "max_joint_command_delta_rad": 0.0030000000000001137, + "max_tracking_error_m": 0.13178454779095133, + "simulation_seconds": 5.399999999999627, + "wall_seconds": 0.2887754589319229, + "solver_warnings": 0, + "native_steps": 2700, + "shoe_external_force_used": false, + "shoe_equality_constraints": 0, + "recovery_count": 0, + "intervention_count": 0, + "peak_contact_force_n": 0.0, + "contact_force_scope": "sum of normal shoe-to-robot/tool forces, excluding table", + "force_peak_by_phase_n": { + "settle": 0.0, + "direct_reach": 0.0, + "direct_close": 0.0, + "direct_lift": 0.0 + }, + "policy_compute_p50_ms": 0.023875036276876926, + "policy_compute_p95_ms": 0.04371682880446315, + "policy_compute_max_ms": 0.8271248079836369, + "wall_includes_model_compile": true, + "recorded_state_scope": "privileged native state; qpos has 6 arm radians, 2 jaw metres, shoe XYZ metres and quaternion wxyz; qvel has 6 arm rad/s, 2 jaw m/s, shoe linear m/s and angular rad/s; controls are 6 joint radians plus jaw metres; requested targets update every20ms and issued controls are rate limited every2ms", + "retention_criterion": "shoe bottom >35 mm with both fingers contacting, tool and world force each <0.01 N for final 500 ms", + "no_tool_baseline": true, + "tool_pre_equipped": false, + "outcome": "failed_direct_reach", + "real_time_factor": 18.699649963235434 + }, + "events": [ + { + "t": 0.0, + "type": "assumptions", + "message": "assumptions", + "pre_equipped_rigid_tool": false, + "privileged_observations": true, + "shoe_attachment": false, + "controller_reach_limit_x_m": 0.54, + "tool_acquisition_tested": false + }, + { + "t": 0.0, + "type": "phase", + "message": "settle", + "name": "settle", + "target": [ + 0.36, + -0.06, + 0.27 + ] + }, + { + "t": 0.4, + "type": "direct_reach_attempt", + "message": "direct reach attempt", + "desired_x_m": 0.7349999676794002, + "clipped_x_m": 0.54 + }, + { + "t": 0.4, + "type": "phase", + "message": "direct reach", + "name": "direct_reach", + "target": [ + 0.54, + -0.075, + 0.075 + ] + }, + { + "t": 2.9, + "type": "phase", + "message": "direct close", + "name": "direct_close", + "target": [ + 0.54, + -0.075, + 0.075 + ] + }, + { + "t": 3.9, + "type": "phase", + "message": "direct lift", + "name": "direct_lift", + "target": [ + 0.5, + -0.075, + 0.2 + ] + }, + { + "t": 5.4, + "type": "direct_reach_failed", + "message": "direct reach failed", + "shoe_x_m": 0.7349999676982211 + } + ], + "errors": [], + "wall_seconds": 0.2901710420846939, + "native_trace_columns": [ + "t_s", + "tool_shoe_force_n", + "shoe_robot_force_n", + "left_finger_force_n", + "right_finger_force_n", + "shoe_x_m", + "shoe_y_m", + "shoe_z_m", + "world_shoe_force_n" + ], + "control_compute_ms": [ + 0.022124964743852615, + 0.02687494270503521, + 0.022499822080135345, + 0.025791814550757408, + 0.02454221248626709, + 0.022249994799494743, + 0.022207852452993393, + 0.022500054910779, + 0.02195802517235279, + 0.02191704697906971, + 0.022208085283637047, + 0.022249994799494743, + 0.021792016923427582, + 0.02187490463256836, + 0.023208092898130417, + 0.021416926756501198, + 0.02150004729628563, + 0.021791085600852966, + 0.020958948880434036, + 0.02150004729628563, + 0.023416010662913322, + 0.023124972358345985, + 0.07499987259507179, + 0.0278339721262455, + 0.029041199013590813, + 0.027207890525460243, + 0.02774992026388645, + 0.02979184500873089, + 0.030624913051724434, + 0.031000003218650818, + 0.03091711550951004, + 0.031416770070791245, + 0.050582922995090485, + 0.0327499583363533, + 0.02791592851281166, + 0.025124987587332726, + 0.023582950234413147, + 0.024250010028481483, + 0.023124972358345985, + 0.02337503246963024, + 0.027374830096960068, + 0.022249994799494743, + 0.02183392643928528, + 0.021625077351927757, + 0.021541956812143326, + 0.021459069103002548, + 0.023416010662913322, + 0.02133403904736042, + 0.024207867681980133, + 0.02100015990436077, + 0.02074986696243286, + 0.021290965378284454, + 0.021832995116710663, + 0.02145790494978428, + 0.02508307807147503, + 0.022833002731204033, + 0.04854192957282066, + 0.03212480805814266, + 0.02637505531311035, + 0.02566608600318432, + 0.023750122636556625, + 0.02300017513334751, + 0.022957799956202507, + 0.02233288250863552, + 0.02208305522799492, + 0.021999934688210487, + 0.02200016751885414, + 0.02166605554521084, + 0.022500054910779, + 0.04541594535112381, + 0.06391690112650394, + 0.026582973077893257, + 0.02374988980591297, + 0.02295803278684616, + 0.023250002413988113, + 0.022166874259710312, + 0.02254219725728035, + 0.02208305522799492, + 0.021792016923427582, + 0.022333115339279175, + 0.025999965146183968, + 0.022916821762919426, + 0.023208092898130417, + 0.030540861189365387, + 0.037833815440535545, + 0.024707987904548645, + 0.023582950234413147, + 0.022416934370994568, + 0.02195802517235279, + 0.02158316783607006, + 0.021832995116710663, + 0.021541956812143326, + 0.02229190431535244, + 0.022207852452993393, + 0.02208305522799492, + 0.021582935005426407, + 0.022792024537920952, + 0.022999942302703857, + 0.022709136828780174, + 0.022166874259710312, + 0.02183392643928528, + 0.02391706220805645, + 0.025165965780615807, + 0.02295803278684616, + 0.05408399738371372, + 0.03374996595084667, + 0.03341701813042164, + 0.025458168238401413, + 0.02408307045698166, + 0.030540861189365387, + 0.03024982288479805, + 0.026332912966609, + 0.023999949917197227, + 0.02304092049598694, + 0.022249994799494743, + 0.0227498821914196, + 0.022500054910779, + 0.022791093215346336, + 0.043625012040138245, + 0.04379195161163807, + 0.026207882910966873, + 0.02429191954433918, + 0.024209031835198402, + 0.0413327943533659, + 0.027667032554745674, + 0.026458175852894783, + 0.03491714596748352, + 0.026708003133535385, + 0.02537504769861698, + 0.024582957848906517, + 0.02400018274784088, + 0.023624859750270844, + 0.02383277751505375, + 0.023541972041130066, + 0.023499829694628716, + 0.02291705459356308, + 0.023250002413988113, + 0.02329191192984581, + 0.023333122953772545, + 0.03358395770192146, + 0.024165958166122437, + 0.024624867364764214, + 0.02345792017877102, + 0.024250010028481483, + 0.02329191192984581, + 0.02483394928276539, + 0.02395804040133953, + 0.023208092898130417, + 0.02287491224706173, + 0.039708102121949196, + 0.027250032871961594, + 0.028042122721672058, + 0.02429191954433918, + 0.023166881874203682, + 0.02291705459356308, + 0.02237502485513687, + 0.023541972041130066, + 0.032250070944428444, + 0.03129197284579277, + 0.03391597419977188, + 0.025999965146183968, + 0.02395804040133953, + 0.022624852135777473, + 0.02233288250863552, + 0.02354104071855545, + 0.02208305522799492, + 0.02195802517235279, + 0.02445792779326439, + 0.022750115022063255, + 0.022666994482278824, + 0.022166874259710312, + 0.022625084966421127, + 0.02170819789171219, + 0.03183400258421898, + 0.02491706982254982, + 0.029291026294231415, + 0.023042084649205208, + 0.025709159672260284, + 0.022624852135777473, + 0.0227498821914196, + 0.02266606315970421, + 0.02391589805483818, + 0.06041605956852436, + 0.032125040888786316, + 0.04137493669986725, + 0.024624867364764214, + 0.02270890399813652, + 0.0227498821914196, + 0.023167114704847336, + 0.03937492147088051, + 0.02770894207060337, + 0.023833010345697403, + 0.04241708666086197, + 0.027499860152602196, + 0.026416964828968048, + 0.034250086173415184, + 0.02904096618294716, + 0.023541972041130066, + 0.023790867999196053, + 0.02458319067955017, + 0.024833017960190773, + 0.024625100195407867, + 0.025042099878191948, + 0.02483394928276539, + 0.024458160623908043, + 0.024665845558047295, + 0.023875152692198753, + 0.024042092263698578, + 0.024084001779556274, + 0.024166889488697052, + 0.02391589805483818, + 0.02345792017877102, + 0.030375085771083832, + 0.021791085600852966, + 0.3201661165803671, + 0.023124972358345985, + 0.028708018362522125, + 0.022042077034711838, + 0.02750009298324585, + 0.021541956812143326, + 0.027582980692386627, + 0.021832995116710663, + 0.02166605554521084, + 0.03374996595084667, + 0.0338749960064888, + 0.04424992948770523, + 0.051582930609583855, + 0.8271248079836369, + 0.046833185479044914, + 0.029999995604157448, + 0.02437504008412361, + 0.023250002413988113, + 0.022624852135777473, + 0.022875145077705383, + 0.022625084966421127, + 0.022042077034711838, + 0.02187490463256836, + 0.02245907671749592, + 0.022625084966421127, + 0.022042077034711838, + 0.026292167603969574, + 0.022875145077705383, + 0.025165965780615807, + 0.027166912332177162, + 0.030207913368940353, + 0.02929195761680603, + 0.027042115107178688, + 0.03587501123547554, + 0.02533290535211563, + 0.024124979972839355, + 0.11379201896488667, + 0.03724987618625164, + 0.027333153411746025, + 0.024208100512623787, + 0.0238749198615551, + 0.023792032152414322, + 0.02845795825123787, + 0.022792024537920952, + 0.023167114704847336, + 0.02550007775425911, + 0.022625084966421127, + 0.02483394928276539, + 0.024041859433054924, + 0.022290972992777824, + 0.023250002413988113, + 0.026332912966609, + 0.024165958166122437, + 0.027833040803670883, + 0.027209054678678513, + 0.02520880661904812 + ], + "replay": { + "model": "trials/tool-reach-reach-heldout-heavy-baseline.model.json", + "motion": "trials/tool-reach-reach-heldout-heavy-baseline.motion.json" + }, + "export_seconds": 0.8515262908767909 + }, + { + "id": "tool-reach-reach-heldout-heavy-recovery", + "task": "tool-reach", + "policy": "recovery", + "case": { + "id": "reach-heldout-heavy", + "shoe_x": 0.735, + "shoe_y": -0.075, + "mass": 0.55, + "friction": 1.05, + "tool_length": 0.37, + "lateral_error": 0.035, + "split": "heldout" + }, + "valid": true, + "success": false, + "metrics": { + "retrieval_success": true, + "grasp_attempted": true, + "retained_lift_success": false, + "final_shoe_speed_m_s": 0.07938056913916249, + "shoe_displacement_x_m": 0.4011409069865923, + "final_shoe_position_m": [ + 0.33385909301340766, + -0.0813226169310668, + 0.12943451687092655 + ], + "peak_lift_m": 0.16526366411263338, + "recovery_attempts": 0, + "help_requested": true, + "peak_tool_shoe_force_n": 12.95346963501141, + "peak_tool_shoe_force_time_s": 3.0159999999998894, + "tool_shoe_impulse_ns": 14.610727306133084, + "tool_shoe_contact_ticks": 1807, + "physics_timestep_s": 0.002, + "policy_interval_s": 0.02, + "max_joint_command_delta_rad": 0.0030000000000001137, + "max_tracking_error_m": 0.18820293053128587, + "simulation_seconds": 12.600000000000877, + "wall_seconds": 0.552977291867137, + "solver_warnings": 0, + "native_steps": 6300, + "shoe_external_force_used": false, + "shoe_equality_constraints": 0, + "recovery_count": 0, + "intervention_count": 1, + "peak_contact_force_n": 20.971625274978795, + "contact_force_scope": "sum of normal shoe-to-robot/tool forces, excluding table", + "force_peak_by_phase_n": { + "settle": 0.0, + "approach_tool": 0.0, + "lower_tool": 12.95346963501141, + "pull_shoe": 8.224335006590293, + "verify_pull": 3.9716480557663125, + "clear_rake": 4.965117629301519, + "grasp_approach": 19.233596102028322, + "close_jaws": 20.971625274978795, + "lift": 20.62512770169056 + }, + "policy_compute_p50_ms": 0.024895532988011837, + "policy_compute_p95_ms": 0.03845631144940852, + "policy_compute_max_ms": 0.18574995920062065, + "wall_includes_model_compile": true, + "recorded_state_scope": "privileged native state; qpos has 6 arm radians, 2 jaw metres, shoe XYZ metres and quaternion wxyz; qvel has 6 arm rad/s, 2 jaw m/s, shoe linear m/s and angular rad/s; controls are 6 joint radians plus jaw metres; requested targets update every20ms and issued controls are rate limited every2ms", + "retention_criterion": "shoe bottom >35 mm with both fingers contacting, tool and world force each <0.01 N for final 500 ms", + "no_tool_baseline": false, + "tool_pre_equipped": true, + "outcome": "retrieved_lift_failed", + "real_time_factor": 22.78574578977153 + }, + "events": [ + { + "t": 0.0, + "type": "assumptions", + "message": "assumptions", + "pre_equipped_rigid_tool": true, + "privileged_observations": true, + "shoe_attachment": false, + "controller_reach_limit_x_m": 0.54, + "tool_acquisition_tested": false + }, + { + "t": 0.0, + "type": "phase", + "message": "settle", + "name": "settle", + "target": [ + 0.36, + -0.06, + 0.27 + ] + }, + { + "t": 0.4, + "type": "phase", + "message": "approach tool", + "name": "approach_tool", + "target": [ + 0.5299999676794003, + -0.0400000518727945, + 0.25 + ] + }, + { + "t": 2.2, + "type": "phase", + "message": "lower tool", + "name": "lower_tool", + "target": [ + 0.5299999676794003, + -0.0400000518727945, + 0.075 + ] + }, + { + "t": 3.2, + "type": "phase", + "message": "pull shoe", + "name": "pull_shoe", + "target": [ + 0.2, + -0.0400000518727945, + 0.075 + ] + }, + { + "t": 6.2, + "type": "phase", + "message": "verify pull", + "name": "verify_pull", + "target": [ + 0.2, + -0.0400000518727945, + 0.075 + ] + }, + { + "t": 6.6, + "type": "retrieval_check", + "message": "retrieval check", + "attempt": 1, + "retrieved": true, + "shoe_x_m": 0.4159473795898768, + "displacement_m": 0.31905262041012317 + }, + { + "t": 6.6, + "type": "phase", + "message": "clear rake", + "name": "clear_rake", + "target": [ + 0.24, + -0.075, + 0.25 + ] + }, + { + "t": 7.8, + "type": "phase", + "message": "grasp approach", + "name": "grasp_approach", + "target": [ + 0.3670827060364998, + -0.07728569847758295, + 0.06 + ] + }, + { + "t": 9.6, + "type": "phase", + "message": "close jaws", + "name": "close_jaws", + "target": [ + 0.3670827060364998, + -0.07728569847758295, + 0.06 + ] + }, + { + "t": 10.6, + "type": "phase", + "message": "lift", + "name": "lift", + "target": [ + 0.3670827060364998, + -0.07728569847758295, + 0.28 + ] + }, + { + "t": 12.6, + "type": "lift_check", + "message": "lift check", + "retained": false, + "shoe_bottom_z_m": 0.12943451687092655 + }, + { + "t": 12.6, + "type": "help_requested", + "message": "retrieved but jaw lift not retained", + "reason": "retrieved_but_jaw_lift_not_retained" + } + ], + "errors": [], + "wall_seconds": 0.5547909170854837, + "native_trace_columns": [ + "t_s", + "tool_shoe_force_n", + "shoe_robot_force_n", + "left_finger_force_n", + "right_finger_force_n", + "shoe_x_m", + "shoe_y_m", + "shoe_z_m", + "world_shoe_force_n" + ], + "control_compute_ms": [ + 0.02991710789501667, + 0.03391713835299015, + 0.02787495031952858, + 0.03004097379744053, + 0.02691592089831829, + 0.02537504769861698, + 0.02450007013976574, + 0.024416018277406693, + 0.024541979655623436, + 0.02450007013976574, + 0.025250017642974854, + 0.025292159989476204, + 0.027916161343455315, + 0.0299159437417984, + 0.07824995554983616, + 0.047042034566402435, + 0.03245798870921135, + 0.02833409234881401, + 0.02637505531311035, + 0.02591591328382492, + 0.027999980375170708, + 0.08691707625985146, + 0.027167145162820816, + 0.029416987672448158, + 0.025833025574684143, + 0.03558304160833359, + 0.029041897505521774, + 0.02587493509054184, + 0.025625107809901237, + 0.025250017642974854, + 0.02408307045698166, + 0.024165958166122437, + 0.02404092811048031, + 0.023499829694628716, + 0.023416941985487938, + 0.029165996238589287, + 0.02391706220805645, + 0.023707980290055275, + 0.023292144760489464, + 0.023541972041130066, + 0.02366676926612854, + 0.023250002413988113, + 0.0238749198615551, + 0.0235831830650568, + 0.026667024940252304, + 0.023875152692198753, + 0.023791100829839706, + 0.023833010345697403, + 0.023834174498915672, + 0.02408307045698166, + 0.03287498839199543, + 0.02666609361767769, + 0.025250017642974854, + 0.02487492747604847, + 0.025250017642974854, + 0.024625100195407867, + 0.02450007013976574, + 0.024999957531690598, + 0.026750145480036736, + 0.028542010113596916, + 0.042625004425644875, + 0.028999987989664078, + 0.025790883228182793, + 0.02537504769861698, + 0.024625100195407867, + 0.02408307045698166, + 0.06020907312631607, + 0.024707987904548645, + 0.02433289773762226, + 0.024082837626338005, + 0.023541972041130066, + 0.024582957848906517, + 0.025292159989476204, + 0.027165981009602547, + 0.028584152460098267, + 0.031250063329935074, + 0.02879183739423752, + 0.03129197284579277, + 0.030749943107366562, + 0.033542048186063766, + 0.034125056117773056, + 0.03316695801913738, + 0.037999823689460754, + 0.03687501884996891, + 0.036082929000258446, + 0.04258309490978718, + 0.04200008697807789, + 0.035708071663975716, + 0.09787501767277718, + 0.031624920666217804, + 0.02650008536875248, + 0.025499844923615456, + 0.025541987270116806, + 0.024792039766907692, + 0.02437504008412361, + 0.024250010028481483, + 0.02445792779326439, + 0.023707980290055275, + 0.021249987185001373, + 0.03887503407895565, + 0.027542002499103546, + 0.02545909956097603, + 0.023999949917197227, + 0.023250002413988113, + 0.023042084649205208, + 0.022791791707277298, + 0.021958956494927406, + 0.022540800273418427, + 0.022875145077705383, + 0.021999934688210487, + 0.025250017642974854, + 0.02491590566933155, + 0.023999949917197227, + 0.024124979972839355, + 0.02391706220805645, + 0.024582957848906517, + 0.02412521280348301, + 0.026916852220892906, + 0.031291041523218155, + 0.026333145797252655, + 0.02529192715883255, + 0.022750115022063255, + 0.03266683779656887, + 0.031458912417292595, + 0.02700020559132099, + 0.02408307045698166, + 0.02537504769861698, + 0.02200016751885414, + 0.02200016751885414, + 0.027209054678678513, + 0.021541956812143326, + 0.022290972992777824, + 0.02683396451175213, + 0.02591591328382492, + 0.026084017008543015, + 0.025042099878191948, + 0.024625100195407867, + 0.025041168555617332, + 0.024833017960190773, + 0.024750130251049995, + 0.02437504008412361, + 0.025916146114468575, + 0.02400018274784088, + 0.030708033591508865, + 0.025833025574684143, + 0.024667009711265564, + 0.024707987904548645, + 0.028582988306879997, + 0.023709144443273544, + 0.03208313137292862, + 0.031041912734508514, + 0.024167122319340706, + 0.025374814867973328, + 0.025207875296473503, + 0.02233288250863552, + 0.021875137463212013, + 0.021374784409999847, + 0.028082868084311485, + 0.025416957214474678, + 0.022916821762919426, + 0.033082906156778336, + 0.031000003218650818, + 0.025582965463399887, + 0.029166927561163902, + 0.02491590566933155, + 0.02395804040133953, + 0.023709144443273544, + 0.023875152692198753, + 0.023417174816131592, + 0.024167122319340706, + 0.02491706982254982, + 0.024208100512623787, + 0.023667002096772194, + 0.025209039449691772, + 0.024416949599981308, + 0.02570892684161663, + 0.04037492908537388, + 0.02808310091495514, + 0.025916844606399536, + 0.025833025574684143, + 0.025333836674690247, + 0.02637505531311035, + 0.04537496715784073, + 0.02954108640551567, + 0.07829186506569386, + 0.031207920983433723, + 0.026041874662041664, + 0.024709152057766914, + 0.024582957848906517, + 0.024250010028481483, + 0.033916207030415535, + 0.0274579506367445, + 0.02550007775425911, + 0.024250010028481483, + 0.024875160306692123, + 0.02450007013976574, + 0.024250010028481483, + 0.02245907671749592, + 0.038667116314172745, + 0.02600019797682762, + 0.0239592045545578, + 0.022875145077705383, + 0.023124972358345985, + 0.02304092049598694, + 0.028667040169239044, + 0.04483410157263279, + 0.03087497316300869, + 0.02691592089831829, + 0.025583896785974503, + 0.025250017642974854, + 0.024750130251049995, + 0.02604094333946705, + 0.02437504008412361, + 0.023833010345697403, + 0.024499837309122086, + 0.024709152057766914, + 0.025541987270116806, + 0.023667002096772194, + 0.023665837943553925, + 0.023875152692198753, + 0.02400018274784088, + 0.031125033274292946, + 0.026333145797252655, + 0.02487492747604847, + 0.03220816142857075, + 0.031333183869719505, + 0.026791123673319817, + 0.022750115022063255, + 0.022124964743852615, + 0.02233288250863552, + 0.022416934370994568, + 0.03095809370279312, + 0.025042099878191948, + 0.023583881556987762, + 0.0338749960064888, + 0.023999949917197227, + 0.023667002096772194, + 0.022582942619919777, + 0.022333115339279175, + 0.022625084966421127, + 0.02195802517235279, + 0.023999949917197227, + 0.030625145882368088, + 0.024791108444333076, + 0.02433289773762226, + 0.023792032152414322, + 0.02374988980591297, + 0.023583881556987762, + 0.023833010345697403, + 0.024333829060196877, + 0.023875152692198753, + 0.03595883026719093, + 0.02737506292760372, + 0.02529192715883255, + 0.024792039766907692, + 0.024166889488697052, + 0.02408307045698166, + 0.04533398896455765, + 0.03558304160833359, + 0.028542010113596916, + 0.026167137548327446, + 0.024582957848906517, + 0.023999949917197227, + 0.024250010028481483, + 0.025790883228182793, + 0.02595805563032627, + 0.02545909956097603, + 0.024958979338407516, + 0.02491590566933155, + 0.025499844923615456, + 0.024084001779556274, + 0.025541987270116806, + 0.023792032152414322, + 0.024624867364764214, + 0.024624867364764214, + 0.041125109419226646, + 0.02795807085931301, + 0.026166904717683792, + 0.025458168238401413, + 0.025042099878191948, + 0.027624890208244324, + 0.03337510861456394, + 0.029042130336165428, + 0.026332912966609, + 0.025499844923615456, + 0.024541979655623436, + 0.023916829377412796, + 0.024042092263698578, + 0.024124979972839355, + 0.04070787690579891, + 0.028541777282953262, + 0.0252497848123312, + 0.02545909956097603, + 0.024750130251049995, + 0.024250010028481483, + 0.02466607838869095, + 0.024958979338407516, + 0.025084009394049644, + 0.02774992026388645, + 0.02674991264939308, + 0.025624874979257584, + 0.026124995201826096, + 0.03454205580055714, + 0.054541975259780884, + 0.03429199568927288, + 0.027582980692386627, + 0.027165981009602547, + 0.02787495031952858, + 0.031250063329935074, + 0.03454112447798252, + 0.035624951124191284, + 0.03695813938975334, + 0.03383285365998745, + 0.03537489101290703, + 0.03554206341505051, + 0.03862520679831505, + 0.03541610203683376, + 0.03437488339841366, + 0.051541952416300774, + 0.03712484613060951, + 0.029582995921373367, + 0.034333206713199615, + 0.03183307126164436, + 0.031624920666217804, + 0.03145798109471798, + 0.044459011405706406, + 0.029624905437231064, + 0.026999972760677338, + 0.02550007775425911, + 0.02487492747604847, + 0.026916852220892906, + 0.025416957214474678, + 0.026667024940252304, + 0.026750145480036736, + 0.025625107809901237, + 0.02245791256427765, + 0.022625084966421127, + 0.021999934688210487, + 0.022208085283637047, + 0.022124964743852615, + 0.022207852452993393, + 0.022333115339279175, + 0.02233288250863552, + 0.025625107809901237, + 0.028125010430812836, + 0.024584122002124786, + 0.036125071346759796, + 0.03108312375843525, + 0.026625115424394608, + 0.026916852220892906, + 0.02583279274404049, + 0.028790906071662903, + 0.025667017325758934, + 0.024833017960190773, + 0.023625092580914497, + 0.02329191192984581, + 0.022292137145996094, + 0.024792039766907692, + 0.02183392643928528, + 0.021750107407569885, + 0.021832995116710663, + 0.023167114704847336, + 0.021625077351927757, + 0.021625077351927757, + 0.02204091288149357, + 0.025584129616618156, + 0.02766610123217106, + 0.025207875296473503, + 0.0238749198615551, + 0.04449998959898949, + 0.030750175938010216, + 0.03079185262322426, + 0.025707995519042015, + 0.025250017642974854, + 0.03283401019871235, + 0.0313750933855772, + 0.025458168238401413, + 0.02170889638364315, + 0.023582950234413147, + 0.021208077669143677, + 0.021249987185001373, + 0.021249987185001373, + 0.022167107090353966, + 0.026208115741610527, + 0.026708003133535385, + 0.02350006252527237, + 0.022416934370994568, + 0.02195802517235279, + 0.024084001779556274, + 0.025624874979257584, + 0.026458175852894783, + 0.03329082392156124, + 0.027957838028669357, + 0.026499852538108826, + 0.025209039449691772, + 0.024999957531690598, + 0.025750137865543365, + 0.02491706982254982, + 0.024084001779556274, + 0.023582950234413147, + 0.023250002413988113, + 0.02333289012312889, + 0.023707980290055275, + 0.02287491224706173, + 0.023833010345697403, + 0.023250002413988113, + 0.023625092580914497, + 0.02295803278684616, + 0.023082830011844635, + 0.02333289012312889, + 0.02291705459356308, + 0.024082837626338005, + 0.023707980290055275, + 0.03212480805814266, + 0.027708010748028755, + 0.024792039766907692, + 0.028667040169239044, + 0.027750153094530106, + 0.024875160306692123, + 0.02433289773762226, + 0.027667032554745674, + 0.025791814550757408, + 0.024165958166122437, + 0.027208123356103897, + 0.023957807570695877, + 0.02404092811048031, + 0.024250010028481483, + 0.027208123356103897, + 0.023875152692198753, + 0.02395804040133953, + 0.024333130568265915, + 0.023792032152414322, + 0.023124972358345985, + 0.026124995201826096, + 0.02337503246963024, + 0.030584167689085007, + 0.025417190045118332, + 0.024333130568265915, + 0.024042092263698578, + 0.023083994165062904, + 0.023999949917197227, + 0.023583881556987762, + 0.023166881874203682, + 0.02308306284248829, + 0.023707980290055275, + 0.023582950234413147, + 0.023582950234413147, + 0.023667002096772194, + 0.024041859433054924, + 0.023667002096772194, + 0.02329191192984581, + 0.02337503246963024, + 0.02345792017877102, + 0.022999942302703857, + 0.023333122953772545, + 0.024082837626338005, + 0.03774999640882015, + 0.037499936297535896, + 0.027167145162820816, + 0.025417190045118332, + 0.025667017325758934, + 0.025707995519042015, + 0.026209047064185143, + 0.022707972675561905, + 0.022209016606211662, + 0.022582942619919777, + 0.02254219725728035, + 0.021999934688210487, + 0.021707965061068535, + 0.021667219698429108, + 0.021416926756501198, + 0.022166874259710312, + 0.024333130568265915, + 0.0316668301820755, + 0.02637505531311035, + 0.03958307206630707, + 0.027709174901247025, + 0.022999942302703857, + 0.02291705459356308, + 0.022707972675561905, + 0.027542002499103546, + 0.028042122721672058, + 0.029999995604157448, + 0.022249994799494743, + 0.022582942619919777, + 0.022124964743852615, + 0.029166927561163902, + 0.024124979972839355, + 0.0235831830650568, + 0.02258317545056343, + 0.022249994799494743, + 0.02329191192984581, + 0.023209024220705032, + 0.02466607838869095, + 0.023166881874203682, + 0.023250002413988113, + 0.023416010662913322, + 0.02329191192984581, + 0.02433289773762226, + 0.031000003218650818, + 0.028582988306879997, + 0.026041874662041664, + 0.024791108444333076, + 0.024416018277406693, + 0.03187498077750206, + 0.03295904025435448, + 0.029416987672448158, + 0.025250017642974854, + 0.025292159989476204, + 0.02783280797302723, + 0.024124979972839355, + 0.024124979972839355, + 0.025124987587332726, + 0.02400018274784088, + 0.02337503246963024, + 0.031207920983433723, + 0.02666609361767769, + 0.024707987904548645, + 0.024792039766907692, + 0.023624859750270844, + 0.023165950551629066, + 0.0238749198615551, + 0.02345908433198929, + 0.02370891161262989, + 0.023750122636556625, + 0.02979184500873089, + 0.025541987270116806, + 0.024541979655623436, + 0.02533290535211563, + 0.022124964743852615, + 0.02395804040133953, + 0.02587493509054184, + 0.024624867364764214, + 0.024667009711265564, + 0.021832995116710663, + 0.02237502485513687, + 0.02174987457692623, + 0.021541956812143326, + 0.023958971723914146, + 0.024209031835198402, + 0.023750122636556625, + 0.023667002096772194, + 0.02429191954433918, + 0.023791100829839706, + 0.02370891161262989, + 0.023875152692198753, + 0.023707980290055275, + 0.022875145077705383, + 0.02270820550620556, + 0.022957799956202507, + 0.024707987904548645, + 0.026541994884610176, + 0.02333289012312889, + 0.022875145077705383, + 0.022999942302703857, + 0.026499852538108826, + 0.024124979972839355, + 0.023583881556987762, + 0.026624882593750954, + 0.03624986857175827, + 0.027416041120886803, + 0.026875175535678864, + 0.022416003048419952, + 0.027166912332177162, + 0.02208305522799492, + 0.02150004729628563, + 0.034291064366698265, + 0.026250025257468224, + 0.027207890525460243, + 0.023667002096772194, + 0.025999965146183968, + 0.02295919694006443, + 0.023416941985487938, + 0.022584106773138046, + 0.024416949599981308, + 0.022707972675561905, + 0.022625084966421127, + 0.022834166884422302, + 0.022582942619919777, + 0.03295904025435448, + 0.026332912966609, + 0.02545793540775776, + 0.025209039449691772, + 0.02450007013976574, + 0.024958979338407516, + 0.03895815461874008, + 0.02287491224706173, + 0.03537512384355068, + 0.028250040486454964, + 0.04295818507671356, + 0.030124792829155922, + 0.025124987587332726, + 0.02433289773762226, + 0.023417174816131592, + 0.025625107809901237, + 0.024165958166122437, + 0.024625100195407867, + 0.02437504008412361, + 0.024208100512623787, + 0.02391706220805645, + 0.023791799321770668, + 0.032207928597927094, + 0.030540861189365387, + 0.024416949599981308, + 0.024041859433054924, + 0.028708018362522125, + 0.02474989742040634, + 0.02333405427634716, + 0.022500054910779, + 0.02354104071855545, + 0.023124972358345985, + 0.18574995920062065, + 0.06579188629984856, + 0.043625012040138245, + 0.0302919652312994, + 0.03637513145804405, + 0.029582995921373367, + 0.040499959141016006, + 0.029750168323516846, + 0.03300001844763756, + 0.028167152777314186, + 0.026209047064185143, + 0.03091595135629177, + 0.02537504769861698, + 0.026624882593750954, + 0.051667215302586555, + 0.0891669187694788, + 0.03824988380074501, + 0.0410410575568676, + 0.029291026294231415 + ], + "replay": { + "model": "trials/tool-reach-reach-heldout-heavy-recovery.model.json", + "motion": "trials/tool-reach-reach-heldout-heavy-recovery.motion.json" + }, + "export_seconds": 0.999219249933958 + }, + { + "id": "tool-reach-reach-heldout-short-baseline", + "task": "tool-reach", + "policy": "baseline", + "case": { + "id": "reach-heldout-short", + "shoe_x": 0.72, + "shoe_y": -0.105, + "mass": 0.27, + "friction": 0.55, + "tool_length": 0.18, + "lateral_error": 0.015, + "split": "heldout" + }, + "valid": true, + "success": false, + "metrics": { + "retrieval_success": false, + "grasp_attempted": true, + "retained_lift_success": false, + "final_shoe_speed_m_s": 1.397808611193814e-12, + "shoe_displacement_x_m": 2.2724222170644737e-08, + "final_shoe_position_m": [ + 0.7199999772757778, + -0.10500005199308247, + -0.00010773877982362633 + ], + "peak_lift_m": 0.0, + "recovery_attempts": 0, + "help_requested": false, + "peak_tool_shoe_force_n": 0.0, + "peak_tool_shoe_force_time_s": 0.0, + "tool_shoe_impulse_ns": 0.0, + "tool_shoe_contact_ticks": 0, + "physics_timestep_s": 0.002, + "policy_interval_s": 0.02, + "max_joint_command_delta_rad": 0.0030000000000001137, + "max_tracking_error_m": 0.13174480451689524, + "simulation_seconds": 5.399999999999627, + "wall_seconds": 0.3304365419317037, + "solver_warnings": 0, + "native_steps": 2700, + "shoe_external_force_used": false, + "shoe_equality_constraints": 0, + "recovery_count": 0, + "intervention_count": 0, + "peak_contact_force_n": 0.0, + "contact_force_scope": "sum of normal shoe-to-robot/tool forces, excluding table", + "force_peak_by_phase_n": { + "settle": 0.0, + "direct_reach": 0.0, + "direct_close": 0.0, + "direct_lift": 0.0 + }, + "policy_compute_p50_ms": 0.0237500062212348, + "policy_compute_p95_ms": 0.03594796871766447, + "policy_compute_max_ms": 0.07462501525878906, + "wall_includes_model_compile": true, + "recorded_state_scope": "privileged native state; qpos has 6 arm radians, 2 jaw metres, shoe XYZ metres and quaternion wxyz; qvel has 6 arm rad/s, 2 jaw m/s, shoe linear m/s and angular rad/s; controls are 6 joint radians plus jaw metres; requested targets update every20ms and issued controls are rate limited every2ms", + "retention_criterion": "shoe bottom >35 mm with both fingers contacting, tool and world force each <0.01 N for final 500 ms", + "no_tool_baseline": true, + "tool_pre_equipped": false, + "outcome": "failed_direct_reach", + "real_time_factor": 16.3420182538883 + }, + "events": [ + { + "t": 0.0, + "type": "assumptions", + "message": "assumptions", + "pre_equipped_rigid_tool": false, + "privileged_observations": true, + "shoe_attachment": false, + "controller_reach_limit_x_m": 0.54, + "tool_acquisition_tested": false + }, + { + "t": 0.0, + "type": "phase", + "message": "settle", + "name": "settle", + "target": [ + 0.36, + -0.06, + 0.27 + ] + }, + { + "t": 0.4, + "type": "direct_reach_attempt", + "message": "direct reach attempt", + "desired_x_m": 0.7199999772540483, + "clipped_x_m": 0.54 + }, + { + "t": 0.4, + "type": "phase", + "message": "direct reach", + "name": "direct_reach", + "target": [ + 0.54, + -0.105, + 0.075 + ] + }, + { + "t": 2.9, + "type": "phase", + "message": "direct close", + "name": "direct_close", + "target": [ + 0.54, + -0.105, + 0.075 + ] + }, + { + "t": 3.9, + "type": "phase", + "message": "direct lift", + "name": "direct_lift", + "target": [ + 0.5, + -0.105, + 0.2 + ] + }, + { + "t": 5.4, + "type": "direct_reach_failed", + "message": "direct reach failed", + "shoe_x_m": 0.7199999772757778 + } + ], + "errors": [], + "wall_seconds": 0.3317696249578148, + "native_trace_columns": [ + "t_s", + "tool_shoe_force_n", + "shoe_robot_force_n", + "left_finger_force_n", + "right_finger_force_n", + "shoe_x_m", + "shoe_y_m", + "shoe_z_m", + "world_shoe_force_n" + ], + "control_compute_ms": [ + 0.02487492747604847, + 0.027667032554745674, + 0.023458153009414673, + 0.029125018045306206, + 0.0238749198615551, + 0.024582957848906517, + 0.034041935577988625, + 0.025999965146183968, + 0.025250017642974854, + 0.02391589805483818, + 0.02245791256427765, + 0.02233288250863552, + 0.022499822080135345, + 0.022416934370994568, + 0.024667009711265564, + 0.021916814148426056, + 0.025042099878191948, + 0.023167114704847336, + 0.022292137145996094, + 0.021999934688210487, + 0.025541987270116806, + 0.02312520518898964, + 0.07324991747736931, + 0.024625100195407867, + 0.02504093572497368, + 0.022124964743852615, + 0.022249994799494743, + 0.022208085283637047, + 0.021207844838500023, + 0.022582942619919777, + 0.026667024940252304, + 0.02212519757449627, + 0.02154102548956871, + 0.02195802517235279, + 0.021999934688210487, + 0.024875160306692123, + 0.02483278512954712, + 0.04075001925230026, + 0.046416884288191795, + 0.03354111686348915, + 0.026790890842676163, + 0.026750145480036736, + 0.024250010028481483, + 0.022834166884422302, + 0.022999942302703857, + 0.023042084649205208, + 0.02674991264939308, + 0.02258317545056343, + 0.024209031835198402, + 0.02204091288149357, + 0.021999934688210487, + 0.021832995116710663, + 0.02629193477332592, + 0.022209016606211662, + 0.022916821762919426, + 0.025250017642974854, + 0.022249994799494743, + 0.02208305522799492, + 0.023625092580914497, + 0.02191704697906971, + 0.02304092049598694, + 0.025042099878191948, + 0.021707965061068535, + 0.023290980607271194, + 0.027042115107178688, + 0.0227498821914196, + 0.023792032152414322, + 0.024625100195407867, + 0.024625100195407867, + 0.07462501525878906, + 0.03254180774092674, + 0.030542025342583656, + 0.03033294342458248, + 0.033125048503279686, + 0.03304216079413891, + 0.039874808862805367, + 0.02804095856845379, + 0.025624874979257584, + 0.025082845240831375, + 0.02329191192984581, + 0.022709136828780174, + 0.022416934370994568, + 0.022417167201638222, + 0.02245791256427765, + 0.022124964743852615, + 0.021999934688210487, + 0.021707965061068535, + 0.02237502485513687, + 0.021499814465641975, + 0.021292129531502724, + 0.021416926756501198, + 0.022042077034711838, + 0.022833002731204033, + 0.0227498821914196, + 0.024166889488697052, + 0.024041859433054924, + 0.025416957214474678, + 0.028207898139953613, + 0.030916882678866386, + 0.030041905120015144, + 0.03345916047692299, + 0.043416861444711685, + 0.026416033506393433, + 0.023624859750270844, + 0.022916123270988464, + 0.0227498821914196, + 0.04229182377457619, + 0.030624913051724434, + 0.02587493509054184, + 0.024167122319340706, + 0.024290988221764565, + 0.023707980290055275, + 0.022750115022063255, + 0.04845811054110527, + 0.032250070944428444, + 0.025167129933834076, + 0.022624852135777473, + 0.02237502485513687, + 0.02195802517235279, + 0.02166605554521084, + 0.022249994799494743, + 0.021832995116710663, + 0.02191588282585144, + 0.0213750172406435, + 0.028041889891028404, + 0.024792039766907692, + 0.023250002413988113, + 0.02287491224706173, + 0.022750115022063255, + 0.02237502485513687, + 0.022249994799494743, + 0.0227498821914196, + 0.022792024537920952, + 0.023250002413988113, + 0.02237502485513687, + 0.023124972358345985, + 0.022625084966421127, + 0.036041950806975365, + 0.022625084966421127, + 0.02216617576777935, + 0.02200016751885414, + 0.022333813831210136, + 0.02141715958714485, + 0.02154102548956871, + 0.033499905839562416, + 0.026165973395109177, + 0.02391706220805645, + 0.028082868084311485, + 0.02400018274784088, + 0.03208382986485958, + 0.025333138182759285, + 0.02212519757449627, + 0.021875137463212013, + 0.02195802517235279, + 0.02191704697906971, + 0.02129189670085907, + 0.021415995433926582, + 0.021124957129359245, + 0.021124957129359245, + 0.021832995116710663, + 0.02237502485513687, + 0.02245791256427765, + 0.023625092580914497, + 0.028333161026239395, + 0.02750009298324585, + 0.03033410757780075, + 0.03341701813042164, + 0.03379187546670437, + 0.03358419053256512, + 0.026708003133535385, + 0.02491706982254982, + 0.02433289773762226, + 0.02474989742040634, + 0.025416025891900063, + 0.02437504008412361, + 0.024124979972839355, + 0.02374988980591297, + 0.0238749198615551, + 0.02366607077419758, + 0.027458183467388153, + 0.021249987185001373, + 0.024958979338407516, + 0.047625042498111725, + 0.022666994482278824, + 0.021166866645216942, + 0.02095801755785942, + 0.029875198379158974, + 0.030959025025367737, + 0.025707995519042015, + 0.023792032152414322, + 0.02450007013976574, + 0.022583873942494392, + 0.026833033189177513, + 0.023750122636556625, + 0.022666994482278824, + 0.023999949917197227, + 0.024290988221764565, + 0.02291705459356308, + 0.022707972675561905, + 0.026625115424394608, + 0.023790867999196053, + 0.022624852135777473, + 0.022416934370994568, + 0.022707972675561905, + 0.022584106773138046, + 0.023041153326630592, + 0.022625084966421127, + 0.022833002731204033, + 0.022249994799494743, + 0.02233288250863552, + 0.022958964109420776, + 0.02450007013976574, + 0.027582980692386627, + 0.031000003218650818, + 0.03341701813042164, + 0.035833101719617844, + 0.036082929000258446, + 0.035708071663975716, + 0.034750206395983696, + 0.03454112447798252, + 0.035250093787908554, + 0.05333311855792999, + 0.026583904400467873, + 0.023250002413988113, + 0.022249994799494743, + 0.022791093215346336, + 0.022249994799494743, + 0.054208096116781235, + 0.021666986867785454, + 0.021167099475860596, + 0.021249987185001373, + 0.020875129848718643, + 0.021042069420218468, + 0.020999927073717117, + 0.02329191192984581, + 0.024167122319340706, + 0.023292144760489464, + 0.02374988980591297, + 0.023707980290055275, + 0.02491706982254982, + 0.024790875613689423, + 0.026041874662041664, + 0.026416964828968048, + 0.027084024623036385, + 0.030667055398225784, + 0.030250055715441704, + 0.03304099664092064, + 0.029916875064373016, + 0.03337487578392029, + 0.025417190045118332, + 0.025624874979257584, + 0.02433406189084053, + 0.024167122319340706, + 0.027667032554745674, + 0.02212519757449627, + 0.02174987457692623, + 0.03654207102954388, + 0.02691592089831829, + 0.022582942619919777, + 0.0249580480158329, + 0.021583866328001022, + 0.021582935005426407, + 0.021459069103002548, + 0.021124957129359245, + 0.021875137463212013, + 0.02474989742040634, + 0.024584122002124786, + 0.029374845325946808, + 0.026582973077893257, + 0.02687494270503521 + ], + "replay": { + "model": "trials/tool-reach-reach-heldout-short-baseline.model.json", + "motion": "trials/tool-reach-reach-heldout-short-baseline.motion.json" + }, + "export_seconds": 0.79332729219459 + }, + { + "id": "tool-reach-reach-heldout-short-recovery", + "task": "tool-reach", + "policy": "recovery", + "case": { + "id": "reach-heldout-short", + "shoe_x": 0.72, + "shoe_y": -0.105, + "mass": 0.27, + "friction": 0.55, + "tool_length": 0.18, + "lateral_error": 0.015, + "split": "heldout" + }, + "valid": true, + "success": false, + "metrics": { + "retrieval_success": false, + "grasp_attempted": false, + "retained_lift_success": false, + "final_shoe_speed_m_s": 4.143724738858311e-12, + "shoe_displacement_x_m": 2.2747197681027842e-08, + "final_shoe_position_m": [ + 0.7199999772528023, + -0.10500005188206221, + -0.00010773877980159284 + ], + "peak_lift_m": 0.0, + "recovery_attempts": 0, + "help_requested": true, + "peak_tool_shoe_force_n": 0.0, + "peak_tool_shoe_force_time_s": 0.0, + "tool_shoe_impulse_ns": 0.0, + "tool_shoe_contact_ticks": 0, + "physics_timestep_s": 0.002, + "policy_interval_s": 0.02, + "max_joint_command_delta_rad": 7.896332776313741e-06, + "max_tracking_error_m": 0.006468237481045584, + "simulation_seconds": 1.0000000000000007, + "wall_seconds": 0.2381687080487609, + "solver_warnings": 0, + "native_steps": 500, + "shoe_external_force_used": false, + "shoe_equality_constraints": 0, + "recovery_count": 0, + "intervention_count": 1, + "peak_contact_force_n": 0.0, + "contact_force_scope": "sum of normal shoe-to-robot/tool forces, excluding table", + "force_peak_by_phase_n": { + "settle": 0.0, + "hold_for_help": 0.0 + }, + "policy_compute_p50_ms": 0.023312633857131004, + "policy_compute_p95_ms": 0.0506835407577455, + "policy_compute_max_ms": 0.055958982557058334, + "wall_includes_model_compile": true, + "recorded_state_scope": "privileged native state; qpos has 6 arm radians, 2 jaw metres, shoe XYZ metres and quaternion wxyz; qvel has 6 arm rad/s, 2 jaw m/s, shoe linear m/s and angular rad/s; controls are 6 joint radians plus jaw metres; requested targets update every20ms and issued controls are rate limited every2ms", + "retention_criterion": "shoe bottom >35 mm with both fingers contacting, tool and world force each <0.01 N for final 500 ms", + "no_tool_baseline": false, + "tool_pre_equipped": true, + "outcome": "deferred_insufficient_reach", + "real_time_factor": 4.198704389811226 + }, + "events": [ + { + "t": 0.0, + "type": "assumptions", + "message": "assumptions", + "pre_equipped_rigid_tool": true, + "privileged_observations": true, + "shoe_attachment": false, + "controller_reach_limit_x_m": 0.54, + "tool_acquisition_tested": false + }, + { + "t": 0.0, + "type": "phase", + "message": "settle", + "name": "settle", + "target": [ + 0.36, + -0.06, + 0.27 + ] + }, + { + "t": 0.4, + "type": "help_requested", + "message": "tool cannot reach far edge", + "reason": "tool_cannot_reach_far_edge", + "required_tcp_x_m": 0.7049999772540483 + }, + { + "t": 0.4, + "type": "phase", + "message": "hold for help", + "name": "hold_for_help", + "target": [ + 0.36, + -0.06, + 0.27 + ] + } + ], + "errors": [], + "wall_seconds": 0.23922554193995893, + "native_trace_columns": [ + "t_s", + "tool_shoe_force_n", + "shoe_robot_force_n", + "left_finger_force_n", + "right_finger_force_n", + "shoe_x_m", + "shoe_y_m", + "shoe_z_m", + "world_shoe_force_n" + ], + "control_compute_ms": [ + 0.024250010028481483, + 0.028790906071662903, + 0.024124979972839355, + 0.028209062293171883, + 0.02487492747604847, + 0.023082830011844635, + 0.022750115022063255, + 0.021958956494927406, + 0.02266606315970421, + 0.022499822080135345, + 0.02308306284248829, + 0.055666081607341766, + 0.055958982557058334, + 0.038499943912029266, + 0.029209069907665253, + 0.02445792779326439, + 0.02491706982254982, + 0.022750115022063255, + 0.022165942937135696, + 0.023958971723914146, + 0.023999949917197227, + 0.022541964426636696, + 0.026332912966609, + 0.02637505531311035, + 0.02787495031952858, + 0.04958314821124077, + 0.0327499583363533, + 0.026207882910966873, + 0.025124987587332726, + 0.023707980290055275, + 0.023041851818561554, + 0.022791093215346336, + 0.02245791256427765, + 0.022292137145996094, + 0.022292137145996094, + 0.02191704697906971, + 0.022416934370994568, + 0.021707965061068535, + 0.022207852452993393, + 0.02154218964278698, + 0.02487492747604847, + 0.022166874259710312, + 0.02354220487177372, + 0.02187490463256836, + 0.05158386193215847, + 0.02408307045698166, + 0.02195802517235279, + 0.022166874259710312, + 0.021625077351927757, + 0.021625077351927757 + ], + "replay": { + "model": "trials/tool-reach-reach-heldout-short-recovery.model.json", + "motion": "trials/tool-reach-reach-heldout-short-recovery.motion.json" + }, + "export_seconds": 0.786098999902606 + } + ], + "groups": [ + { + "task": "hinged-box", + "policy": "baseline", + "attempts": 4, + "valid": 4, + "successes": 2, + "outcomes": { + "completed": 2, + "failed": 2 + }, + "wall_seconds": 1.030725623946637, + "metrics_note": "See every individual trial for contact, retrieval, recovery and failure details." + }, + { + "task": "hinged-box", + "policy": "recovery", + "attempts": 4, + "valid": 4, + "successes": 2, + "outcomes": { + "completed": 1, + "safe_abort": 2, + "recovered": 1 + }, + "wall_seconds": 1.1474612918682396, + "metrics_note": "See every individual trial for contact, retrieval, recovery and failure details." + }, + { + "task": "tool-reach", + "policy": "baseline", + "attempts": 4, + "valid": 4, + "successes": 0, + "outcomes": { + "failed_direct_reach": 4 + }, + "wall_seconds": 1.2767312920186669, + "metrics_note": "See every individual trial for contact, retrieval, recovery and failure details." + }, + { + "task": "tool-reach", + "policy": "recovery", + "attempts": 4, + "valid": 4, + "successes": 0, + "outcomes": { + "retrieved_lift_failed": 3, + "deferred_insufficient_reach": 1 + }, + "wall_seconds": 2.040834126062691, + "metrics_note": "See every individual trial for contact, retrieval, recovery and failure details." + } + ], + "paired_comparisons": [ + { + "task": "hinged-box", + "case_id": "open-medium", + "valid_pair": true, + "baseline_success": true, + "recovery_success": true, + "lid_contact_avoided": false, + "nuisance_interruption": false, + "nuisance_scope": "Baseline completed without disallowed contact; conservative withdrawal is not proven necessary.", + "completion_delay_s": 0.0 + }, + { + "task": "hinged-box", + "case_id": "falling-medium", + "valid_pair": true, + "baseline_success": false, + "recovery_success": false, + "lid_contact_avoided": true, + "nuisance_interruption": false, + "nuisance_scope": "Baseline completed without disallowed contact; conservative withdrawal is not proven necessary.", + "completion_delay_s": null + }, + { + "task": "hinged-box", + "case_id": "falling-low", + "valid_pair": true, + "baseline_success": false, + "recovery_success": false, + "lid_contact_avoided": true, + "nuisance_interruption": false, + "nuisance_scope": "Baseline completed without disallowed contact; conservative withdrawal is not proven necessary.", + "completion_delay_s": null + }, + { + "task": "hinged-box", + "case_id": "transient-damped", + "valid_pair": true, + "baseline_success": true, + "recovery_success": true, + "lid_contact_avoided": false, + "nuisance_interruption": true, + "nuisance_scope": "Baseline completed without disallowed contact; conservative withdrawal is not proven necessary.", + "completion_delay_s": 0.6999999999999997 + }, + { + "task": "tool-reach", + "case_id": "reach-heldout-light", + "valid_pair": true, + "baseline_success": false, + "recovery_success": false, + "baseline_retrieved": false, + "with_tool_retrieved": true, + "with_tool_retained_lift": false, + "comparison_scope": "No-tool capability control versus mounted rake plus recovery; not an isolated policy effect." + }, + { + "task": "tool-reach", + "case_id": "reach-heldout-offset", + "valid_pair": true, + "baseline_success": false, + "recovery_success": false, + "baseline_retrieved": false, + "with_tool_retrieved": true, + "with_tool_retained_lift": false, + "comparison_scope": "No-tool capability control versus mounted rake plus recovery; not an isolated policy effect." + }, + { + "task": "tool-reach", + "case_id": "reach-heldout-heavy", + "valid_pair": true, + "baseline_success": false, + "recovery_success": false, + "baseline_retrieved": false, + "with_tool_retrieved": true, + "with_tool_retained_lift": false, + "comparison_scope": "No-tool capability control versus mounted rake plus recovery; not an isolated policy effect." + }, + { + "task": "tool-reach", + "case_id": "reach-heldout-short", + "valid_pair": true, + "baseline_success": false, + "recovery_success": false, + "baseline_retrieved": false, + "with_tool_retrieved": false, + "with_tool_retained_lift": false, + "comparison_scope": "No-tool capability control versus mounted rake plus recovery; not an isolated policy effect." + } + ] +} diff --git a/benchmarks/skill-prerequisites-20261013/integrity.json b/benchmarks/skill-prerequisites-20261013/integrity.json new file mode 100644 index 0000000..d64a199 --- /dev/null +++ b/benchmarks/skill-prerequisites-20261013/integrity.json @@ -0,0 +1,298 @@ +{ + "schema": "dvidia.prerequisite-integrity/v1", + "scope": "Artifact consistency, not authenticity or physical validation.", + "files": { + "LICENSE": { + "bytes": 1076, + "sha256": "ab47d245880a661fdca3c6a4cb91671031302deee50d64f8d2d6df86832962e1" + }, + "README.md": { + "bytes": 892, + "sha256": "4ad1a98dec5f8b9e2b23a0b6f66877aab2a194295378cb24868ec777c1d46545" + }, + "assets/geometry-2e9a97f9a4c776895f0f.bin.gz": { + "bytes": 3574720, + "sha256": "51365a5a661d8062e28c66abc6bdb843ee410811f84b49d62c5878c265b3631f" + }, + "assets/motion-2f468c72326ea1a16c24.bin.gz": { + "bytes": 43684, + "sha256": "6df38b1943ca80ed23338298f3329fad3e3871765f56e225db3c734028cc51f6" + }, + "assets/motion-3cb436679010fd6d09d4.bin.gz": { + "bytes": 52655, + "sha256": "7399d16a8de2940ebfdf7ae59b652100f58c1eae120165ff4052c1dd2a1b23b3" + }, + "assets/motion-3ed428cb07d9b6425ebd.bin.gz": { + "bytes": 131270, + "sha256": "e45c2641deb5f9cc73c45d4f43c17800239e04221c53f763445e493316979c51" + }, + "assets/motion-44134aa9b34f3448d6e0.bin.gz": { + "bytes": 134495, + "sha256": "8c018f821c6dae3e47304df0e2d7bfc3539756a072c81741939d6895c8169e47" + }, + "assets/motion-520184ec57fc1763d967.bin.gz": { + "bytes": 50687, + "sha256": "96a158ab9285066e7877fb5c905e4a9e89580d30c39e47745a9892a84447d1d5" + }, + "assets/motion-5d25071df8c97aced026.bin.gz": { + "bytes": 49148, + "sha256": "e45eb1b01bb5c4b485732b87a458b536549fb3592b853fcf123a9b9f0c594fc3" + }, + "assets/motion-617482290c52ac7b8f0c.bin.gz": { + "bytes": 43494, + "sha256": "e06ed5aef69e9e8e762dab907a29f49f1db6386678ce5f6a72f66586160d6179" + }, + "assets/motion-95483628624cb3c7755e.bin.gz": { + "bytes": 10111, + "sha256": "1a988f1e4ab0335020d66790793584657d6763b016b42bfb10de0154cd944737" + }, + "assets/motion-971c5e05582a906fe9e0.bin.gz": { + "bytes": 44634, + "sha256": "1aff3a7046edc9fb5c4b5907a60fe78a8b59c97493eb672f1b0077edb73100b2" + }, + "assets/motion-a9266dc05bcaed02bc95.bin.gz": { + "bytes": 43740, + "sha256": "4b481e34aa00cf23c7c52b94a0609bdef32dd2ae62d0a7151b0a4206acac57af" + }, + "assets/motion-b5512f4578b528e71894.bin.gz": { + "bytes": 44530, + "sha256": "75f76b7dcd8f3450d12ca9d31faf4f31721f3f6f5a7ab20379781dc07690e7e1" + }, + "assets/motion-c40e224ba97f05c9bb80.bin.gz": { + "bytes": 43634, + "sha256": "421d93b0b13e3060b8c5ea5d0652bcb1c24a85483baa120935097a2395695197" + }, + "assets/motion-d1110873e8bd84432c30.bin.gz": { + "bytes": 47408, + "sha256": "8554d8a212f4894597e393821ff160c86416d7cd077eee9ce9bd3ecfcea62775" + }, + "assets/motion-d8bd50026ad6ba55e395.bin.gz": { + "bytes": 47420, + "sha256": "fade312d331cd88196653a90c8f9d39283a124aa3befb988d97fc725a14105c0" + }, + "assets/motion-de50902234cf910687ff.bin.gz": { + "bytes": 132682, + "sha256": "2b258ca92e6e640ee6cc60853c8061e6aafe583e3a1a82690aff1dc4a754b082" + }, + "benchmark.json": { + "bytes": 183405, + "sha256": "75601abac0ecaffd953267fe444aa4659163cb7a7f788d6b3e092c14737a0af8" + }, + "index.html": { + "bytes": 70901, + "sha256": "7161523a9e3a1388dedf59d2a31344b8a6ae34f3fa5947365ea5b88bb6b56ee0" + }, + "licenses/agilex_piper/LICENSE": { + "bytes": 1065, + "sha256": "e32d78fd3761052ab0b2bb42fef8a7a9ad3f298d315d305333c349d2aff1f134" + }, + "licenses/agilex_piper/README.md": { + "bytes": 1681, + "sha256": "ab0d218758ec6c298417407962f49179e369236e8f316dbaa7671756d6f8eb77" + }, + "prerequisite_lab.bundle.js": { + "bytes": 527357, + "sha256": "de099a1a2b9bf93564d28de4c6bd0511e86ca2ff58dc08c385a9b0c0a86f27e8" + }, + "protocol.json": { + "bytes": 7483, + "sha256": "addb85407392ad8581861e53e4265b1e73eefd4753e7df835879f84c02ca4754" + }, + "reference_replay.third-party.txt": { + "bytes": 1199, + "sha256": "ea4da6cf7a8a54649702f0eb8d057c8ced12f8fed2329c5e96d92a3316922813" + }, + "trials/hinged-box-falling-low-baseline.json": { + "bytes": 379540, + "sha256": "d06e6214528e3197bd9dacfa5eac3dd6141adaa4ecbb4447c34c82fc4fbdd1ce" + }, + "trials/hinged-box-falling-low-baseline.model.json": { + "bytes": 84485, + "sha256": "502b04f3f32c120454dae278ff650738b8c1a7d63752f926d28db6f4e5b7d2e4" + }, + "trials/hinged-box-falling-low-baseline.motion.json": { + "bytes": 593361, + "sha256": "fe43d47eaa106ada2558c09c48ecb3a411558fbb7f593f7bb490d271723ca658" + }, + "trials/hinged-box-falling-low-recovery.json": { + "bytes": 351322, + "sha256": "d929721d7992bcc71612f614b292b3ae38b2530fbdd6ca397ab518dfd3b064d9" + }, + "trials/hinged-box-falling-low-recovery.model.json": { + "bytes": 84485, + "sha256": "502b04f3f32c120454dae278ff650738b8c1a7d63752f926d28db6f4e5b7d2e4" + }, + "trials/hinged-box-falling-low-recovery.motion.json": { + "bytes": 579373, + "sha256": "1dd1fa68c116cc781e64762522842f2f62fc252ed5cb44725e277c07c8515864" + }, + "trials/hinged-box-falling-medium-baseline.json": { + "bytes": 378284, + "sha256": "d2ea10fb0540da3e7107a61d46239fba6973a0914dcafc6fe732f98f715edd68" + }, + "trials/hinged-box-falling-medium-baseline.model.json": { + "bytes": 84485, + "sha256": "db32eeefc4254b508548658a11b26148c477fcae433fcfe3de2cec95ad6dcce9" + }, + "trials/hinged-box-falling-medium-baseline.motion.json": { + "bytes": 595325, + "sha256": "9591175c1ef17564ee3b4b50ab41b2f11bf8108711191c8b783e7c86a12e8b30" + }, + "trials/hinged-box-falling-medium-recovery.json": { + "bytes": 350286, + "sha256": "8d292c66c0f86e3354229dd42c046a7c111f4829ffef4381a717e86335fe1705" + }, + "trials/hinged-box-falling-medium-recovery.model.json": { + "bytes": 84485, + "sha256": "db32eeefc4254b508548658a11b26148c477fcae433fcfe3de2cec95ad6dcce9" + }, + "trials/hinged-box-falling-medium-recovery.motion.json": { + "bytes": 579121, + "sha256": "d6eb98daaa495caba5f41adcf565d595085f3615bd9de1eb4c99139cd7c0484a" + }, + "trials/hinged-box-open-medium-baseline.json": { + "bytes": 336440, + "sha256": "7417fa0bc07bc3572b82e7eed5d45d3417f46085f92205d17d390a82a9ebeebd" + }, + "trials/hinged-box-open-medium-baseline.model.json": { + "bytes": 84485, + "sha256": "db32eeefc4254b508548658a11b26148c477fcae433fcfe3de2cec95ad6dcce9" + }, + "trials/hinged-box-open-medium-baseline.motion.json": { + "bytes": 578339, + "sha256": "cac66073112ea94bfbb765633bccdfe1d3292050d65dbd20b247cc8b25b7554a" + }, + "trials/hinged-box-open-medium-recovery.json": { + "bytes": 336443, + "sha256": "ff72ab4378862e9e665097f4ac8c9f1e87abdb92c5631817eb76b8c20454726f" + }, + "trials/hinged-box-open-medium-recovery.model.json": { + "bytes": 84485, + "sha256": "db32eeefc4254b508548658a11b26148c477fcae433fcfe3de2cec95ad6dcce9" + }, + "trials/hinged-box-open-medium-recovery.motion.json": { + "bytes": 578339, + "sha256": "cac66073112ea94bfbb765633bccdfe1d3292050d65dbd20b247cc8b25b7554a" + }, + "trials/hinged-box-transient-damped-baseline.json": { + "bytes": 336912, + "sha256": "87f31ed391d1800baab90172e3d956e25205409e075b3edf96bc4bdd24fb2edd" + }, + "trials/hinged-box-transient-damped-baseline.model.json": { + "bytes": 84485, + "sha256": "4154d047d9469b5f675e9ab9ce337fb291c3dac6f76683f04110d0d196f5b5e6" + }, + "trials/hinged-box-transient-damped-baseline.motion.json": { + "bytes": 578344, + "sha256": "41ddce38a3ae569dae3d10feb400d9ddbe81f182b4f1fdace761891aa735037c" + }, + "trials/hinged-box-transient-damped-recovery.json": { + "bytes": 337350, + "sha256": "c19f1debb7d7ca5b912bf98e2366bc1979714d7183c1a692fc0389204c318cba" + }, + "trials/hinged-box-transient-damped-recovery.model.json": { + "bytes": 84485, + "sha256": "4154d047d9469b5f675e9ab9ce337fb291c3dac6f76683f04110d0d196f5b5e6" + }, + "trials/hinged-box-transient-damped-recovery.motion.json": { + "bytes": 578468, + "sha256": "a77d51b74032f337c6f4d2f3749498a12f676fa00899ad0fc35470811f4f4bcd" + }, + "trials/tool-reach-reach-heldout-heavy-baseline.json": { + "bytes": 491389, + "sha256": "74e232b72a66123f8d9e8692ed07ccad713d3af207ac2e0fdac942ca6a8de290" + }, + "trials/tool-reach-reach-heldout-heavy-baseline.model.json": { + "bytes": 82346, + "sha256": "84200882f350950907956d74f41b8bc11cdb19538084b662864d146f37b81089" + }, + "trials/tool-reach-reach-heldout-heavy-baseline.motion.json": { + "bytes": 524579, + "sha256": "a2adb7aae0ee97278b5dced0ca4aa9d14fa9f8d084b0a644aa54d3faa417c3de" + }, + "trials/tool-reach-reach-heldout-heavy-recovery.json": { + "bytes": 1251298, + "sha256": "9739b777acaa51c896e09a99fa79a3320e3fdf64966627af7d0fdc6e7a3dcffa" + }, + "trials/tool-reach-reach-heldout-heavy-recovery.model.json": { + "bytes": 83978, + "sha256": "3f228c39e72479fdbef1fc69e9df042f9f78e7843938ec52a2981ed4a639d5ed" + }, + "trials/tool-reach-reach-heldout-heavy-recovery.motion.json": { + "bytes": 1227208, + "sha256": "be8a55122135decd12ff09d29ec60ea6a5bccce0a7cf7514e9bc142e57ce5aba" + }, + "trials/tool-reach-reach-heldout-light-baseline.json": { + "bytes": 492723, + "sha256": "48223b1d29f4afd2f7881659d8254d6779791b4c86f6e52f44a18fdff389adf0" + }, + "trials/tool-reach-reach-heldout-light-baseline.model.json": { + "bytes": 82346, + "sha256": "5321cfa1314c36e6fffae6d33a03bce1a0a86dace4e3b890bbfdde97b1a7793a" + }, + "trials/tool-reach-reach-heldout-light-baseline.motion.json": { + "bytes": 524095, + "sha256": "a8100bfb734c25185579fffa9140a58f43a1512cc4a8d820299095d45e00e0d4" + }, + "trials/tool-reach-reach-heldout-light-recovery.json": { + "bytes": 1232315, + "sha256": "4129ea83f07efe0ebb0239487d338346fe38c59333150259aa0fe1ad5906636c" + }, + "trials/tool-reach-reach-heldout-light-recovery.model.json": { + "bytes": 83976, + "sha256": "cc2de52fc154d0f0ab1c76999abf0ee13d11e70ef202af78f146b90665ce13d9" + }, + "trials/tool-reach-reach-heldout-light-recovery.motion.json": { + "bytes": 1226411, + "sha256": "63559532670186990dc5b7e5325a227d8ad4c9ec0deea9aa995d757c0c6e630b" + }, + "trials/tool-reach-reach-heldout-offset-baseline.json": { + "bytes": 492899, + "sha256": "b5f704d3b007eb8eefa08f655280573c947dc808adbf608059ae42842accac8b" + }, + "trials/tool-reach-reach-heldout-offset-baseline.model.json": { + "bytes": 82346, + "sha256": "b5e258231af09c07ac58d23e12f7fa22731b8ce913ee7bc4b5fb7124761ceb2d" + }, + "trials/tool-reach-reach-heldout-offset-baseline.motion.json": { + "bytes": 524345, + "sha256": "c1b8becdf194ad9d9606b2b68e020849990618b46c2c5047dfca80333738a72c" + }, + "trials/tool-reach-reach-heldout-offset-recovery.json": { + "bytes": 1199586, + "sha256": "8fd7404972b2d9cacfb5630926d00924c76fc75edecfb0f0e888c08c41783883" + }, + "trials/tool-reach-reach-heldout-offset-recovery.model.json": { + "bytes": 83976, + "sha256": "dd21ab935e916129cd453047d6710f42e6e8c7fcc323d2bfd072ff7e14871a2b" + }, + "trials/tool-reach-reach-heldout-offset-recovery.motion.json": { + "bytes": 1222018, + "sha256": "ea84b82aaaee387ebddba61eeed5c72eec4092803b1873451dcae97a90f0d2e7" + }, + "trials/tool-reach-reach-heldout-short-baseline.json": { + "bytes": 492795, + "sha256": "001de985df57e687f792bc305711ed2b170175bf81b06e1ec996b25444c57d9a" + }, + "trials/tool-reach-reach-heldout-short-baseline.model.json": { + "bytes": 82346, + "sha256": "37e65b7e4689852ef559e5bde4c4b9a99a46088763a3e7ef219a5b6a08361a93" + }, + "trials/tool-reach-reach-heldout-short-baseline.motion.json": { + "bytes": 524423, + "sha256": "866202604bc54456c3a27964e60c5b83dc64956bb13684f62751668562220062" + }, + "trials/tool-reach-reach-heldout-short-recovery.json": { + "bytes": 93201, + "sha256": "2f5ddf697b29cd3c70a5267fc455bebf931ec5904bf57969bb407dda9918a420" + }, + "trials/tool-reach-reach-heldout-short-recovery.model.json": { + "bytes": 83976, + "sha256": "aeb21817c99c084a03614dcf64d2ef16d774a566f6628c5989a88c2b4bacc7db" + }, + "trials/tool-reach-reach-heldout-short-recovery.motion.json": { + "bytes": 96846, + "sha256": "10d0c59af9a192ae921b6292c33d467b6a07cf765d9f4dbd7d4777ad3fbb3db1" + } + } +} diff --git a/benchmarks/skill-prerequisites-20261013/protocol.json b/benchmarks/skill-prerequisites-20261013/protocol.json new file mode 100644 index 0000000..a6b34a8 --- /dev/null +++ b/benchmarks/skill-prerequisites-20261013/protocol.json @@ -0,0 +1,248 @@ +{ + "schema": "dvidia.skill-prerequisites/v1", + "scope": "Authored PiPER policies in native MuJoCo with synthetic rigid objects and privileged simulator observations. Browser replay uses recorded poses; no learned policy, hardware safety qualification or real-world transfer result.", + "split": "heldout", + "attempts": [ + { + "id": "hinged-box-open-medium-baseline", + "task": "hinged-box", + "policy": "baseline", + "case": { + "id": "open-medium", + "lid_angle_deg": 105.0, + "lid_velocity_rad_s": 0.0, + "lid_mass_kg": 0.18, + "hinge_damping": 0.04, + "split": "heldout" + } + }, + { + "id": "hinged-box-open-medium-recovery", + "task": "hinged-box", + "policy": "recovery", + "case": { + "id": "open-medium", + "lid_angle_deg": 105.0, + "lid_velocity_rad_s": 0.0, + "lid_mass_kg": 0.18, + "hinge_damping": 0.04, + "split": "heldout" + } + }, + { + "id": "hinged-box-falling-medium-baseline", + "task": "hinged-box", + "policy": "baseline", + "case": { + "id": "falling-medium", + "lid_angle_deg": 78.0, + "lid_velocity_rad_s": -0.15, + "lid_mass_kg": 0.18, + "hinge_damping": 0.04, + "split": "heldout" + } + }, + { + "id": "hinged-box-falling-medium-recovery", + "task": "hinged-box", + "policy": "recovery", + "case": { + "id": "falling-medium", + "lid_angle_deg": 78.0, + "lid_velocity_rad_s": -0.15, + "lid_mass_kg": 0.18, + "hinge_damping": 0.04, + "split": "heldout" + } + }, + { + "id": "hinged-box-falling-low-baseline", + "task": "hinged-box", + "policy": "baseline", + "case": { + "id": "falling-low", + "lid_angle_deg": 58.0, + "lid_velocity_rad_s": -0.25, + "lid_mass_kg": 0.1, + "hinge_damping": 0.02, + "split": "heldout" + } + }, + { + "id": "hinged-box-falling-low-recovery", + "task": "hinged-box", + "policy": "recovery", + "case": { + "id": "falling-low", + "lid_angle_deg": 58.0, + "lid_velocity_rad_s": -0.25, + "lid_mass_kg": 0.1, + "hinge_damping": 0.02, + "split": "heldout" + } + }, + { + "id": "hinged-box-transient-damped-baseline", + "task": "hinged-box", + "policy": "baseline", + "case": { + "id": "transient-damped", + "lid_angle_deg": 110.0, + "lid_velocity_rad_s": -0.35, + "lid_mass_kg": 0.2, + "hinge_damping": 0.06, + "split": "heldout" + } + }, + { + "id": "hinged-box-transient-damped-recovery", + "task": "hinged-box", + "policy": "recovery", + "case": { + "id": "transient-damped", + "lid_angle_deg": 110.0, + "lid_velocity_rad_s": -0.35, + "lid_mass_kg": 0.2, + "hinge_damping": 0.06, + "split": "heldout" + } + }, + { + "id": "tool-reach-reach-heldout-light-baseline", + "task": "tool-reach", + "policy": "baseline", + "case": { + "id": "reach-heldout-light", + "shoe_x": 0.705, + "shoe_y": -0.09, + "mass": 0.22, + "friction": 0.45, + "tool_length": 0.34, + "lateral_error": 0.025, + "split": "heldout" + } + }, + { + "id": "tool-reach-reach-heldout-light-recovery", + "task": "tool-reach", + "policy": "recovery", + "case": { + "id": "reach-heldout-light", + "shoe_x": 0.705, + "shoe_y": -0.09, + "mass": 0.22, + "friction": 0.45, + "tool_length": 0.34, + "lateral_error": 0.025, + "split": "heldout" + } + }, + { + "id": "tool-reach-reach-heldout-offset-baseline", + "task": "tool-reach", + "policy": "baseline", + "case": { + "id": "reach-heldout-offset", + "shoe_x": 0.725, + "shoe_y": -0.115, + "mass": 0.38, + "friction": 0.8, + "tool_length": 0.36, + "lateral_error": -0.075, + "split": "heldout" + } + }, + { + "id": "tool-reach-reach-heldout-offset-recovery", + "task": "tool-reach", + "policy": "recovery", + "case": { + "id": "reach-heldout-offset", + "shoe_x": 0.725, + "shoe_y": -0.115, + "mass": 0.38, + "friction": 0.8, + "tool_length": 0.36, + "lateral_error": -0.075, + "split": "heldout" + } + }, + { + "id": "tool-reach-reach-heldout-heavy-baseline", + "task": "tool-reach", + "policy": "baseline", + "case": { + "id": "reach-heldout-heavy", + "shoe_x": 0.735, + "shoe_y": -0.075, + "mass": 0.55, + "friction": 1.05, + "tool_length": 0.37, + "lateral_error": 0.035, + "split": "heldout" + } + }, + { + "id": "tool-reach-reach-heldout-heavy-recovery", + "task": "tool-reach", + "policy": "recovery", + "case": { + "id": "reach-heldout-heavy", + "shoe_x": 0.735, + "shoe_y": -0.075, + "mass": 0.55, + "friction": 1.05, + "tool_length": 0.37, + "lateral_error": 0.035, + "split": "heldout" + } + }, + { + "id": "tool-reach-reach-heldout-short-baseline", + "task": "tool-reach", + "policy": "baseline", + "case": { + "id": "reach-heldout-short", + "shoe_x": 0.72, + "shoe_y": -0.105, + "mass": 0.27, + "friction": 0.55, + "tool_length": 0.18, + "lateral_error": 0.015, + "split": "heldout" + } + }, + { + "id": "tool-reach-reach-heldout-short-recovery", + "task": "tool-reach", + "policy": "recovery", + "case": { + "id": "reach-heldout-short", + "shoe_x": 0.72, + "shoe_y": -0.105, + "mass": 0.27, + "friction": 0.55, + "tool_length": 0.18, + "lateral_error": 0.015, + "split": "heldout" + } + } + ], + "comparison": "Matched declared scene conditions. Tool baseline is a no-tool capability control; it is not a policy-only ablation.", + "split_scope": "Explicit parameter holdouts, not independent real-world reliability trials. No held-out tuning.", + "success_scope": "Task-specific completion. Safe abort, retrieval, and retained lift are reported separately.", + "timing_scope": "CPU wall time for native execution including initialization and recording; rendering, downloads and real sensor latency excluded.", + "source_commit": "756306a2beda60ac54567971626080a56227e781", + "implementation_sha256": { + "prerequisite_benchmark.py": "c78efb24263300c56f50413aa65333e4fbf1b99403aa816de9bf4cb5656a3811", + "hinged_shoebox.py": "9e9189b28bb0f97d699039168e8c5022df3afb34aadb0d9f8a04dc4592aaf2e9", + "tool_reach.py": "812072388b518fb11999dafddd15655f3c750fa84fe09047c55a78c2b509e68f", + "workstation.py": "2a6aa6686b5b273efcfb21156952df8ceca88d991674cd17df92f2dccc11b701", + "asset_library.py": "12520ca13b7806004be37a0d7e0d1e023c90410c1eba899296fdcd5b28fdc7f7", + "asset_catalog.json": "592f363389a96fef7f9223737aa72a2f1a74f400238924bf6790ec5bfd3302b7", + "robot_profiles.py": "fb90782a6a9979e282182118ae0e3e29d00f101255cc57378dd3f692672bb13d", + "prerequisite_lab.html": "7161523a9e3a1388dedf59d2a31344b8a6ae34f3fa5947365ea5b88bb6b56ee0", + "prerequisite_lab.js": "154eaaf2d938e2e24b660b674cb3fcc6b0b72c0ded3abd78d4c3393534eefb32", + "prerequisite_lab.bundle.js": "de099a1a2b9bf93564d28de4c6bd0511e86ca2ff58dc08c385a9b0c0a86f27e8" + } +} diff --git a/docs/prerequisite-simulations.md b/docs/prerequisite-simulations.md new file mode 100644 index 0000000..f1092ed --- /dev/null +++ b/docs/prerequisite-simulations.md @@ -0,0 +1,120 @@ +# Skill prerequisites: two small simulations + +The next step toward an installable skill is an explicit account of when the +action is possible, what can go wrong, and what a recovery actually achieves. +This pilot uses a native MuJoCo PiPER arm in two controlled environments: + +- A hinged shoe box tests a moving lid, a gripper in its closing path, and a + bounded withdrawal or retry. +- An out-of-reach shoe tests whether a reachable tool can change the scene so + that the shoe enters the arm's usable workspace, followed by a separate + retained-lift check. The rake is pre-mounted; the controller does not discover + or acquire it. The no-tool baseline is a capability control, not a policy-only + comparison. + +These are authored controllers and synthetic mechanical assumptions. They do +not contain learned weights, train a robot from footage, estimate properties +from a camera, or qualify a physical robot. The purpose is to make those later +comparisons executable and measurable. + +## One small contract + +Each environment should expose the current observation, accept a bounded robot +command, advance native physics, and return the resulting observation and +events. The outcome scorer should remain separate from the policy. A visible +controller phase is useful for inspection but is not evidence of task success. + +Record the observation, the requested command, what was applied, and the next +observation. Keep interventions and human hints distinct from autonomous +decisions. Mark simulator ground truth as such; a contact force supplied by +MuJoCo is not a physical tactile measurement. + +The scene owns object motion. After reset, policies must not teleport the shoe, +weld it to the arm, or apply an undisclosed object force to manufacture success. +Any attached tool, pre-established grasp, or externally triggered lid release +must be stated as part of the initial conditions or intervention protocol. + +## What the benchmark must preserve + +| Question | Evidence | +| --- | --- | +| Did the task finish? | An independent geometric and temporal completion condition, not a policy phase name. | +| Was a hazard avoided? | No disallowed contact over the relevant physics steps; ending outside the hazard is insufficient. | +| Did a recovery work? | A recorded failure or risk trigger, the issued recovery, and the subsequent measured result. | +| Was the tool necessary? | Matched direct-action or no-tool controls, with the same initial scene and task deadline. | +| What remains impossible? | Unsuitable-tool or unreachable conditions retained as failed tasks or explicit deferrals. | +| How fast was it? | Simulated task time, computation time and policy decision time reported separately. | +| Does it generalize? | A frozen confirmation cohort with new parameter combinations after development tuning ends. | + +Success, recovery, avoidance and correct refusal are different outcomes. A +refusal can be appropriate while still counting as an unfinished task. The +publication should show both, without increasing the completion denominator +after observing the results or removing difficult cases. + +Brief contacts need physics-step aggregation or event records. Recording only +the final contact at each control interval can miss an impact between samples. +Report peak normal force, contact duration or impulse where implemented, with +their units and sampling interval. They are simulated contact quantities, not +validated injury thresholds or measured material damage. + +CPU measurements must identify the tested machine, engine version, timed +region, cold versus warm setup, and timing tails. Physics timestep is simulated +time; it is not a measured camera-to-actuator latency. No universal minimum +hardware requirement follows from one successful laptop run. + +## Evidence before release + +Freeze the scenario matrix and implementation hashes before the confirmation +run. Keep every planned attempt, failure and computation overrun. Bind the +results to a source revision, engine version, robot asset revision, scene +parameters and licenses. A new policy tuned after that run needs a fresh +confirmation cohort; the old failures remain evidence. + +The new release belongs in its own versioned namespace. GitHub should contain +the runnable code and compact benchmark receipts. Hugging Face and the research +site should link to the same frozen artifacts, with a clear distinction between +a recorded replay and a live physics environment. Old workstation results and +their licenses remain intact. + +Original DVIDIA code and synthetic assets are MIT. Redistributed PiPER model +assets retain their upstream MIT notice. MuJoCo retains Apache-2.0 and its +dependency notices. Any replay renderer and bundled font need their respective +notices. Research writing on the DVIDIA research site is CC BY 4.0. + +## Run fresh native attempts + +Use the exact source revision identified by the publication. From that checkout: + +```sh +python3.12 -m venv .venv +.venv/bin/python -m pip install '.[arm]' +.venv/bin/dvidia-robot-sim fetch piper --output runs/robot-assets +.venv/bin/dvidia-prerequisites --assets runs/robot-assets \ + --output runs/my-prerequisites --split development +.venv/bin/python -m http.server 8000 --bind 127.0.0.1 \ + --directory runs/my-prerequisites +``` + +Open `http://127.0.0.1:8000/` to inspect the recorded replay. The benchmark has +already run in native Python; moving the replay timeline does not run physics. +Use `--task hinged-box` or `--task tool-reach` to run just one environment. +`--split heldout` selects the frozen parameter holdouts. A fresh run is a +reproduction of that cohort, not new independent confirmation evidence. Use +`--source-commit FULL_GIT_SHA` to identify the checked-out source in your receipt. +The output directory must not already exist. + +On Windows use the virtual environment's `Scripts` executables and place each +continued command on one line. Installing dependencies and fetching the pinned +arm assets needs a network connection. Native simulation and replay can run +locally after those files have been provisioned. The replay needs WebGL2; the +native benchmark needs the optional MuJoCo dependency and a CPU. These are +dependency requirements, not measured minimum hardware specifications. + +The export contains a small `benchmark.json` index, the frozen `protocol.json`, +every full trial JSON, geometry and recorded motion, local viewer code, license +notices and `integrity.json`. Dense native contact traces stay in the full trial +receipts so that the initial viewer does not download every physics tick. +Failed attempts remain in the index and the sealed inventory. + +Measured outcomes and immutable publication links will be added after review. +The protocol above does not itself claim successful task completion. diff --git a/publishing/huggingface/publish_prerequisites.py b/publishing/huggingface/publish_prerequisites.py new file mode 100644 index 0000000..78876b0 --- /dev/null +++ b/publishing/huggingface/publish_prerequisites.py @@ -0,0 +1,401 @@ +"""Append a sealed prerequisites release without replacing historical artifacts. + +snapshot is read-only; stage/check are offline. Publishing needs an explicit +source/results/QA gate and retains a complete Git/LFS inventory of the parent. +Credentials use the existing in-memory macOS Keychain adapter only. +""" +from __future__ import annotations + +import argparse +from hashlib import sha1, sha256 +import json +from pathlib import Path, PurePosixPath +import re +import sys +import zlib + +from publish import PublicationError, checked_remote, client, verified_downloads + +REPO_ID = 'Dvidia/robot-simulation-lab' +NAMESPACE = 'prerequisites/v01' +ROOT_FILES = {'index.html', 'README.md', 'provenance.json'} +SHA = re.compile(r'[a-f0-9]{40}') +MAX_FILE = 32 * 1024 * 1024 +MAX_TOTAL = 192 * 1024 * 1024 +MAX_DECODED = 128 * 1024 * 1024 +MAX_FILES = 256 + + +def encoded(value): + return (json.dumps(value, indent=2, allow_nan=False) + '\n').encode() + + +def record(raw): + return {'bytes': len(raw), 'sha256': sha256(raw).hexdigest()} + + +def plain(path): + path = Path(path).absolute() + if any(p.is_symlink() for p in (path, *path.parents)): + raise PublicationError('Publication paths may not contain symlinks.') + return path + + +def read(path, limit=MAX_FILE): + path = plain(path) + if not path.is_file() or path.stat().st_size > limit: + raise PublicationError('Expected a bounded plain publication file.') + with path.open('rb') as stream: + raw = stream.read(limit + 1) + if len(raw) > limit: + raise PublicationError('Publication file exceeds its size bound.') + return raw + + +def path_name(name): + if (type(name) is not str or not name or '\\' in name + or re.search(r'[\x00-\x20\x7f]', name)): + raise PublicationError('Invalid artifact path.') + path = PurePosixPath(name) + if (path.is_absolute() or path.as_posix() != name + or any(re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.-]*', part) is None for part in path.parts)): + raise PublicationError('Artifact paths must be plain relative names.') + if path.suffix not in {'.html', '.js', '.json', '.txt', '.md', '.png', '.jpg', '.svg', '.bin', '.gz', '.xml'} and path.name != 'LICENSE': + raise PublicationError('Unsupported prerequisites artifact type.') + if path.suffix == '.gz' and not name.endswith(('.json.gz', '.bin.gz')): + raise PublicationError('Only bounded JSON or binary gzip artifacts are allowed.') + return path + + +def inspect_bytes(name, raw): + path_name(name) + decoded = raw + if name.endswith('.gz'): + decoder = zlib.decompressobj(16 + zlib.MAX_WBITS) + try: + decoded = decoder.decompress(raw, MAX_DECODED + 1) + except zlib.error as exc: + raise PublicationError('Invalid compressed artifact.') from exc + if len(decoded) > MAX_DECODED or not decoder.eof or decoder.unused_data or decoder.unconsumed_tail: + raise PublicationError('Compressed artifact exceeds its bound or contains trailing data.') + candidates = [raw, decoded] + if name.endswith(('.json', '.json.gz')): + try: + value = json.loads(decoded, parse_constant=lambda _: (_ for _ in ()).throw(ValueError())) + candidates.append(json.dumps(value, ensure_ascii=False, allow_nan=False).encode()) + except (ValueError, UnicodeError, RecursionError) as exc: + raise PublicationError('Invalid finite JSON artifact.') from exc + if any(re.search(rb'hf_[A-Za-z0-9]{30,}', data) or b'/Users/roguedev/' in data for data in candidates): + raise PublicationError('Possible credential or private path in artifact.') + + +def inventory(root): + root = plain(root) + if not root.is_dir(): + raise PublicationError('Expected a plain artifact directory.') + payload, total = {}, 0 + for path in sorted(root.rglob('*')): + plain(path) + if path.is_dir(): + continue + name = path.relative_to(root).as_posix() + raw = read(path) + inspect_bytes(name, raw) + payload[name] = raw + total += len(raw) + if len(payload) > MAX_FILES or total > MAX_TOTAL: + raise PublicationError('Prerequisites release exceeds its publication budget.') + return payload + + +def check_export(root, source_commit=None): + payload = inventory(root) + if not {'index.html', 'benchmark.json', 'protocol.json', 'integrity.json'} <= payload.keys(): + raise PublicationError('Missing benchmark, protocol, viewer or integrity seal.') + seal = json.loads(payload['integrity.json']) + if seal.get('files') != {name: record(raw) for name, raw in payload.items() if name != 'integrity.json'}: + raise PublicationError('Release inventory or bytes differ from the integrity seal.') + protocol, benchmark = (json.loads(payload[name]) for name in ('protocol.json', 'benchmark.json')) + source = benchmark.get('source', {}) + if (protocol.get('schema') != 'dvidia.skill-prerequisites/v1' + or benchmark.get('schema') != protocol['schema'] + or SHA.fullmatch(protocol.get('source_commit', '') or '') is None + or source.get('commit') != protocol['source_commit'] + or (source_commit is not None and source['commit'] != source_commit) + or source.get('protocol_sha256') != record(payload['protocol.json'])['sha256'] + or benchmark.get('split') != protocol.get('split') + or benchmark.get('learned_policy') is not False or benchmark.get('hardware_validated') is not False): + raise PublicationError('Source, protocol and simulation-only scope must agree.') + planned, measured = protocol.get('attempts'), benchmark.get('attempts') + if (type(planned) is not list or type(measured) is not list or not 1 <= len(planned) <= 100 + or len(measured) != len(planned) or len({row['id'] for row in planned}) != len(planned)): + raise PublicationError('Every planned attempt must occur exactly once.') + for expected, actual in zip(planned, measured): + if (any(actual.get(name) != expected.get(name) for name in ('id', 'task', 'policy', 'case')) + or type(actual.get('valid')) is not bool or type(actual.get('success')) is not bool + or (actual['success'] and not actual['valid'])): + raise PublicationError('Measured attempts differ from the frozen protocol.') + name = 'trials/' + actual['id'] + '.json' + receipt = json.loads(payload[name]) if name in payload else None + if type(receipt) is not dict: + raise PublicationError('Complete attempt receipts must match the benchmark.') + trace = receipt.pop('native_trace', None) + if trace is not None: + if (type(trace) is not list or len(trace) > 100000 + or any(type(row) is not list or not 1 <= len(row) <= 64 + or any(type(value) not in (int, float) for value in row) for row in trace) + or any(b[0] <= a[0] for a, b in zip(trace, trace[1:]))): + raise PublicationError('Native trace must contain bounded numeric observations in time order.') + if receipt != actual: + raise PublicationError('Complete attempt receipts must match the benchmark.') + return payload + + +def git_blob(raw): + return sha1(b'blob ' + str(len(raw)).encode() + b'\0' + raw).hexdigest() + + +def tree(api, revision): + result = {} + for item in api.list_repo_tree(REPO_ID, repo_type='space', revision=revision, recursive=True): + if not hasattr(item, 'blob_id'): + continue + lfs = getattr(item, 'lfs', None) + result[item.path] = {'blob': item.blob_id, 'size': item.size, + 'lfs_sha256': (lfs.get('sha256') if isinstance(lfs, dict) else getattr(lfs, 'sha256', None)) if lfs else None} + return result + + +def public_bytes(name, revision, limit=MAX_FILE): + from huggingface_hub import hf_hub_download + # Hub cache snapshots are symlinks owned by the SDK, never upload inputs. + path = Path(hf_hub_download(REPO_ID, name, repo_type='space', revision=revision, token=False)) + with path.open('rb') as stream: + raw = stream.read(limit + 1) + if len(raw) > limit: + raise PublicationError('Public artifact exceeds its download bound.') + return raw + + +def matches_tree(raw, entry): + digest = entry.get('lfs_sha256') + return len(raw) == entry['size'] and (sha256(raw).hexdigest() == digest if digest else git_blob(raw) == entry['blob']) + + +def snapshot(output, parent_commit): + if SHA.fullmatch(parent_commit) is None: + raise PublicationError('Snapshot requires the exact reviewed parent commit.') + destination = plain(output) + destination.mkdir(parents=True, exist_ok=False) + # Public inspection needs no publisher credential. + from huggingface_hub import HfApi + api = HfApi(token=False) + info = api.repo_info(REPO_ID, repo_type='space') + checked_remote(info, 'space') + if info.sha != parent_commit: + raise PublicationError('Space moved; review its new parent before staging.') + previous = tree(api, parent_commit) + if any(name == NAMESPACE or name.startswith(NAMESPACE + '/') for name in previous): + raise PublicationError('This release namespace already exists.') + if not (ROOT_FILES | {'.gitattributes'}) <= previous.keys(): + raise PublicationError('Existing Space root files are incomplete.') + for name in ROOT_FILES | {'.gitattributes'}: + raw = public_bytes(name, parent_commit) + if not matches_tree(raw, previous[name]): + raise PublicationError('Public root file differs from its pinned Git/LFS entry.') + (destination / name).write_bytes(raw) + (destination / 'snapshot.json').write_bytes(encoded({'schema': 'dvidia.prerequisites-parent/v1', + 'repo_id': REPO_ID, 'parent_commit': parent_commit, 'tree': previous})) + return {'parent_commit': parent_commit, 'retained_tree_entries': len(previous)} + + +def updated_roots(parent, source_commit, seal): + index = parent['index.html'].decode() + marker = '
' + if index.count(marker) != 1: + raise PublicationError('Expected one recorded-replay section in the existing landing page.') + card = ('

' + 'Before a skill can succeed.

Explore a hinged shoe box and an out-of-reach shoe. ' + 'Recorded native MuJoCo attempts retain failed access, withdrawal and tool-assisted reach. ' + 'Authored policies; synthetic properties; no physical robot qualification.

' + 'Inspect both simulations and every result →
') + index = index.replace(marker, card + marker) + readme = parent['README.md'] + ('\n\n## Skill prerequisites v0.1\n\n' + '[Explore both simulations](prerequisites/v01/index.html). Recorded replays of native ' + 'MuJoCo runs; run the open-source Python environments locally for fresh physics. ' + 'The rake is mounted, not autonomously acquired. Lid tests measure access and recovery, ' + 'not shoe extraction. Failures and full benchmark evidence remain visible.\n\n' + f'[Pinned source](https://github.com/Dvidia-Inference/dvidia-training/tree/{source_commit}) · ' + '[Research](https://research.dvidia.org/papers/skill-prerequisites-v01/)\n').encode() + provenance = json.loads(parent['provenance.json']) + if 'prerequisites' in provenance: + raise PublicationError('Prerequisites provenance already exists.') + provenance['prerequisites'] = {'path': NAMESPACE, 'source_commit': source_commit, + 'integrity': record(seal), 'browser_mode': 'recorded-native-replay', + 'learned_policy': False, 'physical_robot_ready': False} + return {'index.html': index.encode(), 'README.md': readme, 'provenance.json': encoded(provenance)} + + +def stage(export, parent, output, source_commit): + if SHA.fullmatch(source_commit) is None: + raise PublicationError('An exact source commit is required.') + parent, destination, export = plain(parent), plain(output), plain(export) + if any(destination == source or source in destination.parents or destination in source.parents + for source in (parent, export)): + raise PublicationError('Staging output must be outside both input trees.') + baseline = json.loads(read(parent / 'snapshot.json', 2 * 1024 * 1024)) + if baseline.get('repo_id') != REPO_ID or SHA.fullmatch(baseline.get('parent_commit', '')) is None: + raise PublicationError('Unexpected parent snapshot.') + previous = baseline['tree'] + if any(name.startswith(NAMESPACE + '/') for name in previous): + raise PublicationError('Prerequisites namespace must be new.') + parent_files = {name: read(parent / name) for name in ROOT_FILES} + attributes = read(parent / '.gitattributes', 65536) + if any(not matches_tree(raw, previous[name]) for name, raw in {**parent_files, '.gitattributes': attributes}.items()): + raise PublicationError('Pinned parent root bytes changed.') + release = check_export(export, source_commit) + payload = {NAMESPACE + '/' + name: raw for name, raw in release.items()} + payload.update(updated_roots(parent_files, source_commit, release['integrity.json'])) + if set(payload) & set(previous) != ROOT_FILES: + raise PublicationError('Only the three root pointers may replace existing files.') + for name, raw in payload.items(): + inspect_bytes(name, raw) + destination.mkdir(parents=True, exist_ok=False) + for name, raw in payload.items(): + path = destination / 'payload' / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(raw) + (destination / 'parent-gitattributes.txt').write_bytes(attributes) + plan = {'schema': 'dvidia.prerequisites-publication/v1', 'repo_id': REPO_ID, + 'namespace': NAMESPACE, 'source_commit': source_commit, 'parent_commit': baseline['parent_commit'], + 'parent_tree': previous, 'parent_roots': {name: record(raw) for name, raw in parent_files.items()}, + 'parent_attributes': record(attributes), 'files': {name: record(raw) for name, raw in sorted(payload.items())}} + (destination / 'plan.json').write_bytes(encoded(plan)) + check(destination / 'plan.json') + return {'plan': str(destination / 'plan.json'), 'files': len(payload), 'bytes': sum(map(len, payload.values()))} + + +def check(path): + path = plain(path) + plan = json.loads(read(path, 2 * 1024 * 1024)) + if (plan.get('schema') != 'dvidia.prerequisites-publication/v1' or plan.get('repo_id') != REPO_ID + or plan.get('namespace') != NAMESPACE + or any(SHA.fullmatch(plan.get(name, '')) is None for name in ('source_commit', 'parent_commit'))): + raise PublicationError('Unexpected prerequisites publication plan.') + payload = inventory(path.parent / 'payload') + if plan.get('files') != {name: record(raw) for name, raw in payload.items()}: + raise PublicationError('Payload changed after staging.') + if (set(payload) & set(plan['parent_tree']) != ROOT_FILES + or any(name not in ROOT_FILES and not name.startswith(NAMESPACE + '/') for name in payload) + or any(name.startswith(NAMESPACE + '/') for name in plan['parent_tree'])): + raise PublicationError('Publication may only append the fresh namespace and change its three root pointers.') + attributes = read(path.parent / 'parent-gitattributes.txt', 65536) + if record(attributes) != plan['parent_attributes'] or not matches_tree(attributes, plan['parent_tree']['.gitattributes']): + raise PublicationError('Parent metadata changed.') + check_export(path.parent / 'payload' / NAMESPACE, plan['source_commit']) + return plan, payload + + +def check_gate(gate, plan): + if (gate.get('source_commit') != plan['source_commit'] + or any(gate.get(name) is not True for name in ('tests_passed', 'browser_qa_passed', 'benchmark_reviewed')) + or gate.get('benchmark_sha256') != plan['files'][NAMESPACE + '/benchmark.json']['sha256'] + or gate.get('integrity_sha256') != plan['files'][NAMESPACE + '/integrity.json']['sha256']): + raise PublicationError('Publication requires source-bound benchmark, tests and browser acceptance.') + + +def verify_tree(before, after, payload, old_attributes, new_attributes): + if set(after) != set(before) | set(payload): + raise PublicationError('Publication added or removed unexpected paths.') + unchanged = set(before) - set(payload) - {'.gitattributes'} + if any(before[name] != after[name] for name in unchanged): + raise PublicationError('Historical Git/LFS entry changed.') + if not matches_tree(new_attributes, after['.gitattributes']) or not new_attributes.startswith(old_attributes): + raise PublicationError('Existing Hub metadata changed.') + additions = new_attributes[len(old_attributes):].splitlines() + allowed = {(name + ' filter=lfs diff=lfs merge=lfs -text').encode() for name in payload} + if len(additions) != len(set(additions)) or any(line not in allowed for line in additions): + raise PublicationError('Unexpected Hub metadata addition.') + return len(unchanged) + + +def publish(path, gate_path): + path = plain(path) + plan, payload = check(path) + gate = json.loads(read(gate_path, 1024 * 1024)) + check_gate(gate, plan) + api, token = client(path.parent / 'publisher-cache') + if any(token.encode() in raw for raw in payload.values()): + raise PublicationError('Credential occurs in upload bytes.') + if 'Dvidia' not in {org.get('name') for org in api.whoami().get('orgs', [])}: + raise PublicationError('Publisher is not a member of the intended organization.') + pending_path = plain(path.parent / 'pending.json') + plan_hash = record(read(path, 2 * 1024 * 1024))['sha256'] + if pending_path.exists(): + pending = json.loads(read(pending_path)) + if pending.get('plan_sha256') != plan_hash or SHA.fullmatch(pending.get('commit', '')) is None: + raise PublicationError('Retry receipt belongs to another plan.') + revision = pending['commit'] + else: + info = api.repo_info(REPO_ID, repo_type='space') + checked_remote(info, 'space') + if info.sha != plan['parent_commit'] or tree(api, info.sha) != plan['parent_tree']: + raise PublicationError('Space changed after the reviewed parent snapshot.') + from huggingface_hub import CommitOperationAdd + result = api.create_commit(REPO_ID, repo_type='space', parent_commit=plan['parent_commit'], + operations=[CommitOperationAdd(path_in_repo=name, path_or_fileobj=raw) for name, raw in payload.items()], + commit_message='Publish two native skill-prerequisite simulations and complete benchmark evidence') + revision = result.oid + pending_path.write_bytes(encoded({'commit': revision, 'plan_sha256': plan_hash})) + after = tree(api, revision) + attributes = public_bytes('.gitattributes', revision, 65536) + unchanged = verify_tree(plan['parent_tree'], after, payload, + read(path.parent / 'parent-gitattributes.txt', 65536), attributes) + row = {'repo_id': REPO_ID, 'repo_type': 'space', 'files': [ + {'path': name, **expected} for name, expected in plan['files'].items()]} + verified_downloads(row, revision, False) + receipt = {'repo_id': REPO_ID, 'commit': revision, 'parent_commit': plan['parent_commit'], + 'source_commit': plan['source_commit'], 'plan_sha256': plan_hash, + 'verified_public_files': len(payload), 'unchanged_historical_tree_entries': unchanged, + 'files': plan['files'], 'gate': gate} + plain(path.parent / 'after-tree.json').write_bytes(encoded(after)) + plain(path.parent / 'publication-receipt.json').write_bytes(encoded(receipt)) + return receipt + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest='command', required=True) + command = commands.add_parser('snapshot') + command.add_argument('--output', required=True, type=Path) + command.add_argument('--parent-commit', required=True) + command = commands.add_parser('stage') + for name in ('export', 'parent', 'output'): + command.add_argument('--' + name, required=True, type=Path) + command.add_argument('--source-commit', required=True) + for name in ('check', 'publish'): + command = commands.add_parser(name) + command.add_argument('plan', type=Path) + if name == 'publish': + command.add_argument('--gate', required=True, type=Path) + args = parser.parse_args() + try: + if args.command == 'snapshot': + result = snapshot(args.output, args.parent_commit) + elif args.command == 'stage': + result = stage(args.export, args.parent, args.output, args.source_commit) + elif args.command == 'check': + plan, payload = check(args.plan) + result = {'files': len(payload), 'source_commit': plan['source_commit']} + else: + result = publish(args.plan, args.gate) + print(json.dumps(result, indent=2)) + except Exception as exc: + # SDK exceptions may include credential-bearing request details. + print(str(exc) if isinstance(exc, PublicationError) else 'Prerequisites publication stopped; raw error suppressed.', file=sys.stderr) + return 1 + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/publishing/huggingface/test_publish_prerequisites.py b/publishing/huggingface/test_publish_prerequisites.py new file mode 100644 index 0000000..d614c5e --- /dev/null +++ b/publishing/huggingface/test_publish_prerequisites.py @@ -0,0 +1,180 @@ +"""Publication boundaries preserve historical evidence and reject stale releases.""" +import gzip +import json +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch + +import publish_prerequisites as publisher + + +class PrerequisitesPublicationTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name).resolve() + self.parent, self.export = self.root / 'parent', self.root / 'export' + self.parent.mkdir() + self.export.mkdir() + self.original = {'index.html': b'
old evidence
', + 'README.md': b'---\nsdk: static\n---\nOld release\n', + 'provenance.json': b'{"old_evidence":{"preserve":true}}\n', + '.gitattributes': b'*.bin filter=lfs diff=lfs merge=lfs -text\n'} + self.tree = {name: {'blob': publisher.git_blob(raw), 'size': len(raw), 'lfs_sha256': None} + for name, raw in self.original.items()} + self.tree['workstation/v01/geometry.bin'] = {'blob': 'd' * 40, 'size': 2000000, 'lfs_sha256': 'e' * 64} + for name, raw in self.original.items(): + (self.parent / name).write_bytes(raw) + self.save_snapshot() + case = {'id': 'hinge-one', 'task': 'hinged-box', 'policy': 'baseline', 'case': {'id': 'one'}} + measured = {**case, 'success': False, 'valid': True} + protocol = publisher.encoded({'schema': 'dvidia.skill-prerequisites/v1', 'source_commit': 'b' * 40, + 'split': 'heldout', 'attempts': [case]}) + benchmark = publisher.encoded({'schema': 'dvidia.skill-prerequisites/v1', + 'source': {'commit': 'b' * 40, 'protocol_sha256': publisher.record(protocol)['sha256']}, + 'split': 'heldout', 'learned_policy': False, 'hardware_validated': False, 'attempts': [measured]}) + self.release = {'index.html': b'

Recorded native attempts

', + 'benchmark.json': benchmark, 'protocol.json': protocol, 'trials/hinge-one.json': publisher.encoded(measured), + 'motion.bin.gz': gzip.compress(b'native motion', mtime=0), 'LICENSE': b'MIT test fixture'} + self.save_release() + + def save_snapshot(self): + (self.parent / 'snapshot.json').write_bytes(publisher.encoded({'schema': 'dvidia.prerequisites-parent/v1', + 'repo_id': publisher.REPO_ID, 'parent_commit': 'a' * 40, 'tree': self.tree})) + + def save_release(self): + for name, raw in self.release.items(): + (self.export / name).parent.mkdir(parents=True, exist_ok=True) + (self.export / name).write_bytes(raw) + (self.export / 'integrity.json').write_bytes(publisher.encoded({'files': { + name: publisher.record(raw) for name, raw in self.release.items()}})) + + def stage(self): + return publisher.stage(self.export, self.parent, self.root / 'staged', 'b' * 40) + + def test_delta_retains_history_and_appends_honest_root_pointers(self): + result = self.stage() + plan, payload = publisher.check(result['plan']) + self.assertEqual(plan['parent_tree'], self.tree) + self.assertEqual(set(payload) & set(self.tree), publisher.ROOT_FILES) + self.assertEqual(len(payload), len(self.release) + 4) + self.assertIn(self.original['README.md'], payload['README.md']) + self.assertIn(b'Recorded native MuJoCo', payload['index.html']) + self.assertIn(b'rake is mounted', payload['README.md']) + provenance = json.loads(payload['provenance.json']) + self.assertEqual(provenance['old_evidence'], {'preserve': True}) + self.assertFalse(provenance['prerequisites']['learned_policy']) + + def test_payload_tampering_after_stage_is_rejected(self): + result = self.stage() + (self.root / 'staged/payload/prerequisites/v01/benchmark.json').write_bytes(b'{"success":true}') + with self.assertRaisesRegex(publisher.PublicationError, 'Payload changed'): + publisher.check(result['plan']) + + def test_resealed_omitted_failure_or_changed_source_is_rejected(self): + benchmark = json.loads(self.release['benchmark.json']) + benchmark['attempts'] = [] + self.release['benchmark.json'] = publisher.encoded(benchmark) + self.save_release() + with self.assertRaisesRegex(publisher.PublicationError, 'Every planned attempt'): + self.stage() + benchmark['source']['commit'] = 'c' * 40 + self.release['benchmark.json'] = publisher.encoded(benchmark) + self.save_release() + with self.assertRaisesRegex(publisher.PublicationError, 'Source, protocol'): + self.stage() + + def test_only_dense_native_trace_can_be_omitted_from_summary_index(self): + receipt = json.loads(self.release['trials/hinge-one.json']) + receipt['native_trace'] = [[0., .1], [.002, .2]] + self.release['trials/hinge-one.json'] = publisher.encoded(receipt) + self.save_release() + publisher.check_export(self.export, 'b' * 40) + receipt['hidden_events'] = ['unreported failure'] + self.release['trials/hinge-one.json'] = publisher.encoded(receipt) + self.save_release() + with self.assertRaisesRegex(publisher.PublicationError, 'Complete attempt receipts'): + publisher.check_export(self.export, 'b' * 40) + + def test_unsealed_added_file_is_rejected(self): + (self.export / 'extra.json').write_bytes(b'{}') + with self.assertRaisesRegex(publisher.PublicationError, 'integrity seal'): + self.stage() + + def test_symlink_file_and_symlink_directory_are_rejected(self): + (self.export / 'shortcut.json').symlink_to(self.export / 'benchmark.json') + with self.assertRaisesRegex(publisher.PublicationError, 'symlinks'): + self.stage() + (self.export / 'shortcut.json').unlink() + (self.export / 'nested').symlink_to(self.parent, target_is_directory=True) + with self.assertRaisesRegex(publisher.PublicationError, 'symlinks'): + self.stage() + + def test_private_path_in_escaped_compressed_json_is_rejected(self): + raw = gzip.compress(b'{"path":"\\u002fUsers/roguedev/private"}', mtime=0) + with self.assertRaisesRegex(publisher.PublicationError, 'private path'): + publisher.inspect_bytes('attempts/one.json.gz', raw) + + def test_bounded_decompression_and_trailing_members(self): + with patch.object(publisher, 'MAX_DECODED', 20): + with self.assertRaisesRegex(publisher.PublicationError, 'exceeds its bound'): + publisher.inspect_bytes('motion.bin.gz', gzip.compress(b'x' * 21)) + with self.assertRaisesRegex(publisher.PublicationError, 'trailing data'): + publisher.inspect_bytes('motion.bin.gz', gzip.compress(b'x') + gzip.compress(b'y')) + + def test_invalid_paths_and_nonfinite_json(self): + for name in ('../secret.json', '/file.json', 'a/../b.json', 'a//b.json', '.secret', 'a\\b.json', + 'a\nb.json', 'secret.py', '%2e%2e/secret.json', 'index.html?x.json'): + with self.subTest(name=name), self.assertRaises(publisher.PublicationError): + publisher.path_name(name) + with self.assertRaisesRegex(publisher.PublicationError, 'finite JSON'): + publisher.inspect_bytes('benchmark.json', b'{"value":NaN}') + + def test_parent_root_tampering_and_existing_namespace_are_rejected(self): + (self.parent / 'README.md').write_bytes(b'changed') + with self.assertRaisesRegex(publisher.PublicationError, 'root bytes changed'): + self.stage() + (self.parent / 'README.md').write_bytes(self.original['README.md']) + self.tree['prerequisites/v01/old.json'] = {'blob': 'c' * 40, 'size': 2, 'lfs_sha256': None} + self.save_snapshot() + with self.assertRaisesRegex(publisher.PublicationError, 'must be new'): + self.stage() + + def test_gate_binds_source_benchmark_integrity_and_all_checks(self): + plan, _ = publisher.check(self.stage()['plan']) + gate = {'source_commit': plan['source_commit'], 'tests_passed': True, 'browser_qa_passed': True, + 'benchmark_reviewed': True, + 'benchmark_sha256': plan['files']['prerequisites/v01/benchmark.json']['sha256'], + 'integrity_sha256': plan['files']['prerequisites/v01/integrity.json']['sha256']} + publisher.check_gate(gate, plan) + for name, value in [('source_commit', 'c' * 40), ('browser_qa_passed', False), ('tests_passed', 1), + ('benchmark_sha256', '0' * 64), ('integrity_sha256', '0' * 64)]: + with self.subTest(name=name), self.assertRaisesRegex(publisher.PublicationError, 'source-bound'): + publisher.check_gate({**gate, name: value}, plan) + + def test_remote_tree_keeps_all_historical_git_and_lfs_entries(self): + payload = {'prerequisites/v01/new.bin.gz': b'new'} + old_attributes = self.original['.gitattributes'] + attributes = old_attributes + b'prerequisites/v01/new.bin.gz filter=lfs diff=lfs merge=lfs -text\n' + after = {**self.tree, 'prerequisites/v01/new.bin.gz': {'blob': 'f' * 40, 'size': 3, 'lfs_sha256': None}, + '.gitattributes': {'blob': publisher.git_blob(attributes), 'size': len(attributes), 'lfs_sha256': None}} + self.assertEqual(publisher.verify_tree(self.tree, after, payload, old_attributes, attributes), len(self.tree) - 1) + changed = {**after, 'workstation/v01/geometry.bin': {**after['workstation/v01/geometry.bin'], 'lfs_sha256': '0' * 64}} + with self.assertRaisesRegex(publisher.PublicationError, 'Historical Git/LFS'): + publisher.verify_tree(self.tree, changed, payload, old_attributes, attributes) + with self.assertRaisesRegex(publisher.PublicationError, 'unexpected paths'): + publisher.verify_tree(self.tree, {**after, 'extra.json': {}}, payload, old_attributes, attributes) + + def test_hub_metadata_cannot_replace_prior_rules_or_add_unrelated_rule(self): + payload = {'prerequisites/v01/one.png': b'image'} + original = self.original['.gitattributes'] + for attributes in (b'replaced', original + b'old.png filter=lfs diff=lfs merge=lfs -text\n'): + after = {**self.tree, 'prerequisites/v01/one.png': {}, + '.gitattributes': {'blob': publisher.git_blob(attributes), 'size': len(attributes), 'lfs_sha256': None}} + with self.assertRaises(publisher.PublicationError): + publisher.verify_tree(self.tree, after, payload, original, attributes) + + +if __name__ == '__main__': + unittest.main() diff --git a/pyproject.toml b/pyproject.toml index 3628b2a..e6ce2cb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -51,6 +51,7 @@ dvidia-piper-reliability = "dvidia_training.piper_reliability_benchmark:main" dvidia-assets = "dvidia_training.asset_cli:main" dvidia-workstation = "dvidia_training.workstation:main" dvidia-workstation-benchmark = "dvidia_training.workstation_benchmark:main" +dvidia-prerequisites = "dvidia_training.prerequisite_benchmark:main" [tool.setuptools.packages.find] where = ["src"] diff --git a/src/dvidia_training/hinged_shoebox.py b/src/dvidia_training/hinged_shoebox.py new file mode 100644 index 0000000..75bb862 --- /dev/null +++ b/src/dvidia_training/hinged_shoebox.py @@ -0,0 +1,295 @@ +"""Passive shoe-box lid / PiPER access pilot, using native MuJoCo contact. + +Policies are authored, use privileged joint/TCP state and do not learn from video. +The task is reaching an inspection waypoint inside an open box, then returning; +it is not shoe retrieval. A closed box requires assistance. Reset angle/velocity +are declared initial conditions. During rollout only PiPER actuators are driven: +no lid motor, mocap body, object attachment, external force or pose rewrite. +""" +from __future__ import annotations + +import math +import time +from copy import deepcopy + +from . import reference_sim as sim, workstation as ws + +TASK = 'hinged-shoebox' +TIMESTEP = .002 +CONTROL_DT = .02 +DURATION = 6. +START = (.36, -.235, .17) +ACCESS = (.36, -.125, .13) +WITHDRAW = (.36, -.27, .22) +LID = 'shoebox_lid' +HINGE = 'shoebox_hinge' +CONTACT_THRESHOLD_N = .5 +SCOPE = ('Authored PiPER shoe-box inspection-waypoint access with privileged native ' + 'hinge and robot states. Synthetic rigid shoe/lid, uncalibrated contact. ' + 'No learned policy, shoe retrieval, damage model or physical robot qualification.') + +# Frozen before development-policy tuning. These are different exact reset states, +# not an IID statistical generalization study. Never tune a policy on heldout runs. +_CASES = { + 'development': [ + {'id':'open-light','lid_angle_deg':112.,'lid_velocity_rad_s':0.,'lid_mass_kg':.12,'hinge_damping':.025}, + {'id':'falling-light','lid_angle_deg':72.,'lid_velocity_rad_s':-.10,'lid_mass_kg':.12,'hinge_damping':.025}, + {'id':'falling-heavy','lid_angle_deg':65.,'lid_velocity_rad_s':-.30,'lid_mass_kg':.24,'hinge_damping':.06}, + {'id':'transient-closing','lid_angle_deg':108.,'lid_velocity_rad_s':-.40,'lid_mass_kg':.12,'hinge_damping':.025}, + ], + 'heldout': [ + {'id':'open-medium','lid_angle_deg':105.,'lid_velocity_rad_s':0.,'lid_mass_kg':.18,'hinge_damping':.04}, + {'id':'falling-medium','lid_angle_deg':78.,'lid_velocity_rad_s':-.15,'lid_mass_kg':.18,'hinge_damping':.04}, + {'id':'falling-low','lid_angle_deg':58.,'lid_velocity_rad_s':-.25,'lid_mass_kg':.10,'hinge_damping':.02}, + {'id':'transient-damped','lid_angle_deg':110.,'lid_velocity_rad_s':-.35,'lid_mass_kg':.20,'hinge_damping':.06}, + ], +} + + +def cases(split='development'): + if split not in _CASES: + raise ValueError('split must be development or heldout') + return [dict(deepcopy(case), split=split) for case in _CASES[split]] + + +def _validate_case(case): + if not isinstance(case,dict) or case not in cases('development')+cases('heldout'): + raise ValueError('Expected an exact frozen hinged-shoebox case') + return deepcopy(case) + + +def build_model(assets, case): + """Return a compiled physical scene; nothing has been stepped or settled.""" + case = _validate_case(case) + mj, _ = sim._native_imports() + spec = ws._spec(assets) + # Retain the exact PiPER mechanics/actuators and free authored trainer. + spec.body(ws.SHOE).pos = [.36,-.11,.018] + for geom in list(spec.geoms): + if geom.name.startswith('workstation_rack_'): + spec.delete(geom) + world = spec.worldbody + material = [.57,.43,.29,1] + for name,pos,size in [ + ('bottom',[.36,-.105,.006],[.175,.135,.006]), + ('front',[.36,-.238,.057],[.175,.007,.045]), + ('back',[.36,.028,.057],[.175,.007,.045]), + ('left',[.188,-.105,.057],[.007,.135,.045]), + ('right',[.532,-.105,.057],[.007,.135,.045]), + ]: + world.add_geom(name='shoebox_'+name,type=mj.mjtGeom.mjGEOM_BOX, + pos=pos,size=size,rgba=material,friction=[.6,.005,.0001], + solref=[.01,1]) + lid = world.add_body(name=LID,pos=[.36,.035,.108]) + lid.add_joint(name=HINGE,type=mj.mjtJoint.mjJNT_HINGE,axis=[-1,0,0], + limited=True,range=[0,math.radians(120)],damping=case['hinge_damping'], + armature=0,solref_limit=[.015,1]) + lid.add_geom(name='shoebox_lid_panel',type=mj.mjtGeom.mjGEOM_BOX, + pos=[0,-.141,0],size=[.181,.135,.006], + mass=case['lid_mass_kg'],rgba=[.68,.53,.37,1], + friction=[.6,.005,.0001],solref=[.01,1],condim=4) + # A small seam makes the hinge's axis legible in the replay, but contributes + # no collision or inertial mass. The physical hinge is the revolute joint. + world.add_geom(name='shoebox_hinge_visual',type=mj.mjtGeom.mjGEOM_CAPSULE, + fromto=[.18,.035,.108,.54,.035,.108],size=[.003,0,0], + contype=0,conaffinity=0,rgba=[.23,.24,.24,1]) + model = spec.compile() + if (model.nq,model.nv,model.nu,model.neq,model.nmocap)!=(16,15,7,1,0): + raise ValueError('Unexpected PiPER / free shoe / passive hinge dimensions') + return model + + +def initialize(model, case): + """Declared reset-only pose solve; no object mutations occur during rollout.""" + mj,np = sim._native_imports() + case = _validate_case(case) + data = ws.initialize(model) + joint = model.joint(HINGE) + data.qpos[joint.qposadr[0]] = math.radians(case['lid_angle_deg']) + for _ in range(240): + mj.mj_forward(model,data) + data.qpos[:6] = ws.controller_action(model,data,START,.025,validate=False)[:6] + data.qvel[:] = 0 + data.qvel[joint.dofadr[0]] = case['lid_velocity_rad_s'] + data.ctrl[:6] = data.qpos[:6] + data.ctrl[6] = .025 + mj.mj_forward(model,data) + if not np.isfinite(data.qpos).all(): + raise RuntimeError('Invalid reset') + return data + + +def risk_observation(angle, velocity, tcp): + """Causal conservative swept-lid guard, deliberately independent of case IDs. + + The aperture gate remains conservative: avoid entry into any descending lid + below 115 degrees; entering only resumes after 200 ms of a stable/open state. + This is a hand-authored geometric guard, not an uncertainty-calibrated model. + """ + return bool(velocity < -.03 and angle < math.radians(115) + and .14 < float(tcp[0]) < .58 + and -.28 < float(tcp[1]) < .06 and float(tcp[2]) < .35) + + +def _contact(model,data,lid_id,robot_ids): + mj,np = sim._native_imports() + peak = 0.; count = 0; other_peak = 0. + for index in range(data.ncon): + contact = data.contact[index] + b1,b2 = int(model.geom_bodyid[contact.geom1]),int(model.geom_bodyid[contact.geom2]) + if (b1==lid_id and b2 in robot_ids) or (b2==lid_id and b1 in robot_ids): + force=np.zeros(6);mj.mj_contactForce(model,data,index,force) + peak=max(peak,float(abs(force[0])));count+=1 + elif ((b1 in robot_ids-{1}) != (b2 in robot_ids-{1})) and not (b1 in robot_ids and b2 in robot_ids): + force=np.zeros(6);mj.mj_contactForce(model,data,index,force) + other_peak=max(other_peak,float(abs(force[0]))) + return peak,count,other_peak + + +def run_case(assets,case,policy='baseline',record=True): + """Run a frozen case with 2 ms native observation and 20 ms control decisions. + + ``native_trace`` retains every step's causal hinge/risk/contact observations. + Frame poses at 50 Hz are replay data, not physics executed in the viewer. + ``success`` is task success only; safe_abort/help is never counted as success. + """ + case = _validate_case(case) + if policy not in ('baseline','recovery'): + raise ValueError('policy must be baseline or recovery') + if type(record) is not bool: + raise ValueError('record must be boolean') + mj,np = sim._native_imports() + model=build_model(assets,case);data=initialize(model,case) + tcp_id=model.site(ws.TCP).id;lid_id=model.body(LID).id + robot_ids=set(range(1,model.body(ws.SHOE).id)) + hinge=model.joint(HINGE);qindex=int(hinge.qposadr[0]);vindex=int(hinge.dofadr[0]) + events=[];frames=[];trace=[] + phase='access';target=ACCESS;desired=data.ctrl.copy() + intervention_count=0;resumed_count=0;false_interventions=0 + risk_steps=0;contact_steps=0;peak_force=0.;other_peak_force=0.;window_peak=0.;impulse=0. + first_risk=None;first_intervention=None;first_contact=None + contact_active=False;risk_active=False;safe_dwell=0.;access_dwell=0. + reached=False;returned=False;safe_abort=False;valid=True;failure_reason=None + decision_ms=[];wall_started=time.perf_counter() + def event(kind,**values): + messages={'withdrawal_started':'Lid descending. Withdraw from the access path.', + 'withdrawal_complete':'Arm has reached the withdrawal waypoint.', + 'access_resumed':'Lid aperture stable. Resume the inspection waypoint.', + 'help_requested':'Box closed. Stop here and request help reopening it.', + 'hazardous_contact':'Lid contacted the robot above the synthetic benchmark threshold.', + 'inspection_waypoint_reached':'Inspection waypoint held for 200 ms; no shoe grasp attempted.', + 'return_complete':'Arm returned from the box.'} + events.append({'t':round(float(data.time),6),'type':kind,'message':messages.get(kind,kind.replace('_',' ')),**values}) + for step in range(round(DURATION/TIMESTEP)+1): + angle=float(data.qpos[qindex]);velocity=float(data.qvel[vindex]);tcp=data.site_xpos[tcp_id].copy() + risk=risk_observation(angle,velocity,tcp) + contact_force,contact_count,other_force=_contact(model,data,lid_id,robot_ids) + other_peak_force=max(other_peak_force,other_force) + peak_force=max(peak_force,contact_force);window_peak=max(window_peak,contact_force) + if step: + impulse+=contact_force*TIMESTEP;contact_steps+=int(contact_force>CONTACT_THRESHOLD_N);risk_steps+=int(risk) + if risk and first_risk is None:first_risk=float(data.time) + if risk!=risk_active: + event('hazard_started' if risk else 'hazard_cleared',lid_angle_rad=angle,lid_velocity_rad_s=velocity) + risk_active=risk + harmful=contact_force>CONTACT_THRESHOLD_N + if harmful and first_contact is None:first_contact=float(data.time) + if harmful!=contact_active: + event('hazardous_contact' if harmful else 'lid_robot_contact_cleared',normal_force_n=contact_force) + contact_active=harmful + if record: + trace.append([round(float(data.time),6),angle,velocity,contact_force,int(risk),other_force]) + if step%10==0: + decision_started=time.perf_counter() + if policy=='recovery' and risk and phase in ('access','return'): + phase='withdraw';target=WITHDRAW;intervention_count+=1 + false_interventions+=int(not risk) + if first_intervention is None:first_intervention=float(data.time) + event('withdrawal_started',reason='descending_lid_in_access_volume') + if phase=='withdraw': + target=WITHDRAW + if float(np.linalg.norm(tcp-np.asarray(WITHDRAW))) < .018: + phase='wait';safe_dwell=0.;event('withdrawal_complete') + elif phase=='wait': + target=WITHDRAW + aperture_open=angle>math.radians(95) and velocity>=-.015 + safe_dwell=safe_dwell+CONTROL_DT if aperture_open else 0. + if safe_dwell>=.2: + phase='access';target=ACCESS;resumed_count+=1;event('access_resumed') + elif anglemath.radians(45) + access_dwell=access_dwell+CONTROL_DT if at_access and clear else 0. + if access_dwell>=.2: + reached=True;phase='return';target=WITHDRAW;event('inspection_waypoint_reached') + elif phase=='return': + target=WITHDRAW + if float(np.linalg.norm(tcp-np.asarray(WITHDRAW)))<.018: + returned=True;phase='done';event('return_complete') + elif phase in ('done','help'): + target=WITHDRAW + desired=ws.controller_action(model,data,target,.025,validate=False) + decision_ms.append((time.perf_counter()-decision_started)*1000) + if record: + poses=np.concatenate((data.xpos,data.xquat),axis=1) + frames.append({'t':round(float(data.time),6),'body_poses':poses.tolist(),'phase':phase, + 'lid_angle_rad':angle,'lid_velocity_rad_s':velocity, + 'tcp_position_m':tcp.tolist(),'target_position_m':list(target), + 'qpos_rad_m':data.qpos.tolist(),'qvel_rad_m_s':data.qvel.tolist(), + 'issued_ctrl':data.ctrl.tolist(),'requested_joint_target':desired.tolist(), + 'risk':risk,'lid_robot_force_n':contact_force, + 'native_window_peak_force_n':window_peak,'other_environment_robot_force_n':other_force}) + window_peak=0. + if step==round(DURATION/TIMESTEP):break + data.ctrl[:6]+=np.clip(desired[:6]-data.ctrl[:6],-ws.CONTROLLER['joint_rate_rad_s']*TIMESTEP,ws.CONTROLLER['joint_rate_rad_s']*TIMESTEP) + data.ctrl[6]+=float(np.clip(desired[6]-data.ctrl[6],-ws.CONTROLLER['gripper_rate_m_s']*TIMESTEP,ws.CONTROLLER['gripper_rate_m_s']*TIMESTEP)) + # No qpos/qvel/force writes during rollout: only native joint actuators. + mj.mj_step(model,data);mj.mj_forward(model,data) + if not all(np.isfinite(value).all() for value in (data.qpos,data.qvel,data.qacc)) or any(w.number for w in data.warning): + valid=False;failure_reason='nonfinite_state_or_solver_warning';event('invalid_native_state');break + wall_seconds=time.perf_counter()-wall_started + collision=peak_force>CONTACT_THRESHOLD_N + other_collision=other_peak_force>CONTACT_THRESHOLD_N + success=bool(valid and reached and returned and not collision and not other_collision) + safe_abort=bool(valid and safe_abort and not collision and not other_collision) + if valid and not success and not safe_abort: + failure_reason=('lid_robot_contact' if collision else 'other_environment_robot_contact' if other_collision + else 'inspection_waypoint_not_reached' if not reached else 'return_timeout') + completion_time=next((e['t'] for e in events if e['type']=='return_complete'),None) + withdrawal_time=next((e['t'] for e in events if e['type']=='withdrawal_complete'),None) + outcome='recovered' if success and resumed_count else 'completed' if success else 'safe_abort' if safe_abort else 'failed' + metrics={'outcome':outcome,'task_success':success,'inspection_waypoint_reached':reached,'return_completed':returned, + 'safe_abort':safe_abort,'help_requested':any(e['type']=='help_requested' for e in events), + 'resumed_count':resumed_count,'recovery_count':resumed_count,'intervention_count':intervention_count, + 'missed_interventions':int(first_risk is not None and first_intervention is None), + 'false_interventions':None,'predicate_mismatch_interventions':false_interventions, + 'false_intervention_definition':'Not identifiable from the treated rollout alone. Compare this case against baseline: a withdrawal when baseline completes without contact is a counterfactual nuisance interruption, not proven necessary avoidance.', + 'missed_intervention_definition':'At least one observed descending-lid predicate with no withdrawal command; this is guard coverage, not calibrated danger classification.', + 'lid_robot_collision':collision,'other_environment_robot_collision':other_collision, + 'peak_contact_force_n':max(peak_force,other_peak_force), + 'peak_lid_robot_normal_force_n':peak_force,'peak_other_environment_robot_force_n':other_peak_force, + 'lid_robot_peak_force_time_integral_ns':impulse,'contact_duration_s':contact_steps*TIMESTEP, + 'hazard_duration_s':risk_steps*TIMESTEP,'first_hazard_s':first_risk, + 'first_intervention_s':first_intervention,'first_command_s':first_intervention,'first_contact_s':first_contact, + 'detection_time_s':first_risk,'command_time_s':first_intervention, + 'reaction_measurement_scope':'Privileged native predicate sampled at 2 ms; authored command at 20 ms. No sensor, transport or actuator-response latency included.', + 'first_response_latency_s':None if first_intervention is None else max(0.,first_intervention-(first_risk or 0.)), + 'completion_time_s':completion_time, + 'withdrawal_duration_s':None if withdrawal_time is None or first_intervention is None else withdrawal_time-first_intervention, + 'simulated_seconds':float(data.time),'wall_seconds':wall_seconds, + 'physics_realtime_factor':float(data.time)/wall_seconds, + 'decision_latency_p50_ms':float(np.percentile(decision_ms,50)), + 'decision_latency_p95_ms':float(np.percentile(decision_ms,95)), + 'decision_latency_max_ms':max(decision_ms),'native_steps':int(round(data.time/TIMESTEP)), + 'state_action_frame_timing':'Frame state and issued_ctrl are observed at t before the next native step; requested_joint_target is the authored 20 ms decision subsequently rate-limited into issued_ctrl.', + 'state_action_units':{'qpos_rad_m':{'0:6':'arm rad','6:8':'finger m','8:11':'shoe position m','11:15':'shoe quaternion wxyz dimensionless','15':'hinge rad'}, + 'qvel_rad_m_s':{'0:6':'arm rad/s','6:8':'finger m/s','8:11':'shoe linear m/s','11:14':'shoe angular rad/s','14':'hinge rad/s'}, + 'issued_ctrl':{'0:6':'arm rad','6':'jaw m'},'requested_joint_target':{'0:6':'arm rad','6':'jaw m'}}, + 'terminal_phase':phase,'failure_reason':failure_reason,'solver_warnings':int(sum(w.number for w in data.warning))} + return {'task':TASK,'case':case,'policy':policy,'success':success,'valid':valid, + 'metrics':metrics,'events':events,'frames':frames,'model':model, + 'native_trace_columns':['t','lid_angle_rad','lid_velocity_rad_s','lid_robot_normal_force_n','risk','other_environment_robot_force_n'], + 'native_trace':trace,'scope':SCOPE} diff --git a/src/dvidia_training/prerequisite_benchmark.py b/src/dvidia_training/prerequisite_benchmark.py new file mode 100644 index 0000000..791ea4e --- /dev/null +++ b/src/dvidia_training/prerequisite_benchmark.py @@ -0,0 +1,272 @@ +"""Reproducible native experiments in skill prerequisites, with every trial retained. + +The web export replays measured body poses. Policies are authored and observations +are simulator truth. Neither the viewer nor this benchmark trains a robot policy. +""" +from __future__ import annotations + +import argparse +import gzip +from hashlib import sha256 +import json +from pathlib import Path +import platform +import re +import time + +from . import asset_preview, reference_replay, reference_sim as sim + +SCHEMA = 'dvidia.skill-prerequisites/v1' +SCOPE = ('Authored PiPER policies in native MuJoCo with synthetic rigid objects and ' + 'privileged simulator observations. Browser replay uses recorded poses; ' + 'no learned policy, hardware safety qualification or real-world transfer result.') +TASKS = ('hinged-box', 'tool-reach') +POLICIES = ('baseline', 'recovery') +MAX_FILE_BYTES = 32 * 1024 * 1024 +MAX_EXPORT_BYTES = 192 * 1024 * 1024 + + +def encode(value): + return (json.dumps(value, indent=2, allow_nan=False) + '\n').encode() + + +def modules(): + from . import hinged_shoebox, tool_reach + return {'hinged-box': hinged_shoebox, 'tool-reach': tool_reach} + + +def implementation_hashes(): + root = Path(__file__).parent + return {name: sha256((root / name).read_bytes()).hexdigest() for name in ( + 'prerequisite_benchmark.py', 'hinged_shoebox.py', 'tool_reach.py', + 'workstation.py', 'asset_library.py', 'asset_catalog.json', 'robot_profiles.py', + 'prerequisite_lab.html', 'prerequisite_lab.js', 'prerequisite_lab.bundle.js')} + + +def protocol(split='heldout', task='all'): + if split not in ('development', 'heldout') or task not in (*TASKS, 'all'): + raise ValueError('Choose a declared split and task') + cases = [] + for name, module in modules().items(): + if task not in (name, 'all'): + continue + for case in module.cases(split): + if not isinstance(case, dict) or not re.fullmatch(r'[a-z0-9_-]{1,80}', case.get('id', '')): + raise ValueError('Every case needs a bounded portable ID') + for policy in POLICIES: + cases.append({'id': name + '-' + case['id'] + '-' + policy, + 'task': name, 'policy': policy, 'case': case}) + if len({item['id'] for item in cases}) != len(cases) or not 1 <= len(cases) <= 100: + raise ValueError('Protocol requires distinct, bounded attempts') + return {'schema': SCHEMA, 'scope': SCOPE, 'split': split, 'attempts': cases, + 'comparison': 'Matched declared scene conditions. Tool baseline is a no-tool capability control; it is not a policy-only ablation.', + 'split_scope': 'Explicit parameter holdouts, not independent real-world reliability trials. No held-out tuning.', + 'success_scope': 'Task-specific completion. Safe abort, retrieval, and retained lift are reported separately.', + 'timing_scope': 'CPU wall time for native execution including initialization and recording; rendering, downloads and real sensor latency excluded.'} + + +def _write(root, name, content): + if len(content) > MAX_FILE_BYTES: + raise ValueError('Export file exceeds byte limit: ' + name) + target = root / name + target.parent.mkdir(parents=True, exist_ok=True) + if target.exists(): + if target.read_bytes() != content: + raise ValueError('Export path collision: ' + name) + return + with target.open('xb') as stream: + stream.write(content) + + +def _binary(root, raw, prefix): + if len(raw) > MAX_FILE_BYTES: + raise ValueError('Decoded binary exceeds byte limit') + digest = sha256(raw).hexdigest() + packed = gzip.compress(raw, mtime=0) + name = 'assets/' + prefix + '-' + digest[:20] + '.bin.gz' + _write(root, name, packed) + return {'href': name, 'compression': 'gzip', 'bytes': len(raw), + 'compressed_bytes': len(packed), 'sha256': digest} + + +def export_trial(root, trial_id, result, source): + """Export native poses without recreating or interpolating a physics result.""" + _, np = sim._native_imports() + model, frames = result['model'], result['frames'] + source = {**source, 'compiled_model_sha256': sim.model_digest(model)} + if not 2 <= len(frames) <= 10000: + raise ValueError('A replay needs between two and ten thousand recorded frames') + poses = np.asarray([frame['body_poses'] for frame in frames], dtype=' 0 + row['nuisance_scope'] = 'Baseline completed without disallowed contact; conservative withdrawal is not proven necessary.' + t0, t1 = a['completion_time_s'], b['completion_time_s'] + row['completion_delay_s'] = None if t0 is None or t1 is None else t1 - t0 + if row['valid_pair'] and baseline['task'] == 'tool-reach': + row['baseline_retrieved'] = a['retrieval_success'] + row['with_tool_retrieved'] = b['retrieval_success'] + row['with_tool_retained_lift'] = b['retained_lift_success'] + row['comparison_scope'] = 'No-tool capability control versus mounted rake plus recovery; not an isolated policy effect.' + pairs.append(row) + return pairs + + +def seal(root): + files = {} + for path in sorted(root.rglob('*')): + if path.is_symlink(): + raise ValueError('Export cannot contain symlinks') + if path.is_file() and path.name != 'integrity.json': + content = path.read_bytes() + files[path.relative_to(root).as_posix()] = {'bytes': len(content), 'sha256': sha256(content).hexdigest()} + if any(item['bytes'] > MAX_FILE_BYTES for item in files.values()) or sum(item['bytes'] for item in files.values()) > MAX_EXPORT_BYTES: + raise ValueError('Export exceeds size limits') + _write(root, 'integrity.json', encode({'schema': 'dvidia.prerequisite-integrity/v1', + 'scope': 'Artifact consistency, not authenticity or physical validation.', 'files': files})) + return files + + +def benchmark(assets, output, *, split='heldout', task='all', source_commit=None): + destination = Path(output) + if destination.exists() or destination.is_symlink(): + raise ValueError('Benchmark output must be a fresh directory') + if source_commit is not None and re.fullmatch(r'[a-f0-9]{40}', source_commit) is None: + raise ValueError('Source commit must be a full Git SHA') + plan = protocol(split, task) + plan.update(source_commit=source_commit, implementation_sha256=implementation_hashes()) + mj, _ = sim._native_imports() + provenance, notices = asset_preview._licenses('piper', assets) + destination.mkdir(parents=True) + _write(destination, 'protocol.json', encode(plan)) + source = {'commit': source_commit, 'protocol_sha256': sha256(encode(plan)).hexdigest(), + 'mujoco': mj.__version__, 'robot_assets': provenance} + records = [] + for attempt in plan['attempts']: + start = time.perf_counter() + row = {'id': attempt['id'], 'task': attempt['task'], 'policy': attempt['policy'], + 'case': attempt['case'], 'valid': False, 'success': False, 'metrics': {}, 'events': [], 'errors': []} + try: + result = modules()[attempt['task']].run_case(assets, attempt['case'], policy=attempt['policy'], record=True) + row['wall_seconds'] = time.perf_counter() - start + if type(result['success']) is not bool or type(result['valid']) is not bool: + raise ValueError('Attempt validity and success must be explicit booleans') + row.update(valid=result['valid'], success=result['success'] and result['valid'], + metrics=result['metrics'], events=result['events']) + for key in ('native_trace', 'native_trace_columns', 'trace_columns', 'control_compute_ms', 'warnings'): + if key in result: + row[key] = result[key] + row['replay'] = export_trial(destination, attempt['id'], result, source) + encode(row) + except Exception as exc: + row.update(valid=False, success=False) + # Published failures use a category; exception messages can contain + # private asset paths. Do not leak those paths into public evidence. + row['errors'].append(type(exc).__name__ + ': attempt or export failed') + try: + encode(row) + except (ValueError, TypeError): + row.update(metrics={}, events=[]) + for key in ('native_trace', 'native_trace_columns', 'trace_columns', 'control_compute_ms', 'warnings'): + row.pop(key, None) + row.setdefault('wall_seconds', time.perf_counter() - start) + row['export_seconds'] = max(0., time.perf_counter() - start - row['wall_seconds']) + # A failed attempt is evidence too; write it before starting the next one. + _write(destination, 'trials/' + attempt['id'] + '.json', encode(row)) + # Keep the landing page small. Full-rate evidence remains in the exact + # per-trial receipt; the index retains every trial and all other fields. + records.append({key: value for key, value in row.items() if key != 'native_trace'}) + print(json.dumps({'attempt': row['id'], 'success': row['success'], 'valid': row['valid'], + 'outcome': row['metrics'].get('outcome') if row['valid'] else 'invalid_attempt', + 'errors': row['errors']}), flush=True) + report = {'schema': SCHEMA, 'scope': SCOPE, 'source': source, 'split': split, + 'host': {'system': platform.system(), 'machine': platform.machine(), 'python': platform.python_version(), + 'compute': 'CPU native simulation; no GPU required for benchmark. Browser replay needs WebGL2.'}, + 'learned_policy': False, 'hardware_validated': False, 'attempts': records, + 'groups': summarize(records), 'paired_comparisons': paired_comparisons(records)} + _write(destination, 'benchmark.json', encode(report)) + resource = Path(__file__).parent + for name in ('prerequisite_lab.html', 'prerequisite_lab.bundle.js', 'reference_replay.third-party.txt'): + _write(destination, 'index.html' if name.endswith('.html') else name, (resource / name).read_bytes()) + for name, content in notices.items(): + _write(destination, name, content) + _write(destination, 'LICENSE', reference_replay.MIT_LICENSE.encode()) + _write(destination, 'README.md', ('# DVIDIA skill prerequisites v0.1\n\n' + SCOPE + '\n\n' + 'Open the replay by serving this folder: `python -m http.server 8000`. All visual assets are local. ' + 'The browser plays recorded native poses; it does not run physics.\n\n' + 'Reproduce native experiments using the matching Git source commit, install `.[arm]`, ' + 'fetch pinned PiPER assets with `dvidia-robot-sim fetch piper --output robot-assets`, then run ' + '`dvidia-prerequisites --assets robot-assets --output fresh-results --split ' + split + '`.\n\n' + 'DVIDIA code and synthetic objects: MIT. Upstream arm and viewer notices are retained under licenses/ ' + 'and reference_replay.third-party.txt. Minimum RAM and cross-device throughput are not established.\n').encode()) + seal(destination) + return report + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--assets', required=True) + parser.add_argument('--output', required=True) + parser.add_argument('--split', choices=('development', 'heldout'), default='heldout') + parser.add_argument('--task', choices=(*TASKS, 'all'), default='all') + parser.add_argument('--source-commit') + args = parser.parse_args() + report = benchmark(args.assets, args.output, split=args.split, task=args.task, source_commit=args.source_commit) + print(json.dumps({'output': args.output, 'groups': report['groups']})) + + +if __name__ == '__main__': + main() diff --git a/src/dvidia_training/prerequisite_lab.bundle.js b/src/dvidia_training/prerequisite_lab.bundle.js new file mode 100644 index 0000000..8ea87a3 --- /dev/null +++ b/src/dvidia_training/prerequisite_lab.bundle.js @@ -0,0 +1,3841 @@ +/* DVIDIA prerequisite experiments. MIT; bundled Three.js r180, MIT. See reference_replay.third-party.txt. */ +(()=>{var Gn={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},Wn={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},Al=0,ro=1,Cl=2;var ao=1,Tr=2,hn=3,Sn=0,Re=1,Ye=2,En=0,ei=1,oo=2,lo=3,co=4,Rl=5,On=100,Il=101,Pl=102,Dl=103,Ll=104,Ul=200,Nl=201,Fl=202,Ol=203,ir=204,sr=205,Bl=206,zl=207,kl=208,Vl=209,Hl=210,Gl=211,Wl=212,Xl=213,ql=214,wr=0,Ar=1,Cr=2,ni=3,Rr=4,Ir=5,Pr=6,Dr=7,ho=0,Yl=1,Zl=2,Tn=0,Jl=1,$l=2,Kl=3,Lr=4,jl=5,Ql=6,tc=7;var uo=300,ri=301,ai=302,Ur=303,Nr=304,ws=306,rr=1e3,Fn=1001,ar=1002,Xe=1003,ec=1004;var As=1005;var nn=1006,Fr=1007;var Xn=1008;var an=1009,fo=1010,po=1011,Vi=1012,Or=1013,qn=1014,un=1015,Hi=1016,Br=1017,zr=1018,Gi=1020,mo=35902,go=35899,_o=1021,xo=1022,Ze=1023,Ri=1026,Wi=1027,yo=1028,kr=1029,vo=1030,Vr=1031;var Hr=1033,Cs=33776,Rs=33777,Is=33778,Ps=33779,Gr=35840,Wr=35841,Xr=35842,qr=35843,Yr=36196,Zr=37492,Jr=37496,$r=37808,Kr=37809,jr=37810,Qr=37811,ta=37812,ea=37813,na=37814,ia=37815,sa=37816,ra=37817,aa=37818,oa=37819,la=37820,ca=37821,ha=36492,ua=36494,da=36495,fa=36283,pa=36284,ma=36285,ga=36286;var rs=2300,or=2301,nr=2302,Ka=2400,ja=2401,Qa=2402;var nc=3200,ic=3201;var Mo=0,sc=1,wn="",Ce="srgb",bn="srgb-linear",as="linear",Yt="srgb";var ti=7680;var to=519,rc=512,ac=513,oc=514,So=515,lc=516,cc=517,hc=518,uc=519,eo=35044;var bo="300 es",en=2e3,os=2001;var ln=class{addEventListener(t,e){this._listeners===void 0&&(this._listeners={});let n=this._listeners;n[t]===void 0&&(n[t]=[]),n[t].indexOf(e)===-1&&n[t].push(e)}hasEventListener(t,e){let n=this._listeners;return n===void 0?!1:n[t]!==void 0&&n[t].indexOf(e)!==-1}removeEventListener(t,e){let n=this._listeners;if(n===void 0)return;let s=n[t];if(s!==void 0){let r=s.indexOf(e);r!==-1&&s.splice(r,1)}}dispatchEvent(t){let e=this._listeners;if(e===void 0)return;let n=e[t.type];if(n!==void 0){t.target=this;let s=n.slice(0);for(let r=0,a=s.length;r>8&255]+ve[i>>16&255]+ve[i>>24&255]+"-"+ve[t&255]+ve[t>>8&255]+"-"+ve[t>>16&15|64]+ve[t>>24&255]+"-"+ve[e&63|128]+ve[e>>8&255]+"-"+ve[e>>16&255]+ve[e>>24&255]+ve[n&255]+ve[n>>8&255]+ve[n>>16&255]+ve[n>>24&255]).toLowerCase()}function Bt(i,t,e){return Math.max(t,Math.min(e,i))}function Eo(i,t){return(i%t+t)%t}function uh(i,t,e,n,s){return n+(i-t)*(s-n)/(e-t)}function dh(i,t,e){return i!==t?(e-i)/(t-i):0}function ss(i,t,e){return(1-e)*i+e*t}function fh(i,t,e,n){return ss(i,t,1-Math.exp(-e*n))}function ph(i,t=1){return t-Math.abs(Eo(i,t*2)-t)}function mh(i,t,e){return i<=t?0:i>=e?1:(i=(i-t)/(e-t),i*i*(3-2*i))}function gh(i,t,e){return i<=t?0:i>=e?1:(i=(i-t)/(e-t),i*i*i*(i*(i*6-15)+10))}function _h(i,t){return i+Math.floor(Math.random()*(t-i+1))}function xh(i,t){return i+Math.random()*(t-i)}function yh(i){return i*(.5-Math.random())}function vh(i){i!==void 0&&(ol=i);let t=ol+=1831565813;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}function Mh(i){return i*is}function Sh(i){return i*Ii}function bh(i){return(i&i-1)===0&&i!==0}function Eh(i){return Math.pow(2,Math.ceil(Math.log(i)/Math.LN2))}function Th(i){return Math.pow(2,Math.floor(Math.log(i)/Math.LN2))}function wh(i,t,e,n,s){let r=Math.cos,a=Math.sin,o=r(e/2),l=a(e/2),c=r((t+n)/2),h=a((t+n)/2),d=r((t-n)/2),f=a((t-n)/2),m=r((n-t)/2),_=a((n-t)/2);switch(s){case"XYX":i.set(o*h,l*d,l*f,o*c);break;case"YZY":i.set(l*f,o*h,l*d,o*c);break;case"ZXZ":i.set(l*d,l*f,o*h,o*c);break;case"XZX":i.set(o*h,l*_,l*m,o*c);break;case"YXY":i.set(l*m,o*h,l*_,o*c);break;case"ZYZ":i.set(l*_,l*m,o*h,o*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+s)}}function Ai(i,t){switch(t.constructor){case Float32Array:return i;case Uint32Array:return i/4294967295;case Uint16Array:return i/65535;case Uint8Array:return i/255;case Int32Array:return Math.max(i/2147483647,-1);case Int16Array:return Math.max(i/32767,-1);case Int8Array:return Math.max(i/127,-1);default:throw new Error("Invalid component type.")}}function Ae(i,t){switch(t.constructor){case Float32Array:return i;case Uint32Array:return Math.round(i*4294967295);case Uint16Array:return Math.round(i*65535);case Uint8Array:return Math.round(i*255);case Int32Array:return Math.round(i*2147483647);case Int16Array:return Math.round(i*32767);case Int8Array:return Math.round(i*127);default:throw new Error("Invalid component type.")}}var To={DEG2RAD:is,RAD2DEG:Ii,generateUUID:Xi,clamp:Bt,euclideanModulo:Eo,mapLinear:uh,inverseLerp:dh,lerp:ss,damp:fh,pingpong:ph,smoothstep:mh,smootherstep:gh,randInt:_h,randFloat:xh,randFloatSpread:yh,seededRandom:vh,degToRad:Mh,radToDeg:Sh,isPowerOfTwo:bh,ceilPowerOfTwo:Eh,floorPowerOfTwo:Th,setQuaternionFromProperEuler:wh,normalize:Ae,denormalize:Ai},Pt=class i{constructor(t=0,e=0){i.prototype.isVector2=!0,this.x=t,this.y=e}get width(){return this.x}set width(t){this.x=t}get height(){return this.y}set height(t){this.y=t}set(t,e){return this.x=t,this.y=e,this}setScalar(t){return this.x=t,this.y=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}add(t){return this.x+=t.x,this.y+=t.y,this}addScalar(t){return this.x+=t,this.y+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this}subScalar(t){return this.x-=t,this.y-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this}multiply(t){return this.x*=t.x,this.y*=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divide(t){return this.x/=t.x,this.y/=t.y,this}divideScalar(t){return this.multiplyScalar(1/t)}applyMatrix3(t){let e=this.x,n=this.y,s=t.elements;return this.x=s[0]*e+s[3]*n+s[6],this.y=s[1]*e+s[4]*n+s[7],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this}clamp(t,e){return this.x=Bt(this.x,t.x,e.x),this.y=Bt(this.y,t.y,e.y),this}clampScalar(t,e){return this.x=Bt(this.x,t,e),this.y=Bt(this.y,t,e),this}clampLength(t,e){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Bt(n,t,e))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(t){let e=Math.sqrt(this.lengthSq()*t.lengthSq());if(e===0)return Math.PI/2;let n=this.dot(t)/e;return Math.acos(Bt(n,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){let e=this.x-t.x,n=this.y-t.y;return e*e+n*n}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this}lerpVectors(t,e,n){return this.x=t.x+(e.x-t.x)*n,this.y=t.y+(e.y-t.y)*n,this}equals(t){return t.x===this.x&&t.y===this.y}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this}rotateAround(t,e){let n=Math.cos(e),s=Math.sin(e),r=this.x-t.x,a=this.y-t.y;return this.x=r*n-a*s+t.x,this.y=r*s+a*n+t.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}},qe=class{constructor(t=0,e=0,n=0,s=1){this.isQuaternion=!0,this._x=t,this._y=e,this._z=n,this._w=s}static slerpFlat(t,e,n,s,r,a,o){let l=n[s+0],c=n[s+1],h=n[s+2],d=n[s+3],f=r[a+0],m=r[a+1],_=r[a+2],M=r[a+3];if(o===0){t[e+0]=l,t[e+1]=c,t[e+2]=h,t[e+3]=d;return}if(o===1){t[e+0]=f,t[e+1]=m,t[e+2]=_,t[e+3]=M;return}if(d!==M||l!==f||c!==m||h!==_){let p=1-o,u=l*f+c*m+h*_+d*M,T=u>=0?1:-1,E=1-u*u;if(E>Number.EPSILON){let C=Math.sqrt(E),A=Math.atan2(C,u*T);p=Math.sin(p*A)/C,o=Math.sin(o*A)/C}let S=o*T;if(l=l*p+f*S,c=c*p+m*S,h=h*p+_*S,d=d*p+M*S,p===1-o){let C=1/Math.sqrt(l*l+c*c+h*h+d*d);l*=C,c*=C,h*=C,d*=C}}t[e]=l,t[e+1]=c,t[e+2]=h,t[e+3]=d}static multiplyQuaternionsFlat(t,e,n,s,r,a){let o=n[s],l=n[s+1],c=n[s+2],h=n[s+3],d=r[a],f=r[a+1],m=r[a+2],_=r[a+3];return t[e]=o*_+h*d+l*m-c*f,t[e+1]=l*_+h*f+c*d-o*m,t[e+2]=c*_+h*m+o*f-l*d,t[e+3]=h*_-o*d-l*f-c*m,t}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get w(){return this._w}set w(t){this._w=t,this._onChangeCallback()}set(t,e,n,s){return this._x=t,this._y=e,this._z=n,this._w=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(t){return this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._onChangeCallback(),this}setFromEuler(t,e=!0){let n=t._x,s=t._y,r=t._z,a=t._order,o=Math.cos,l=Math.sin,c=o(n/2),h=o(s/2),d=o(r/2),f=l(n/2),m=l(s/2),_=l(r/2);switch(a){case"XYZ":this._x=f*h*d+c*m*_,this._y=c*m*d-f*h*_,this._z=c*h*_+f*m*d,this._w=c*h*d-f*m*_;break;case"YXZ":this._x=f*h*d+c*m*_,this._y=c*m*d-f*h*_,this._z=c*h*_-f*m*d,this._w=c*h*d+f*m*_;break;case"ZXY":this._x=f*h*d-c*m*_,this._y=c*m*d+f*h*_,this._z=c*h*_+f*m*d,this._w=c*h*d-f*m*_;break;case"ZYX":this._x=f*h*d-c*m*_,this._y=c*m*d+f*h*_,this._z=c*h*_-f*m*d,this._w=c*h*d+f*m*_;break;case"YZX":this._x=f*h*d+c*m*_,this._y=c*m*d+f*h*_,this._z=c*h*_-f*m*d,this._w=c*h*d-f*m*_;break;case"XZY":this._x=f*h*d-c*m*_,this._y=c*m*d-f*h*_,this._z=c*h*_+f*m*d,this._w=c*h*d+f*m*_;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+a)}return e===!0&&this._onChangeCallback(),this}setFromAxisAngle(t,e){let n=e/2,s=Math.sin(n);return this._x=t.x*s,this._y=t.y*s,this._z=t.z*s,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(t){let e=t.elements,n=e[0],s=e[4],r=e[8],a=e[1],o=e[5],l=e[9],c=e[2],h=e[6],d=e[10],f=n+o+d;if(f>0){let m=.5/Math.sqrt(f+1);this._w=.25/m,this._x=(h-l)*m,this._y=(r-c)*m,this._z=(a-s)*m}else if(n>o&&n>d){let m=2*Math.sqrt(1+n-o-d);this._w=(h-l)/m,this._x=.25*m,this._y=(s+a)/m,this._z=(r+c)/m}else if(o>d){let m=2*Math.sqrt(1+o-n-d);this._w=(r-c)/m,this._x=(s+a)/m,this._y=.25*m,this._z=(l+h)/m}else{let m=2*Math.sqrt(1+d-n-o);this._w=(a-s)/m,this._x=(r+c)/m,this._y=(l+h)/m,this._z=.25*m}return this._onChangeCallback(),this}setFromUnitVectors(t,e){let n=t.dot(e)+1;return n<1e-8?(n=0,Math.abs(t.x)>Math.abs(t.z)?(this._x=-t.y,this._y=t.x,this._z=0,this._w=n):(this._x=0,this._y=-t.z,this._z=t.y,this._w=n)):(this._x=t.y*e.z-t.z*e.y,this._y=t.z*e.x-t.x*e.z,this._z=t.x*e.y-t.y*e.x,this._w=n),this.normalize()}angleTo(t){return 2*Math.acos(Math.abs(Bt(this.dot(t),-1,1)))}rotateTowards(t,e){let n=this.angleTo(t);if(n===0)return this;let s=Math.min(1,e/n);return this.slerp(t,s),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let t=this.length();return t===0?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this._onChangeCallback(),this}multiply(t){return this.multiplyQuaternions(this,t)}premultiply(t){return this.multiplyQuaternions(t,this)}multiplyQuaternions(t,e){let n=t._x,s=t._y,r=t._z,a=t._w,o=e._x,l=e._y,c=e._z,h=e._w;return this._x=n*h+a*o+s*c-r*l,this._y=s*h+a*l+r*o-n*c,this._z=r*h+a*c+n*l-s*o,this._w=a*h-n*o-s*l-r*c,this._onChangeCallback(),this}slerp(t,e){if(e===0)return this;if(e===1)return this.copy(t);let n=this._x,s=this._y,r=this._z,a=this._w,o=a*t._w+n*t._x+s*t._y+r*t._z;if(o<0?(this._w=-t._w,this._x=-t._x,this._y=-t._y,this._z=-t._z,o=-o):this.copy(t),o>=1)return this._w=a,this._x=n,this._y=s,this._z=r,this;let l=1-o*o;if(l<=Number.EPSILON){let m=1-e;return this._w=m*a+e*this._w,this._x=m*n+e*this._x,this._y=m*s+e*this._y,this._z=m*r+e*this._z,this.normalize(),this}let c=Math.sqrt(l),h=Math.atan2(c,o),d=Math.sin((1-e)*h)/c,f=Math.sin(e*h)/c;return this._w=a*d+this._w*f,this._x=n*d+this._x*f,this._y=s*d+this._y*f,this._z=r*d+this._z*f,this._onChangeCallback(),this}slerpQuaternions(t,e,n){return this.copy(t).slerp(e,n)}random(){let t=2*Math.PI*Math.random(),e=2*Math.PI*Math.random(),n=Math.random(),s=Math.sqrt(1-n),r=Math.sqrt(n);return this.set(s*Math.sin(t),s*Math.cos(t),r*Math.sin(e),r*Math.cos(e))}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w}fromArray(t,e=0){return this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t}fromBufferAttribute(t,e){return this._x=t.getX(e),this._y=t.getY(e),this._z=t.getZ(e),this._w=t.getW(e),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}},N=class i{constructor(t=0,e=0,n=0){i.prototype.isVector3=!0,this.x=t,this.y=e,this.z=n}set(t,e,n){return n===void 0&&(n=this.z),this.x=t,this.y=e,this.z=n,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}multiplyVectors(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this}applyEuler(t){return this.applyQuaternion(ll.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(ll.setFromAxisAngle(t,e))}applyMatrix3(t){let e=this.x,n=this.y,s=this.z,r=t.elements;return this.x=r[0]*e+r[3]*n+r[6]*s,this.y=r[1]*e+r[4]*n+r[7]*s,this.z=r[2]*e+r[5]*n+r[8]*s,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){let e=this.x,n=this.y,s=this.z,r=t.elements,a=1/(r[3]*e+r[7]*n+r[11]*s+r[15]);return this.x=(r[0]*e+r[4]*n+r[8]*s+r[12])*a,this.y=(r[1]*e+r[5]*n+r[9]*s+r[13])*a,this.z=(r[2]*e+r[6]*n+r[10]*s+r[14])*a,this}applyQuaternion(t){let e=this.x,n=this.y,s=this.z,r=t.x,a=t.y,o=t.z,l=t.w,c=2*(a*s-o*n),h=2*(o*e-r*s),d=2*(r*n-a*e);return this.x=e+l*c+a*d-o*h,this.y=n+l*h+o*c-r*d,this.z=s+l*d+r*h-a*c,this}project(t){return this.applyMatrix4(t.matrixWorldInverse).applyMatrix4(t.projectionMatrix)}unproject(t){return this.applyMatrix4(t.projectionMatrixInverse).applyMatrix4(t.matrixWorld)}transformDirection(t){let e=this.x,n=this.y,s=this.z,r=t.elements;return this.x=r[0]*e+r[4]*n+r[8]*s,this.y=r[1]*e+r[5]*n+r[9]*s,this.z=r[2]*e+r[6]*n+r[10]*s,this.normalize()}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this}divideScalar(t){return this.multiplyScalar(1/t)}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this}clamp(t,e){return this.x=Bt(this.x,t.x,e.x),this.y=Bt(this.y,t.y,e.y),this.z=Bt(this.z,t.z,e.z),this}clampScalar(t,e){return this.x=Bt(this.x,t,e),this.y=Bt(this.y,t,e),this.z=Bt(this.z,t,e),this}clampLength(t,e){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Bt(n,t,e))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this}lerpVectors(t,e,n){return this.x=t.x+(e.x-t.x)*n,this.y=t.y+(e.y-t.y)*n,this.z=t.z+(e.z-t.z)*n,this}cross(t){return this.crossVectors(this,t)}crossVectors(t,e){let n=t.x,s=t.y,r=t.z,a=e.x,o=e.y,l=e.z;return this.x=s*l-r*o,this.y=r*a-n*l,this.z=n*o-s*a,this}projectOnVector(t){let e=t.lengthSq();if(e===0)return this.set(0,0,0);let n=t.dot(this)/e;return this.copy(t).multiplyScalar(n)}projectOnPlane(t){return Ra.copy(this).projectOnVector(t),this.sub(Ra)}reflect(t){return this.sub(Ra.copy(t).multiplyScalar(2*this.dot(t)))}angleTo(t){let e=Math.sqrt(this.lengthSq()*t.lengthSq());if(e===0)return Math.PI/2;let n=this.dot(t)/e;return Math.acos(Bt(n,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){let e=this.x-t.x,n=this.y-t.y,s=this.z-t.z;return e*e+n*n+s*s}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)}setFromSpherical(t){return this.setFromSphericalCoords(t.radius,t.phi,t.theta)}setFromSphericalCoords(t,e,n){let s=Math.sin(e)*t;return this.x=s*Math.sin(n),this.y=Math.cos(e)*t,this.z=s*Math.cos(n),this}setFromCylindrical(t){return this.setFromCylindricalCoords(t.radius,t.theta,t.y)}setFromCylindricalCoords(t,e,n){return this.x=t*Math.sin(e),this.y=n,this.z=t*Math.cos(e),this}setFromMatrixPosition(t){let e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}setFromMatrixScale(t){let e=this.setFromMatrixColumn(t,0).length(),n=this.setFromMatrixColumn(t,1).length(),s=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=n,this.z=s,this}setFromMatrixColumn(t,e){return this.fromArray(t.elements,e*4)}setFromMatrix3Column(t,e){return this.fromArray(t.elements,e*3)}setFromEuler(t){return this.x=t._x,this.y=t._y,this.z=t._z,this}setFromColor(t){return this.x=t.r,this.y=t.g,this.z=t.b,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let t=Math.random()*Math.PI*2,e=Math.random()*2-1,n=Math.sqrt(1-e*e);return this.x=n*Math.cos(t),this.y=e,this.z=n*Math.sin(t),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}},Ra=new N,ll=new qe,Ut=class i{constructor(t,e,n,s,r,a,o,l,c){i.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],t!==void 0&&this.set(t,e,n,s,r,a,o,l,c)}set(t,e,n,s,r,a,o,l,c){let h=this.elements;return h[0]=t,h[1]=s,h[2]=o,h[3]=e,h[4]=r,h[5]=l,h[6]=n,h[7]=a,h[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(t){let e=this.elements,n=t.elements;return e[0]=n[0],e[1]=n[1],e[2]=n[2],e[3]=n[3],e[4]=n[4],e[5]=n[5],e[6]=n[6],e[7]=n[7],e[8]=n[8],this}extractBasis(t,e,n){return t.setFromMatrix3Column(this,0),e.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(t){let e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){let n=t.elements,s=e.elements,r=this.elements,a=n[0],o=n[3],l=n[6],c=n[1],h=n[4],d=n[7],f=n[2],m=n[5],_=n[8],M=s[0],p=s[3],u=s[6],T=s[1],E=s[4],S=s[7],C=s[2],A=s[5],P=s[8];return r[0]=a*M+o*T+l*C,r[3]=a*p+o*E+l*A,r[6]=a*u+o*S+l*P,r[1]=c*M+h*T+d*C,r[4]=c*p+h*E+d*A,r[7]=c*u+h*S+d*P,r[2]=f*M+m*T+_*C,r[5]=f*p+m*E+_*A,r[8]=f*u+m*S+_*P,this}multiplyScalar(t){let e=this.elements;return e[0]*=t,e[3]*=t,e[6]*=t,e[1]*=t,e[4]*=t,e[7]*=t,e[2]*=t,e[5]*=t,e[8]*=t,this}determinant(){let t=this.elements,e=t[0],n=t[1],s=t[2],r=t[3],a=t[4],o=t[5],l=t[6],c=t[7],h=t[8];return e*a*h-e*o*c-n*r*h+n*o*l+s*r*c-s*a*l}invert(){let t=this.elements,e=t[0],n=t[1],s=t[2],r=t[3],a=t[4],o=t[5],l=t[6],c=t[7],h=t[8],d=h*a-o*c,f=o*l-h*r,m=c*r-a*l,_=e*d+n*f+s*m;if(_===0)return this.set(0,0,0,0,0,0,0,0,0);let M=1/_;return t[0]=d*M,t[1]=(s*c-h*n)*M,t[2]=(o*n-s*a)*M,t[3]=f*M,t[4]=(h*e-s*l)*M,t[5]=(s*r-o*e)*M,t[6]=m*M,t[7]=(n*l-c*e)*M,t[8]=(a*e-n*r)*M,this}transpose(){let t,e=this.elements;return t=e[1],e[1]=e[3],e[3]=t,t=e[2],e[2]=e[6],e[6]=t,t=e[5],e[5]=e[7],e[7]=t,this}getNormalMatrix(t){return this.setFromMatrix4(t).invert().transpose()}transposeIntoArray(t){let e=this.elements;return t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8],this}setUvTransform(t,e,n,s,r,a,o){let l=Math.cos(r),c=Math.sin(r);return this.set(n*l,n*c,-n*(l*a+c*o)+a+t,-s*c,s*l,-s*(-c*a+l*o)+o+e,0,0,1),this}scale(t,e){return this.premultiply(Ia.makeScale(t,e)),this}rotate(t){return this.premultiply(Ia.makeRotation(-t)),this}translate(t,e){return this.premultiply(Ia.makeTranslation(t,e)),this}makeTranslation(t,e){return t.isVector2?this.set(1,0,t.x,0,1,t.y,0,0,1):this.set(1,0,t,0,1,e,0,0,1),this}makeRotation(t){let e=Math.cos(t),n=Math.sin(t);return this.set(e,-n,0,n,e,0,0,0,1),this}makeScale(t,e){return this.set(t,0,0,0,e,0,0,0,1),this}equals(t){let e=this.elements,n=t.elements;for(let s=0;s<9;s++)if(e[s]!==n[s])return!1;return!0}fromArray(t,e=0){for(let n=0;n<9;n++)this.elements[n]=t[n+e];return this}toArray(t=[],e=0){let n=this.elements;return t[e]=n[0],t[e+1]=n[1],t[e+2]=n[2],t[e+3]=n[3],t[e+4]=n[4],t[e+5]=n[5],t[e+6]=n[6],t[e+7]=n[7],t[e+8]=n[8],t}clone(){return new this.constructor().fromArray(this.elements)}},Ia=new Ut;function wo(i){for(let t=i.length-1;t>=0;--t)if(i[t]>=65535)return!0;return!1}function ls(i){return document.createElementNS("http://www.w3.org/1999/xhtml",i)}function dc(){let i=ls("canvas");return i.style.display="block",i}var cl={};function Pi(i){i in cl||(cl[i]=!0,console.warn(i))}function fc(i,t,e){return new Promise(function(n,s){function r(){switch(i.clientWaitSync(t,i.SYNC_FLUSH_COMMANDS_BIT,0)){case i.WAIT_FAILED:s();break;case i.TIMEOUT_EXPIRED:setTimeout(r,e);break;default:n()}}setTimeout(r,e)})}var hl=new Ut().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),ul=new Ut().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Ah(){let i={enabled:!0,workingColorSpace:bn,spaces:{},convert:function(s,r,a){return this.enabled===!1||r===a||!r||!a||(this.spaces[r].transfer===Yt&&(s.r=Mn(s.r),s.g=Mn(s.g),s.b=Mn(s.b)),this.spaces[r].primaries!==this.spaces[a].primaries&&(s.applyMatrix3(this.spaces[r].toXYZ),s.applyMatrix3(this.spaces[a].fromXYZ)),this.spaces[a].transfer===Yt&&(s.r=Ci(s.r),s.g=Ci(s.g),s.b=Ci(s.b))),s},workingToColorSpace:function(s,r){return this.convert(s,this.workingColorSpace,r)},colorSpaceToWorking:function(s,r){return this.convert(s,r,this.workingColorSpace)},getPrimaries:function(s){return this.spaces[s].primaries},getTransfer:function(s){return s===wn?as:this.spaces[s].transfer},getToneMappingMode:function(s){return this.spaces[s].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(s,r=this.workingColorSpace){return s.fromArray(this.spaces[r].luminanceCoefficients)},define:function(s){Object.assign(this.spaces,s)},_getMatrix:function(s,r,a){return s.copy(this.spaces[r].toXYZ).multiply(this.spaces[a].fromXYZ)},_getDrawingBufferColorSpace:function(s){return this.spaces[s].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(s=this.workingColorSpace){return this.spaces[s].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(s,r){return Pi("THREE.ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),i.workingToColorSpace(s,r)},toWorkingColorSpace:function(s,r){return Pi("THREE.ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),i.colorSpaceToWorking(s,r)}},t=[.64,.33,.3,.6,.15,.06],e=[.2126,.7152,.0722],n=[.3127,.329];return i.define({[bn]:{primaries:t,whitePoint:n,transfer:as,toXYZ:hl,fromXYZ:ul,luminanceCoefficients:e,workingColorSpaceConfig:{unpackColorSpace:Ce},outputColorSpaceConfig:{drawingBufferColorSpace:Ce}},[Ce]:{primaries:t,whitePoint:n,transfer:Yt,toXYZ:hl,fromXYZ:ul,luminanceCoefficients:e,outputColorSpaceConfig:{drawingBufferColorSpace:Ce}}}),i}var Gt=Ah();function Mn(i){return i<.04045?i*.0773993808:Math.pow(i*.9478672986+.0521327014,2.4)}function Ci(i){return i<.0031308?i*12.92:1.055*Math.pow(i,.41666)-.055}var mi,lr=class{static getDataURL(t,e="image/png"){if(/^data:/i.test(t.src)||typeof HTMLCanvasElement>"u")return t.src;let n;if(t instanceof HTMLCanvasElement)n=t;else{mi===void 0&&(mi=ls("canvas")),mi.width=t.width,mi.height=t.height;let s=mi.getContext("2d");t instanceof ImageData?s.putImageData(t,0,0):s.drawImage(t,0,0,t.width,t.height),n=mi}return n.toDataURL(e)}static sRGBToLinear(t){if(typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&t instanceof ImageBitmap){let e=ls("canvas");e.width=t.width,e.height=t.height;let n=e.getContext("2d");n.drawImage(t,0,0,t.width,t.height);let s=n.getImageData(0,0,t.width,t.height),r=s.data;for(let a=0;a1),this.pmremVersion=0}get width(){return this.source.getSize(Da).x}get height(){return this.source.getSize(Da).y}get depth(){return this.source.getSize(Da).z}get image(){return this.source.data}set image(t=null){this.source.data=t}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(t){return this.name=t.name,this.source=t.source,this.mipmaps=t.mipmaps.slice(0),this.mapping=t.mapping,this.channel=t.channel,this.wrapS=t.wrapS,this.wrapT=t.wrapT,this.magFilter=t.magFilter,this.minFilter=t.minFilter,this.anisotropy=t.anisotropy,this.format=t.format,this.internalFormat=t.internalFormat,this.type=t.type,this.offset.copy(t.offset),this.repeat.copy(t.repeat),this.center.copy(t.center),this.rotation=t.rotation,this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrix.copy(t.matrix),this.generateMipmaps=t.generateMipmaps,this.premultiplyAlpha=t.premultiplyAlpha,this.flipY=t.flipY,this.unpackAlignment=t.unpackAlignment,this.colorSpace=t.colorSpace,this.renderTarget=t.renderTarget,this.isRenderTargetTexture=t.isRenderTargetTexture,this.isArrayTexture=t.isArrayTexture,this.userData=JSON.parse(JSON.stringify(t.userData)),this.needsUpdate=!0,this}setValues(t){for(let e in t){let n=t[e];if(n===void 0){console.warn(`THREE.Texture.setValues(): parameter '${e}' has value of undefined.`);continue}let s=this[e];if(s===void 0){console.warn(`THREE.Texture.setValues(): property '${e}' does not exist.`);continue}s&&n&&s.isVector2&&n.isVector2||s&&n&&s.isVector3&&n.isVector3||s&&n&&s.isMatrix3&&n.isMatrix3?s.copy(n):this[e]=n}}toJSON(t){let e=t===void 0||typeof t=="string";if(!e&&t.textures[this.uuid]!==void 0)return t.textures[this.uuid];let n={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(t).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),e||(t.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(t){if(this.mapping!==uo)return t;if(t.applyMatrix3(this.matrix),t.x<0||t.x>1)switch(this.wrapS){case rr:t.x=t.x-Math.floor(t.x);break;case Fn:t.x=t.x<0?0:1;break;case ar:Math.abs(Math.floor(t.x)%2)===1?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x);break}if(t.y<0||t.y>1)switch(this.wrapT){case rr:t.y=t.y-Math.floor(t.y);break;case Fn:t.y=t.y<0?0:1;break;case ar:Math.abs(Math.floor(t.y)%2)===1?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y);break}return this.flipY&&(t.y=1-t.y),t}set needsUpdate(t){t===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(t){t===!0&&this.pmremVersion++}};Be.DEFAULT_IMAGE=null;Be.DEFAULT_MAPPING=uo;Be.DEFAULT_ANISOTROPY=1;var le=class i{constructor(t=0,e=0,n=0,s=1){i.prototype.isVector4=!0,this.x=t,this.y=e,this.z=n,this.w=s}get width(){return this.z}set width(t){this.z=t}get height(){return this.w}set height(t){this.w=t}set(t,e,n,s){return this.x=t,this.y=e,this.z=n,this.w=s,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this.w=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setW(t){return this.w=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;case 3:this.w=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w!==void 0?t.w:1,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this}applyMatrix4(t){let e=this.x,n=this.y,s=this.z,r=this.w,a=t.elements;return this.x=a[0]*e+a[4]*n+a[8]*s+a[12]*r,this.y=a[1]*e+a[5]*n+a[9]*s+a[13]*r,this.z=a[2]*e+a[6]*n+a[10]*s+a[14]*r,this.w=a[3]*e+a[7]*n+a[11]*s+a[15]*r,this}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this.w/=t.w,this}divideScalar(t){return this.multiplyScalar(1/t)}setAxisAngleFromQuaternion(t){this.w=2*Math.acos(t.w);let e=Math.sqrt(1-t.w*t.w);return e<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=t.x/e,this.y=t.y/e,this.z=t.z/e),this}setAxisAngleFromRotationMatrix(t){let e,n,s,r,l=t.elements,c=l[0],h=l[4],d=l[8],f=l[1],m=l[5],_=l[9],M=l[2],p=l[6],u=l[10];if(Math.abs(h-f)<.01&&Math.abs(d-M)<.01&&Math.abs(_-p)<.01){if(Math.abs(h+f)<.1&&Math.abs(d+M)<.1&&Math.abs(_+p)<.1&&Math.abs(c+m+u-3)<.1)return this.set(1,0,0,0),this;e=Math.PI;let E=(c+1)/2,S=(m+1)/2,C=(u+1)/2,A=(h+f)/4,P=(d+M)/4,U=(_+p)/4;return E>S&&E>C?E<.01?(n=0,s=.707106781,r=.707106781):(n=Math.sqrt(E),s=A/n,r=P/n):S>C?S<.01?(n=.707106781,s=0,r=.707106781):(s=Math.sqrt(S),n=A/s,r=U/s):C<.01?(n=.707106781,s=.707106781,r=0):(r=Math.sqrt(C),n=P/r,s=U/r),this.set(n,s,r,e),this}let T=Math.sqrt((p-_)*(p-_)+(d-M)*(d-M)+(f-h)*(f-h));return Math.abs(T)<.001&&(T=1),this.x=(p-_)/T,this.y=(d-M)/T,this.z=(f-h)/T,this.w=Math.acos((c+m+u-1)/2),this}setFromMatrixPosition(t){let e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this.w=e[15],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this.w=Math.min(this.w,t.w),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this.w=Math.max(this.w,t.w),this}clamp(t,e){return this.x=Bt(this.x,t.x,e.x),this.y=Bt(this.y,t.y,e.y),this.z=Bt(this.z,t.z,e.z),this.w=Bt(this.w,t.w,e.w),this}clampScalar(t,e){return this.x=Bt(this.x,t,e),this.y=Bt(this.y,t,e),this.z=Bt(this.z,t,e),this.w=Bt(this.w,t,e),this}clampLength(t,e){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Bt(n,t,e))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this.w+=(t.w-this.w)*e,this}lerpVectors(t,e,n){return this.x=t.x+(e.x-t.x)*n,this.y=t.y+(e.y-t.y)*n,this.z=t.z+(e.z-t.z)*n,this.w=t.w+(e.w-t.w)*n,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z&&t.w===this.w}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this.w=t[e+3],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t[e+3]=this.w,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this.w=t.getW(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}},cr=class extends ln{constructor(t=1,e=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:nn,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},n),this.isRenderTarget=!0,this.width=t,this.height=e,this.depth=n.depth,this.scissor=new le(0,0,t,e),this.scissorTest=!1,this.viewport=new le(0,0,t,e);let s={width:t,height:e,depth:n.depth},r=new Be(s);this.textures=[];let a=n.count;for(let o=0;o1;this.dispose()}this.viewport.set(0,0,t,e),this.scissor.set(0,0,t,e)}clone(){return new this.constructor().copy(this)}copy(t){this.width=t.width,this.height=t.height,this.depth=t.depth,this.scissor.copy(t.scissor),this.scissorTest=t.scissorTest,this.viewport.copy(t.viewport),this.textures.length=0;for(let e=0,n=t.textures.length;e=this.min.x&&t.x<=this.max.x&&t.y>=this.min.y&&t.y<=this.max.y&&t.z>=this.min.z&&t.z<=this.max.z}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y&&this.min.z<=t.min.z&&t.max.z<=this.max.z}getParameter(t,e){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y),(t.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(t){return t.max.x>=this.min.x&&t.min.x<=this.max.x&&t.max.y>=this.min.y&&t.min.y<=this.max.y&&t.max.z>=this.min.z&&t.min.z<=this.max.z}intersectsSphere(t){return this.clampPoint(t.center,je),je.distanceToSquared(t.center)<=t.radius*t.radius}intersectsPlane(t){let e,n;return t.normal.x>0?(e=t.normal.x*this.min.x,n=t.normal.x*this.max.x):(e=t.normal.x*this.max.x,n=t.normal.x*this.min.x),t.normal.y>0?(e+=t.normal.y*this.min.y,n+=t.normal.y*this.max.y):(e+=t.normal.y*this.max.y,n+=t.normal.y*this.min.y),t.normal.z>0?(e+=t.normal.z*this.min.z,n+=t.normal.z*this.max.z):(e+=t.normal.z*this.max.z,n+=t.normal.z*this.min.z),e<=-t.constant&&n>=-t.constant}intersectsTriangle(t){if(this.isEmpty())return!1;this.getCenter(Qi),zs.subVectors(this.max,Qi),gi.subVectors(t.a,Qi),_i.subVectors(t.b,Qi),xi.subVectors(t.c,Qi),Rn.subVectors(_i,gi),In.subVectors(xi,_i),$n.subVectors(gi,xi);let e=[0,-Rn.z,Rn.y,0,-In.z,In.y,0,-$n.z,$n.y,Rn.z,0,-Rn.x,In.z,0,-In.x,$n.z,0,-$n.x,-Rn.y,Rn.x,0,-In.y,In.x,0,-$n.y,$n.x,0];return!La(e,gi,_i,xi,zs)||(e=[1,0,0,0,1,0,0,0,1],!La(e,gi,_i,xi,zs))?!1:(ks.crossVectors(Rn,In),e=[ks.x,ks.y,ks.z],La(e,gi,_i,xi,zs))}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return this.clampPoint(t,je).distanceTo(t)}getBoundingSphere(t){return this.isEmpty()?t.makeEmpty():(this.getCenter(t.center),t.radius=this.getSize(je).length()*.5),t}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this}union(t){return this.min.min(t.min),this.max.max(t.max),this}applyMatrix4(t){return this.isEmpty()?this:(mn[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(t),mn[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(t),mn[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(t),mn[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(t),mn[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(t),mn[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(t),mn[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(t),mn[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(t),this.setFromPoints(mn),this)}translate(t){return this.min.add(t),this.max.add(t),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(t){return this.min.fromArray(t.min),this.max.fromArray(t.max),this}},mn=[new N,new N,new N,new N,new N,new N,new N,new N],je=new N,Bs=new Bn,gi=new N,_i=new N,xi=new N,Rn=new N,In=new N,$n=new N,Qi=new N,zs=new N,ks=new N,Kn=new N;function La(i,t,e,n,s){for(let r=0,a=i.length-3;r<=a;r+=3){Kn.fromArray(i,r);let o=s.x*Math.abs(Kn.x)+s.y*Math.abs(Kn.y)+s.z*Math.abs(Kn.z),l=t.dot(Kn),c=e.dot(Kn),h=n.dot(Kn);if(Math.max(-Math.max(l,c,h),Math.min(l,c,h))>o)return!1}return!0}var Ih=new Bn,ts=new N,Ua=new N,Li=class{constructor(t=new N,e=-1){this.isSphere=!0,this.center=t,this.radius=e}set(t,e){return this.center.copy(t),this.radius=e,this}setFromPoints(t,e){let n=this.center;e!==void 0?n.copy(e):Ih.setFromPoints(t).getCenter(n);let s=0;for(let r=0,a=t.length;rthis.radius*this.radius&&(e.sub(this.center).normalize(),e.multiplyScalar(this.radius).add(this.center)),e}getBoundingBox(t){return this.isEmpty()?(t.makeEmpty(),t):(t.set(this.center,this.center),t.expandByScalar(this.radius),t)}applyMatrix4(t){return this.center.applyMatrix4(t),this.radius=this.radius*t.getMaxScaleOnAxis(),this}translate(t){return this.center.add(t),this}expandByPoint(t){if(this.isEmpty())return this.center.copy(t),this.radius=0,this;ts.subVectors(t,this.center);let e=ts.lengthSq();if(e>this.radius*this.radius){let n=Math.sqrt(e),s=(n-this.radius)*.5;this.center.addScaledVector(ts,s/n),this.radius+=s}return this}union(t){return t.isEmpty()?this:this.isEmpty()?(this.copy(t),this):(this.center.equals(t.center)===!0?this.radius=Math.max(this.radius,t.radius):(Ua.subVectors(t.center,this.center).setLength(t.radius),this.expandByPoint(ts.copy(t.center).add(Ua)),this.expandByPoint(ts.copy(t.center).sub(Ua))),this)}equals(t){return t.center.equals(this.center)&&t.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(t){return this.radius=t.radius,this.center.fromArray(t.center),this}},gn=new N,Na=new N,Vs=new N,Pn=new N,Fa=new N,Hs=new N,Oa=new N,Ui=class{constructor(t=new N,e=new N(0,0,-1)){this.origin=t,this.direction=e}set(t,e){return this.origin.copy(t),this.direction.copy(e),this}copy(t){return this.origin.copy(t.origin),this.direction.copy(t.direction),this}at(t,e){return e.copy(this.origin).addScaledVector(this.direction,t)}lookAt(t){return this.direction.copy(t).sub(this.origin).normalize(),this}recast(t){return this.origin.copy(this.at(t,gn)),this}closestPointToPoint(t,e){e.subVectors(t,this.origin);let n=e.dot(this.direction);return n<0?e.copy(this.origin):e.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(t){return Math.sqrt(this.distanceSqToPoint(t))}distanceSqToPoint(t){let e=gn.subVectors(t,this.origin).dot(this.direction);return e<0?this.origin.distanceToSquared(t):(gn.copy(this.origin).addScaledVector(this.direction,e),gn.distanceToSquared(t))}distanceSqToSegment(t,e,n,s){Na.copy(t).add(e).multiplyScalar(.5),Vs.copy(e).sub(t).normalize(),Pn.copy(this.origin).sub(Na);let r=t.distanceTo(e)*.5,a=-this.direction.dot(Vs),o=Pn.dot(this.direction),l=-Pn.dot(Vs),c=Pn.lengthSq(),h=Math.abs(1-a*a),d,f,m,_;if(h>0)if(d=a*l-o,f=a*o-l,_=r*h,d>=0)if(f>=-_)if(f<=_){let M=1/h;d*=M,f*=M,m=d*(d+a*f+2*o)+f*(a*d+f+2*l)+c}else f=r,d=Math.max(0,-(a*f+o)),m=-d*d+f*(f+2*l)+c;else f=-r,d=Math.max(0,-(a*f+o)),m=-d*d+f*(f+2*l)+c;else f<=-_?(d=Math.max(0,-(-a*r+o)),f=d>0?-r:Math.min(Math.max(-r,-l),r),m=-d*d+f*(f+2*l)+c):f<=_?(d=0,f=Math.min(Math.max(-r,-l),r),m=f*(f+2*l)+c):(d=Math.max(0,-(a*r+o)),f=d>0?r:Math.min(Math.max(-r,-l),r),m=-d*d+f*(f+2*l)+c);else f=a>0?-r:r,d=Math.max(0,-(a*f+o)),m=-d*d+f*(f+2*l)+c;return n&&n.copy(this.origin).addScaledVector(this.direction,d),s&&s.copy(Na).addScaledVector(Vs,f),m}intersectSphere(t,e){gn.subVectors(t.center,this.origin);let n=gn.dot(this.direction),s=gn.dot(gn)-n*n,r=t.radius*t.radius;if(s>r)return null;let a=Math.sqrt(r-s),o=n-a,l=n+a;return l<0?null:o<0?this.at(l,e):this.at(o,e)}intersectsSphere(t){return t.radius<0?!1:this.distanceSqToPoint(t.center)<=t.radius*t.radius}distanceToPlane(t){let e=t.normal.dot(this.direction);if(e===0)return t.distanceToPoint(this.origin)===0?0:null;let n=-(this.origin.dot(t.normal)+t.constant)/e;return n>=0?n:null}intersectPlane(t,e){let n=this.distanceToPlane(t);return n===null?null:this.at(n,e)}intersectsPlane(t){let e=t.distanceToPoint(this.origin);return e===0||t.normal.dot(this.direction)*e<0}intersectBox(t,e){let n,s,r,a,o,l,c=1/this.direction.x,h=1/this.direction.y,d=1/this.direction.z,f=this.origin;return c>=0?(n=(t.min.x-f.x)*c,s=(t.max.x-f.x)*c):(n=(t.max.x-f.x)*c,s=(t.min.x-f.x)*c),h>=0?(r=(t.min.y-f.y)*h,a=(t.max.y-f.y)*h):(r=(t.max.y-f.y)*h,a=(t.min.y-f.y)*h),n>a||r>s||((r>n||isNaN(n))&&(n=r),(a=0?(o=(t.min.z-f.z)*d,l=(t.max.z-f.z)*d):(o=(t.max.z-f.z)*d,l=(t.min.z-f.z)*d),n>l||o>s)||((o>n||n!==n)&&(n=o),(l=0?n:s,e)}intersectsBox(t){return this.intersectBox(t,gn)!==null}intersectTriangle(t,e,n,s,r){Fa.subVectors(e,t),Hs.subVectors(n,t),Oa.crossVectors(Fa,Hs);let a=this.direction.dot(Oa),o;if(a>0){if(s)return null;o=1}else if(a<0)o=-1,a=-a;else return null;Pn.subVectors(this.origin,t);let l=o*this.direction.dot(Hs.crossVectors(Pn,Hs));if(l<0)return null;let c=o*this.direction.dot(Fa.cross(Pn));if(c<0||l+c>a)return null;let h=-o*Pn.dot(Oa);return h<0?null:this.at(h/a,r)}applyMatrix4(t){return this.origin.applyMatrix4(t),this.direction.transformDirection(t),this}equals(t){return t.origin.equals(this.origin)&&t.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}},ue=class i{constructor(t,e,n,s,r,a,o,l,c,h,d,f,m,_,M,p){i.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],t!==void 0&&this.set(t,e,n,s,r,a,o,l,c,h,d,f,m,_,M,p)}set(t,e,n,s,r,a,o,l,c,h,d,f,m,_,M,p){let u=this.elements;return u[0]=t,u[4]=e,u[8]=n,u[12]=s,u[1]=r,u[5]=a,u[9]=o,u[13]=l,u[2]=c,u[6]=h,u[10]=d,u[14]=f,u[3]=m,u[7]=_,u[11]=M,u[15]=p,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new i().fromArray(this.elements)}copy(t){let e=this.elements,n=t.elements;return e[0]=n[0],e[1]=n[1],e[2]=n[2],e[3]=n[3],e[4]=n[4],e[5]=n[5],e[6]=n[6],e[7]=n[7],e[8]=n[8],e[9]=n[9],e[10]=n[10],e[11]=n[11],e[12]=n[12],e[13]=n[13],e[14]=n[14],e[15]=n[15],this}copyPosition(t){let e=this.elements,n=t.elements;return e[12]=n[12],e[13]=n[13],e[14]=n[14],this}setFromMatrix3(t){let e=t.elements;return this.set(e[0],e[3],e[6],0,e[1],e[4],e[7],0,e[2],e[5],e[8],0,0,0,0,1),this}extractBasis(t,e,n){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this}makeBasis(t,e,n){return this.set(t.x,e.x,n.x,0,t.y,e.y,n.y,0,t.z,e.z,n.z,0,0,0,0,1),this}extractRotation(t){let e=this.elements,n=t.elements,s=1/yi.setFromMatrixColumn(t,0).length(),r=1/yi.setFromMatrixColumn(t,1).length(),a=1/yi.setFromMatrixColumn(t,2).length();return e[0]=n[0]*s,e[1]=n[1]*s,e[2]=n[2]*s,e[3]=0,e[4]=n[4]*r,e[5]=n[5]*r,e[6]=n[6]*r,e[7]=0,e[8]=n[8]*a,e[9]=n[9]*a,e[10]=n[10]*a,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromEuler(t){let e=this.elements,n=t.x,s=t.y,r=t.z,a=Math.cos(n),o=Math.sin(n),l=Math.cos(s),c=Math.sin(s),h=Math.cos(r),d=Math.sin(r);if(t.order==="XYZ"){let f=a*h,m=a*d,_=o*h,M=o*d;e[0]=l*h,e[4]=-l*d,e[8]=c,e[1]=m+_*c,e[5]=f-M*c,e[9]=-o*l,e[2]=M-f*c,e[6]=_+m*c,e[10]=a*l}else if(t.order==="YXZ"){let f=l*h,m=l*d,_=c*h,M=c*d;e[0]=f+M*o,e[4]=_*o-m,e[8]=a*c,e[1]=a*d,e[5]=a*h,e[9]=-o,e[2]=m*o-_,e[6]=M+f*o,e[10]=a*l}else if(t.order==="ZXY"){let f=l*h,m=l*d,_=c*h,M=c*d;e[0]=f-M*o,e[4]=-a*d,e[8]=_+m*o,e[1]=m+_*o,e[5]=a*h,e[9]=M-f*o,e[2]=-a*c,e[6]=o,e[10]=a*l}else if(t.order==="ZYX"){let f=a*h,m=a*d,_=o*h,M=o*d;e[0]=l*h,e[4]=_*c-m,e[8]=f*c+M,e[1]=l*d,e[5]=M*c+f,e[9]=m*c-_,e[2]=-c,e[6]=o*l,e[10]=a*l}else if(t.order==="YZX"){let f=a*l,m=a*c,_=o*l,M=o*c;e[0]=l*h,e[4]=M-f*d,e[8]=_*d+m,e[1]=d,e[5]=a*h,e[9]=-o*h,e[2]=-c*h,e[6]=m*d+_,e[10]=f-M*d}else if(t.order==="XZY"){let f=a*l,m=a*c,_=o*l,M=o*c;e[0]=l*h,e[4]=-d,e[8]=c*h,e[1]=f*d+M,e[5]=a*h,e[9]=m*d-_,e[2]=_*d-m,e[6]=o*h,e[10]=M*d+f}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromQuaternion(t){return this.compose(Ph,t,Dh)}lookAt(t,e,n){let s=this.elements;return Fe.subVectors(t,e),Fe.lengthSq()===0&&(Fe.z=1),Fe.normalize(),Dn.crossVectors(n,Fe),Dn.lengthSq()===0&&(Math.abs(n.z)===1?Fe.x+=1e-4:Fe.z+=1e-4,Fe.normalize(),Dn.crossVectors(n,Fe)),Dn.normalize(),Gs.crossVectors(Fe,Dn),s[0]=Dn.x,s[4]=Gs.x,s[8]=Fe.x,s[1]=Dn.y,s[5]=Gs.y,s[9]=Fe.y,s[2]=Dn.z,s[6]=Gs.z,s[10]=Fe.z,this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){let n=t.elements,s=e.elements,r=this.elements,a=n[0],o=n[4],l=n[8],c=n[12],h=n[1],d=n[5],f=n[9],m=n[13],_=n[2],M=n[6],p=n[10],u=n[14],T=n[3],E=n[7],S=n[11],C=n[15],A=s[0],P=s[4],U=s[8],v=s[12],y=s[1],R=s[5],F=s[9],k=s[13],H=s[2],q=s[6],W=s[10],et=s[14],V=s[3],rt=s[7],ct=s[11],bt=s[15];return r[0]=a*A+o*y+l*H+c*V,r[4]=a*P+o*R+l*q+c*rt,r[8]=a*U+o*F+l*W+c*ct,r[12]=a*v+o*k+l*et+c*bt,r[1]=h*A+d*y+f*H+m*V,r[5]=h*P+d*R+f*q+m*rt,r[9]=h*U+d*F+f*W+m*ct,r[13]=h*v+d*k+f*et+m*bt,r[2]=_*A+M*y+p*H+u*V,r[6]=_*P+M*R+p*q+u*rt,r[10]=_*U+M*F+p*W+u*ct,r[14]=_*v+M*k+p*et+u*bt,r[3]=T*A+E*y+S*H+C*V,r[7]=T*P+E*R+S*q+C*rt,r[11]=T*U+E*F+S*W+C*ct,r[15]=T*v+E*k+S*et+C*bt,this}multiplyScalar(t){let e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this}determinant(){let t=this.elements,e=t[0],n=t[4],s=t[8],r=t[12],a=t[1],o=t[5],l=t[9],c=t[13],h=t[2],d=t[6],f=t[10],m=t[14],_=t[3],M=t[7],p=t[11],u=t[15];return _*(+r*l*d-s*c*d-r*o*f+n*c*f+s*o*m-n*l*m)+M*(+e*l*m-e*c*f+r*a*f-s*a*m+s*c*h-r*l*h)+p*(+e*c*d-e*o*m-r*a*d+n*a*m+r*o*h-n*c*h)+u*(-s*o*h-e*l*d+e*o*f+s*a*d-n*a*f+n*l*h)}transpose(){let t=this.elements,e;return e=t[1],t[1]=t[4],t[4]=e,e=t[2],t[2]=t[8],t[8]=e,e=t[6],t[6]=t[9],t[9]=e,e=t[3],t[3]=t[12],t[12]=e,e=t[7],t[7]=t[13],t[13]=e,e=t[11],t[11]=t[14],t[14]=e,this}setPosition(t,e,n){let s=this.elements;return t.isVector3?(s[12]=t.x,s[13]=t.y,s[14]=t.z):(s[12]=t,s[13]=e,s[14]=n),this}invert(){let t=this.elements,e=t[0],n=t[1],s=t[2],r=t[3],a=t[4],o=t[5],l=t[6],c=t[7],h=t[8],d=t[9],f=t[10],m=t[11],_=t[12],M=t[13],p=t[14],u=t[15],T=d*p*c-M*f*c+M*l*m-o*p*m-d*l*u+o*f*u,E=_*f*c-h*p*c-_*l*m+a*p*m+h*l*u-a*f*u,S=h*M*c-_*d*c+_*o*m-a*M*m-h*o*u+a*d*u,C=_*d*l-h*M*l-_*o*f+a*M*f+h*o*p-a*d*p,A=e*T+n*E+s*S+r*C;if(A===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let P=1/A;return t[0]=T*P,t[1]=(M*f*r-d*p*r-M*s*m+n*p*m+d*s*u-n*f*u)*P,t[2]=(o*p*r-M*l*r+M*s*c-n*p*c-o*s*u+n*l*u)*P,t[3]=(d*l*r-o*f*r-d*s*c+n*f*c+o*s*m-n*l*m)*P,t[4]=E*P,t[5]=(h*p*r-_*f*r+_*s*m-e*p*m-h*s*u+e*f*u)*P,t[6]=(_*l*r-a*p*r-_*s*c+e*p*c+a*s*u-e*l*u)*P,t[7]=(a*f*r-h*l*r+h*s*c-e*f*c-a*s*m+e*l*m)*P,t[8]=S*P,t[9]=(_*d*r-h*M*r-_*n*m+e*M*m+h*n*u-e*d*u)*P,t[10]=(a*M*r-_*o*r+_*n*c-e*M*c-a*n*u+e*o*u)*P,t[11]=(h*o*r-a*d*r-h*n*c+e*d*c+a*n*m-e*o*m)*P,t[12]=C*P,t[13]=(h*M*s-_*d*s+_*n*f-e*M*f-h*n*p+e*d*p)*P,t[14]=(_*o*s-a*M*s-_*n*l+e*M*l+a*n*p-e*o*p)*P,t[15]=(a*d*s-h*o*s+h*n*l-e*d*l-a*n*f+e*o*f)*P,this}scale(t){let e=this.elements,n=t.x,s=t.y,r=t.z;return e[0]*=n,e[4]*=s,e[8]*=r,e[1]*=n,e[5]*=s,e[9]*=r,e[2]*=n,e[6]*=s,e[10]*=r,e[3]*=n,e[7]*=s,e[11]*=r,this}getMaxScaleOnAxis(){let t=this.elements,e=t[0]*t[0]+t[1]*t[1]+t[2]*t[2],n=t[4]*t[4]+t[5]*t[5]+t[6]*t[6],s=t[8]*t[8]+t[9]*t[9]+t[10]*t[10];return Math.sqrt(Math.max(e,n,s))}makeTranslation(t,e,n){return t.isVector3?this.set(1,0,0,t.x,0,1,0,t.y,0,0,1,t.z,0,0,0,1):this.set(1,0,0,t,0,1,0,e,0,0,1,n,0,0,0,1),this}makeRotationX(t){let e=Math.cos(t),n=Math.sin(t);return this.set(1,0,0,0,0,e,-n,0,0,n,e,0,0,0,0,1),this}makeRotationY(t){let e=Math.cos(t),n=Math.sin(t);return this.set(e,0,n,0,0,1,0,0,-n,0,e,0,0,0,0,1),this}makeRotationZ(t){let e=Math.cos(t),n=Math.sin(t);return this.set(e,-n,0,0,n,e,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(t,e){let n=Math.cos(e),s=Math.sin(e),r=1-n,a=t.x,o=t.y,l=t.z,c=r*a,h=r*o;return this.set(c*a+n,c*o-s*l,c*l+s*o,0,c*o+s*l,h*o+n,h*l-s*a,0,c*l-s*o,h*l+s*a,r*l*l+n,0,0,0,0,1),this}makeScale(t,e,n){return this.set(t,0,0,0,0,e,0,0,0,0,n,0,0,0,0,1),this}makeShear(t,e,n,s,r,a){return this.set(1,n,r,0,t,1,a,0,e,s,1,0,0,0,0,1),this}compose(t,e,n){let s=this.elements,r=e._x,a=e._y,o=e._z,l=e._w,c=r+r,h=a+a,d=o+o,f=r*c,m=r*h,_=r*d,M=a*h,p=a*d,u=o*d,T=l*c,E=l*h,S=l*d,C=n.x,A=n.y,P=n.z;return s[0]=(1-(M+u))*C,s[1]=(m+S)*C,s[2]=(_-E)*C,s[3]=0,s[4]=(m-S)*A,s[5]=(1-(f+u))*A,s[6]=(p+T)*A,s[7]=0,s[8]=(_+E)*P,s[9]=(p-T)*P,s[10]=(1-(f+M))*P,s[11]=0,s[12]=t.x,s[13]=t.y,s[14]=t.z,s[15]=1,this}decompose(t,e,n){let s=this.elements,r=yi.set(s[0],s[1],s[2]).length(),a=yi.set(s[4],s[5],s[6]).length(),o=yi.set(s[8],s[9],s[10]).length();this.determinant()<0&&(r=-r),t.x=s[12],t.y=s[13],t.z=s[14],Qe.copy(this);let c=1/r,h=1/a,d=1/o;return Qe.elements[0]*=c,Qe.elements[1]*=c,Qe.elements[2]*=c,Qe.elements[4]*=h,Qe.elements[5]*=h,Qe.elements[6]*=h,Qe.elements[8]*=d,Qe.elements[9]*=d,Qe.elements[10]*=d,e.setFromRotationMatrix(Qe),n.x=r,n.y=a,n.z=o,this}makePerspective(t,e,n,s,r,a,o=en,l=!1){let c=this.elements,h=2*r/(e-t),d=2*r/(n-s),f=(e+t)/(e-t),m=(n+s)/(n-s),_,M;if(l)_=r/(a-r),M=a*r/(a-r);else if(o===en)_=-(a+r)/(a-r),M=-2*a*r/(a-r);else if(o===os)_=-a/(a-r),M=-a*r/(a-r);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return c[0]=h,c[4]=0,c[8]=f,c[12]=0,c[1]=0,c[5]=d,c[9]=m,c[13]=0,c[2]=0,c[6]=0,c[10]=_,c[14]=M,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(t,e,n,s,r,a,o=en,l=!1){let c=this.elements,h=2/(e-t),d=2/(n-s),f=-(e+t)/(e-t),m=-(n+s)/(n-s),_,M;if(l)_=1/(a-r),M=a/(a-r);else if(o===en)_=-2/(a-r),M=-(a+r)/(a-r);else if(o===os)_=-1/(a-r),M=-r/(a-r);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return c[0]=h,c[4]=0,c[8]=0,c[12]=f,c[1]=0,c[5]=d,c[9]=0,c[13]=m,c[2]=0,c[6]=0,c[10]=_,c[14]=M,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(t){let e=this.elements,n=t.elements;for(let s=0;s<16;s++)if(e[s]!==n[s])return!1;return!0}fromArray(t,e=0){for(let n=0;n<16;n++)this.elements[n]=t[n+e];return this}toArray(t=[],e=0){let n=this.elements;return t[e]=n[0],t[e+1]=n[1],t[e+2]=n[2],t[e+3]=n[3],t[e+4]=n[4],t[e+5]=n[5],t[e+6]=n[6],t[e+7]=n[7],t[e+8]=n[8],t[e+9]=n[9],t[e+10]=n[10],t[e+11]=n[11],t[e+12]=n[12],t[e+13]=n[13],t[e+14]=n[14],t[e+15]=n[15],t}},yi=new N,Qe=new ue,Ph=new N(0,0,0),Dh=new N(1,1,1),Dn=new N,Gs=new N,Fe=new N,dl=new ue,fl=new qe,sn=class i{constructor(t=0,e=0,n=0,s=i.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=e,this._z=n,this._order=s}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get order(){return this._order}set order(t){this._order=t,this._onChangeCallback()}set(t,e,n,s=this._order){return this._x=t,this._y=e,this._z=n,this._order=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._order=t._order,this._onChangeCallback(),this}setFromRotationMatrix(t,e=this._order,n=!0){let s=t.elements,r=s[0],a=s[4],o=s[8],l=s[1],c=s[5],h=s[9],d=s[2],f=s[6],m=s[10];switch(e){case"XYZ":this._y=Math.asin(Bt(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-h,m),this._z=Math.atan2(-a,r)):(this._x=Math.atan2(f,c),this._z=0);break;case"YXZ":this._x=Math.asin(-Bt(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(o,m),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-d,r),this._z=0);break;case"ZXY":this._x=Math.asin(Bt(f,-1,1)),Math.abs(f)<.9999999?(this._y=Math.atan2(-d,m),this._z=Math.atan2(-a,c)):(this._y=0,this._z=Math.atan2(l,r));break;case"ZYX":this._y=Math.asin(-Bt(d,-1,1)),Math.abs(d)<.9999999?(this._x=Math.atan2(f,m),this._z=Math.atan2(l,r)):(this._x=0,this._z=Math.atan2(-a,c));break;case"YZX":this._z=Math.asin(Bt(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-h,c),this._y=Math.atan2(-d,r)):(this._x=0,this._y=Math.atan2(o,m));break;case"XZY":this._z=Math.asin(-Bt(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(f,c),this._y=Math.atan2(o,r)):(this._x=Math.atan2(-h,m),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+e)}return this._order=e,n===!0&&this._onChangeCallback(),this}setFromQuaternion(t,e,n){return dl.makeRotationFromQuaternion(t),this.setFromRotationMatrix(dl,e,n)}setFromVector3(t,e=this._order){return this.set(t.x,t.y,t.z,e)}reorder(t){return fl.setFromEuler(this),this.setFromQuaternion(fl,t)}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._order===this._order}fromArray(t){return this._x=t[0],this._y=t[1],this._z=t[2],t[3]!==void 0&&(this._order=t[3]),this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._order,t}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}};sn.DEFAULT_ORDER="XYZ";var hs=class{constructor(){this.mask=1}set(t){this.mask=(1<>>0}enable(t){this.mask|=1<1){for(let e=0;e1){for(let n=0;n0&&(s.userData=this.userData),s.layers=this.layers.mask,s.matrix=this.matrix.toArray(),s.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(s.matrixAutoUpdate=!1),this.isInstancedMesh&&(s.type="InstancedMesh",s.count=this.count,s.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(s.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(s.type="BatchedMesh",s.perObjectFrustumCulled=this.perObjectFrustumCulled,s.sortObjects=this.sortObjects,s.drawRanges=this._drawRanges,s.reservedRanges=this._reservedRanges,s.geometryInfo=this._geometryInfo.map(o=>({...o,boundingBox:o.boundingBox?o.boundingBox.toJSON():void 0,boundingSphere:o.boundingSphere?o.boundingSphere.toJSON():void 0})),s.instanceInfo=this._instanceInfo.map(o=>({...o})),s.availableInstanceIds=this._availableInstanceIds.slice(),s.availableGeometryIds=this._availableGeometryIds.slice(),s.nextIndexStart=this._nextIndexStart,s.nextVertexStart=this._nextVertexStart,s.geometryCount=this._geometryCount,s.maxInstanceCount=this._maxInstanceCount,s.maxVertexCount=this._maxVertexCount,s.maxIndexCount=this._maxIndexCount,s.geometryInitialized=this._geometryInitialized,s.matricesTexture=this._matricesTexture.toJSON(t),s.indirectTexture=this._indirectTexture.toJSON(t),this._colorsTexture!==null&&(s.colorsTexture=this._colorsTexture.toJSON(t)),this.boundingSphere!==null&&(s.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(s.boundingBox=this.boundingBox.toJSON()));function r(o,l){return o[l.uuid]===void 0&&(o[l.uuid]=l.toJSON(t)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?s.background=this.background.toJSON():this.background.isTexture&&(s.background=this.background.toJSON(t).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(s.environment=this.environment.toJSON(t).uuid);else if(this.isMesh||this.isLine||this.isPoints){s.geometry=r(t.geometries,this.geometry);let o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){let l=o.shapes;if(Array.isArray(l))for(let c=0,h=l.length;c0){s.children=[];for(let o=0;o0){s.animations=[];for(let o=0;o0&&(n.geometries=o),l.length>0&&(n.materials=l),c.length>0&&(n.textures=c),h.length>0&&(n.images=h),d.length>0&&(n.shapes=d),f.length>0&&(n.skeletons=f),m.length>0&&(n.animations=m),_.length>0&&(n.nodes=_)}return n.object=s,n;function a(o){let l=[];for(let c in o){let h=o[c];delete h.metadata,l.push(h)}return l}}clone(t){return new this.constructor().copy(this,t)}copy(t,e=!0){if(this.name=t.name,this.up.copy(t.up),this.position.copy(t.position),this.rotation.order=t.rotation.order,this.quaternion.copy(t.quaternion),this.scale.copy(t.scale),this.matrix.copy(t.matrix),this.matrixWorld.copy(t.matrixWorld),this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrixWorldAutoUpdate=t.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=t.matrixWorldNeedsUpdate,this.layers.mask=t.layers.mask,this.visible=t.visible,this.castShadow=t.castShadow,this.receiveShadow=t.receiveShadow,this.frustumCulled=t.frustumCulled,this.renderOrder=t.renderOrder,this.animations=t.animations.slice(),this.userData=JSON.parse(JSON.stringify(t.userData)),e===!0)for(let n=0;n0?s.multiplyScalar(1/Math.sqrt(r)):s.set(0,0,0)}static getBarycoord(t,e,n,s,r){tn.subVectors(s,e),xn.subVectors(n,e),za.subVectors(t,e);let a=tn.dot(tn),o=tn.dot(xn),l=tn.dot(za),c=xn.dot(xn),h=xn.dot(za),d=a*c-o*o;if(d===0)return r.set(0,0,0),null;let f=1/d,m=(c*l-o*h)*f,_=(a*h-o*l)*f;return r.set(1-m-_,_,m)}static containsPoint(t,e,n,s){return this.getBarycoord(t,e,n,s,yn)===null?!1:yn.x>=0&&yn.y>=0&&yn.x+yn.y<=1}static getInterpolation(t,e,n,s,r,a,o,l){return this.getBarycoord(t,e,n,s,yn)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(r,yn.x),l.addScaledVector(a,yn.y),l.addScaledVector(o,yn.z),l)}static getInterpolatedAttribute(t,e,n,s,r,a){return Ga.setScalar(0),Wa.setScalar(0),Xa.setScalar(0),Ga.fromBufferAttribute(t,e),Wa.fromBufferAttribute(t,n),Xa.fromBufferAttribute(t,s),a.setScalar(0),a.addScaledVector(Ga,r.x),a.addScaledVector(Wa,r.y),a.addScaledVector(Xa,r.z),a}static isFrontFacing(t,e,n,s){return tn.subVectors(n,e),xn.subVectors(t,e),tn.cross(xn).dot(s)<0}set(t,e,n){return this.a.copy(t),this.b.copy(e),this.c.copy(n),this}setFromPointsAndIndices(t,e,n,s){return this.a.copy(t[e]),this.b.copy(t[n]),this.c.copy(t[s]),this}setFromAttributeAndIndices(t,e,n,s){return this.a.fromBufferAttribute(t,e),this.b.fromBufferAttribute(t,n),this.c.fromBufferAttribute(t,s),this}clone(){return new this.constructor().copy(this)}copy(t){return this.a.copy(t.a),this.b.copy(t.b),this.c.copy(t.c),this}getArea(){return tn.subVectors(this.c,this.b),xn.subVectors(this.a,this.b),tn.cross(xn).length()*.5}getMidpoint(t){return t.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return i.getNormal(this.a,this.b,this.c,t)}getPlane(t){return t.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,e){return i.getBarycoord(t,this.a,this.b,this.c,e)}getInterpolation(t,e,n,s,r){return i.getInterpolation(t,this.a,this.b,this.c,e,n,s,r)}containsPoint(t){return i.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return i.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(t){return t.intersectsTriangle(this)}closestPointToPoint(t,e){let n=this.a,s=this.b,r=this.c,a,o;Si.subVectors(s,n),bi.subVectors(r,n),ka.subVectors(t,n);let l=Si.dot(ka),c=bi.dot(ka);if(l<=0&&c<=0)return e.copy(n);Va.subVectors(t,s);let h=Si.dot(Va),d=bi.dot(Va);if(h>=0&&d<=h)return e.copy(s);let f=l*d-h*c;if(f<=0&&l>=0&&h<=0)return a=l/(l-h),e.copy(n).addScaledVector(Si,a);Ha.subVectors(t,r);let m=Si.dot(Ha),_=bi.dot(Ha);if(_>=0&&m<=_)return e.copy(r);let M=m*c-l*_;if(M<=0&&c>=0&&_<=0)return o=c/(c-_),e.copy(n).addScaledVector(bi,o);let p=h*_-m*d;if(p<=0&&d-h>=0&&m-_>=0)return yl.subVectors(r,s),o=(d-h)/(d-h+(m-_)),e.copy(s).addScaledVector(yl,o);let u=1/(p+M+f);return a=M*u,o=f*u,e.copy(n).addScaledVector(Si,a).addScaledVector(bi,o)}equals(t){return t.a.equals(this.a)&&t.b.equals(this.b)&&t.c.equals(this.c)}},pc={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Ln={h:0,s:0,l:0},Xs={h:0,s:0,l:0};function qa(i,t,e){return e<0&&(e+=1),e>1&&(e-=1),e<1/6?i+(t-i)*6*e:e<1/2?t:e<2/3?i+(t-i)*6*(2/3-e):i}var zt=class{constructor(t,e,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(t,e,n)}set(t,e,n){if(e===void 0&&n===void 0){let s=t;s&&s.isColor?this.copy(s):typeof s=="number"?this.setHex(s):typeof s=="string"&&this.setStyle(s)}else this.setRGB(t,e,n);return this}setScalar(t){return this.r=t,this.g=t,this.b=t,this}setHex(t,e=Ce){return t=Math.floor(t),this.r=(t>>16&255)/255,this.g=(t>>8&255)/255,this.b=(t&255)/255,Gt.colorSpaceToWorking(this,e),this}setRGB(t,e,n,s=Gt.workingColorSpace){return this.r=t,this.g=e,this.b=n,Gt.colorSpaceToWorking(this,s),this}setHSL(t,e,n,s=Gt.workingColorSpace){if(t=Eo(t,1),e=Bt(e,0,1),n=Bt(n,0,1),e===0)this.r=this.g=this.b=n;else{let r=n<=.5?n*(1+e):n+e-n*e,a=2*n-r;this.r=qa(a,r,t+1/3),this.g=qa(a,r,t),this.b=qa(a,r,t-1/3)}return Gt.colorSpaceToWorking(this,s),this}setStyle(t,e=Ce){function n(r){r!==void 0&&parseFloat(r)<1&&console.warn("THREE.Color: Alpha component of "+t+" will be ignored.")}let s;if(s=/^(\w+)\(([^\)]*)\)/.exec(t)){let r,a=s[1],o=s[2];switch(a){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,e);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,e);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,e);break;default:console.warn("THREE.Color: Unknown color model "+t)}}else if(s=/^\#([A-Fa-f\d]+)$/.exec(t)){let r=s[1],a=r.length;if(a===3)return this.setRGB(parseInt(r.charAt(0),16)/15,parseInt(r.charAt(1),16)/15,parseInt(r.charAt(2),16)/15,e);if(a===6)return this.setHex(parseInt(r,16),e);console.warn("THREE.Color: Invalid hex color "+t)}else if(t&&t.length>0)return this.setColorName(t,e);return this}setColorName(t,e=Ce){let n=pc[t.toLowerCase()];return n!==void 0?this.setHex(n,e):console.warn("THREE.Color: Unknown color "+t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(t){return this.r=t.r,this.g=t.g,this.b=t.b,this}copySRGBToLinear(t){return this.r=Mn(t.r),this.g=Mn(t.g),this.b=Mn(t.b),this}copyLinearToSRGB(t){return this.r=Ci(t.r),this.g=Ci(t.g),this.b=Ci(t.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(t=Ce){return Gt.workingToColorSpace(Me.copy(this),t),Math.round(Bt(Me.r*255,0,255))*65536+Math.round(Bt(Me.g*255,0,255))*256+Math.round(Bt(Me.b*255,0,255))}getHexString(t=Ce){return("000000"+this.getHex(t).toString(16)).slice(-6)}getHSL(t,e=Gt.workingColorSpace){Gt.workingToColorSpace(Me.copy(this),e);let n=Me.r,s=Me.g,r=Me.b,a=Math.max(n,s,r),o=Math.min(n,s,r),l,c,h=(o+a)/2;if(o===a)l=0,c=0;else{let d=a-o;switch(c=h<=.5?d/(a+o):d/(2-a-o),a){case n:l=(s-r)/d+(s0!=t>0&&this.version++,this._alphaTest=t}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(t){if(t!==void 0)for(let e in t){let n=t[e];if(n===void 0){console.warn(`THREE.Material: parameter '${e}' has value of undefined.`);continue}let s=this[e];if(s===void 0){console.warn(`THREE.Material: '${e}' is not a property of THREE.${this.type}.`);continue}s&&s.isColor?s.set(n):s&&s.isVector3&&n&&n.isVector3?s.copy(n):this[e]=n}}toJSON(t){let e=t===void 0||typeof t=="string";e&&(t={textures:{},images:{}});let n={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(t).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(t).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(t).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(t).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(t).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(t).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(t).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(t).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(t).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(t).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(t).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(t).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(t).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(t).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(t).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(t).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(t).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(t).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(t).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(t).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(t).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(t).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(t).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(t).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(t).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(t).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==ei&&(n.blending=this.blending),this.side!==Sn&&(n.side=this.side),this.vertexColors===!0&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=!0),this.blendSrc!==ir&&(n.blendSrc=this.blendSrc),this.blendDst!==sr&&(n.blendDst=this.blendDst),this.blendEquation!==On&&(n.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(n.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(n.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(n.blendAlpha=this.blendAlpha),this.depthFunc!==ni&&(n.depthFunc=this.depthFunc),this.depthTest===!1&&(n.depthTest=this.depthTest),this.depthWrite===!1&&(n.depthWrite=this.depthWrite),this.colorWrite===!1&&(n.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==to&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==ti&&(n.stencilFail=this.stencilFail),this.stencilZFail!==ti&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==ti&&(n.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=!0),this.alphaToCoverage===!0&&(n.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=!0),this.forceSinglePass===!0&&(n.forceSinglePass=!0),this.wireframe===!0&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=!0),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData);function s(r){let a=[];for(let o in r){let l=r[o];delete l.metadata,a.push(l)}return a}if(e){let r=s(t.textures),a=s(t.images);r.length>0&&(n.textures=r),a.length>0&&(n.images=a)}return n}clone(){return new this.constructor().copy(this)}copy(t){this.name=t.name,this.blending=t.blending,this.side=t.side,this.vertexColors=t.vertexColors,this.opacity=t.opacity,this.transparent=t.transparent,this.blendSrc=t.blendSrc,this.blendDst=t.blendDst,this.blendEquation=t.blendEquation,this.blendSrcAlpha=t.blendSrcAlpha,this.blendDstAlpha=t.blendDstAlpha,this.blendEquationAlpha=t.blendEquationAlpha,this.blendColor.copy(t.blendColor),this.blendAlpha=t.blendAlpha,this.depthFunc=t.depthFunc,this.depthTest=t.depthTest,this.depthWrite=t.depthWrite,this.stencilWriteMask=t.stencilWriteMask,this.stencilFunc=t.stencilFunc,this.stencilRef=t.stencilRef,this.stencilFuncMask=t.stencilFuncMask,this.stencilFail=t.stencilFail,this.stencilZFail=t.stencilZFail,this.stencilZPass=t.stencilZPass,this.stencilWrite=t.stencilWrite;let e=t.clippingPlanes,n=null;if(e!==null){let s=e.length;n=new Array(s);for(let r=0;r!==s;++r)n[r]=e[r].clone()}return this.clippingPlanes=n,this.clipIntersection=t.clipIntersection,this.clipShadows=t.clipShadows,this.shadowSide=t.shadowSide,this.colorWrite=t.colorWrite,this.precision=t.precision,this.polygonOffset=t.polygonOffset,this.polygonOffsetFactor=t.polygonOffsetFactor,this.polygonOffsetUnits=t.polygonOffsetUnits,this.dithering=t.dithering,this.alphaTest=t.alphaTest,this.alphaHash=t.alphaHash,this.alphaToCoverage=t.alphaToCoverage,this.premultipliedAlpha=t.premultipliedAlpha,this.forceSinglePass=t.forceSinglePass,this.visible=t.visible,this.toneMapped=t.toneMapped,this.userData=JSON.parse(JSON.stringify(t.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(t){t===!0&&this.version++}},us=class extends zn{constructor(t){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new zt(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new sn,this.combine=ho,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.fog=t.fog,this}};var de=new N,qs=new Pt,Bh=0,be=class{constructor(t,e,n=!1){if(Array.isArray(t))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:Bh++}),this.name="",this.array=t,this.itemSize=e,this.count=t!==void 0?t.length/e:0,this.normalized=n,this.usage=eo,this.updateRanges=[],this.gpuType=un,this.version=0}onUploadCallback(){}set needsUpdate(t){t===!0&&this.version++}setUsage(t){return this.usage=t,this}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}copy(t){return this.name=t.name,this.array=new t.array.constructor(t.array),this.itemSize=t.itemSize,this.count=t.count,this.normalized=t.normalized,this.usage=t.usage,this.gpuType=t.gpuType,this}copyAt(t,e,n){t*=this.itemSize,n*=e.itemSize;for(let s=0,r=this.itemSize;se.count&&console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),e.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Bn);let t=this.attributes.position,e=this.morphAttributes.position;if(t&&t.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new N(-1/0,-1/0,-1/0),new N(1/0,1/0,1/0));return}if(t!==void 0){if(this.boundingBox.setFromBufferAttribute(t),e)for(let n=0,s=e.length;n0&&(t.userData=this.userData),this.parameters!==void 0){let l=this.parameters;for(let c in l)l[c]!==void 0&&(t[c]=l[c]);return t}t.data={attributes:{}};let e=this.index;e!==null&&(t.data.index={type:e.array.constructor.name,array:Array.prototype.slice.call(e.array)});let n=this.attributes;for(let l in n){let c=n[l];t.data.attributes[l]=c.toJSON(t.data)}let s={},r=!1;for(let l in this.morphAttributes){let c=this.morphAttributes[l],h=[];for(let d=0,f=c.length;d0&&(s[l]=h,r=!0)}r&&(t.data.morphAttributes=s,t.data.morphTargetsRelative=this.morphTargetsRelative);let a=this.groups;a.length>0&&(t.data.groups=JSON.parse(JSON.stringify(a)));let o=this.boundingSphere;return o!==null&&(t.data.boundingSphere=o.toJSON()),t}clone(){return new this.constructor().copy(this)}copy(t){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let e={};this.name=t.name;let n=t.index;n!==null&&this.setIndex(n.clone());let s=t.attributes;for(let c in s){let h=s[c];this.setAttribute(c,h.clone(e))}let r=t.morphAttributes;for(let c in r){let h=[],d=r[c];for(let f=0,m=d.length;f0){let s=e[n[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,a=s.length;r(t.far-t.near)**2))&&(vl.copy(r).invert(),jn.copy(t.ray).applyMatrix4(vl),!(n.boundingBox!==null&&jn.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(t,e,jn)))}_computeIntersections(t,e,n){let s,r=this.geometry,a=this.material,o=r.index,l=r.attributes.position,c=r.attributes.uv,h=r.attributes.uv1,d=r.attributes.normal,f=r.groups,m=r.drawRange;if(o!==null)if(Array.isArray(a))for(let _=0,M=f.length;_e.far?null:{distance:c,point:js.clone(),object:i}}function Qs(i,t,e,n,s,r,a,o,l,c){i.getVertexPosition(o,Zs),i.getVertexPosition(l,Js),i.getVertexPosition(c,$s);let h=kh(i,t,e,n,Zs,Js,$s,Sl);if(h){let d=new N;Nn.getBarycoord(Sl,Zs,Js,$s,d),s&&(h.uv=Nn.getInterpolatedAttribute(s,o,l,c,d,new Pt)),r&&(h.uv1=Nn.getInterpolatedAttribute(r,o,l,c,d,new Pt)),a&&(h.normal=Nn.getInterpolatedAttribute(a,o,l,c,d,new N),h.normal.dot(n.direction)>0&&h.normal.multiplyScalar(-1));let f={a:o,b:l,c,normal:new N,materialIndex:0};Nn.getNormal(Zs,Js,$s,f.normal),h.face=f,h.barycoord=d}return h}var kn=class i extends ze{constructor(t=1,e=1,n=1,s=1,r=1,a=1){super(),this.type="BoxGeometry",this.parameters={width:t,height:e,depth:n,widthSegments:s,heightSegments:r,depthSegments:a};let o=this;s=Math.floor(s),r=Math.floor(r),a=Math.floor(a);let l=[],c=[],h=[],d=[],f=0,m=0;_("z","y","x",-1,-1,n,e,t,a,r,0),_("z","y","x",1,-1,n,e,-t,a,r,1),_("x","z","y",1,1,t,n,e,s,a,2),_("x","z","y",1,-1,t,n,-e,s,a,3),_("x","y","z",1,-1,t,e,n,s,r,4),_("x","y","z",-1,-1,t,e,-n,s,r,5),this.setIndex(l),this.setAttribute("position",new fe(c,3)),this.setAttribute("normal",new fe(h,3)),this.setAttribute("uv",new fe(d,2));function _(M,p,u,T,E,S,C,A,P,U,v){let y=S/P,R=C/U,F=S/2,k=C/2,H=A/2,q=P+1,W=U+1,et=0,V=0,rt=new N;for(let ct=0;ct0?1:-1,h.push(rt.x,rt.y,rt.z),d.push(kt/P),d.push(1-ct/U),et+=1}}for(let ct=0;ct0&&(e.defines=this.defines),e.vertexShader=this.vertexShader,e.fragmentShader=this.fragmentShader,e.lights=this.lights,e.clipping=this.clipping;let n={};for(let s in this.extensions)this.extensions[s]===!0&&(n[s]=!0);return Object.keys(n).length>0&&(e.extensions=n),e}},ps=class extends Ee{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new ue,this.projectionMatrix=new ue,this.projectionMatrixInverse=new ue,this.coordinateSystem=en,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(t,e){return super.copy(t,e),this.matrixWorldInverse.copy(t.matrixWorldInverse),this.projectionMatrix.copy(t.projectionMatrix),this.projectionMatrixInverse.copy(t.projectionMatrixInverse),this.coordinateSystem=t.coordinateSystem,this}getWorldDirection(t){return super.getWorldDirection(t).negate()}updateMatrixWorld(t){super.updateMatrixWorld(t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(t,e){super.updateWorldMatrix(t,e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}},Un=new N,bl=new Pt,El=new Pt,Se=class extends ps{constructor(t=50,e=1,n=.1,s=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=t,this.zoom=1,this.near=n,this.far=s,this.focus=10,this.aspect=e,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(t,e){return super.copy(t,e),this.fov=t.fov,this.zoom=t.zoom,this.near=t.near,this.far=t.far,this.focus=t.focus,this.aspect=t.aspect,this.view=t.view===null?null:Object.assign({},t.view),this.filmGauge=t.filmGauge,this.filmOffset=t.filmOffset,this}setFocalLength(t){let e=.5*this.getFilmHeight()/t;this.fov=Ii*2*Math.atan(e),this.updateProjectionMatrix()}getFocalLength(){let t=Math.tan(is*.5*this.fov);return .5*this.getFilmHeight()/t}getEffectiveFOV(){return Ii*2*Math.atan(Math.tan(is*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(t,e,n){Un.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),e.set(Un.x,Un.y).multiplyScalar(-t/Un.z),Un.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(Un.x,Un.y).multiplyScalar(-t/Un.z)}getViewSize(t,e){return this.getViewBounds(t,bl,El),e.subVectors(El,bl)}setViewOffset(t,e,n,s,r,a){this.aspect=t/e,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=t,this.view.fullHeight=e,this.view.offsetX=n,this.view.offsetY=s,this.view.width=r,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let t=this.near,e=t*Math.tan(is*.5*this.fov)/this.zoom,n=2*e,s=this.aspect*n,r=-.5*s,a=this.view;if(this.view!==null&&this.view.enabled){let l=a.fullWidth,c=a.fullHeight;r+=a.offsetX*s/l,e-=a.offsetY*n/c,s*=a.width/l,n*=a.height/c}let o=this.filmOffset;o!==0&&(r+=t*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+s,e,e-n,t,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(t){let e=super.toJSON(t);return e.object.fov=this.fov,e.object.zoom=this.zoom,e.object.near=this.near,e.object.far=this.far,e.object.focus=this.focus,e.object.aspect=this.aspect,this.view!==null&&(e.object.view=Object.assign({},this.view)),e.object.filmGauge=this.filmGauge,e.object.filmOffset=this.filmOffset,e}},Ti=-90,wi=1,ur=class extends Ee{constructor(t,e,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;let s=new Se(Ti,wi,t,e);s.layers=this.layers,this.add(s);let r=new Se(Ti,wi,t,e);r.layers=this.layers,this.add(r);let a=new Se(Ti,wi,t,e);a.layers=this.layers,this.add(a);let o=new Se(Ti,wi,t,e);o.layers=this.layers,this.add(o);let l=new Se(Ti,wi,t,e);l.layers=this.layers,this.add(l);let c=new Se(Ti,wi,t,e);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){let t=this.coordinateSystem,e=this.children.concat(),[n,s,r,a,o,l]=e;for(let c of e)this.remove(c);if(t===en)n.up.set(0,1,0),n.lookAt(1,0,0),s.up.set(0,1,0),s.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),l.up.set(0,1,0),l.lookAt(0,0,-1);else if(t===os)n.up.set(0,-1,0),n.lookAt(-1,0,0),s.up.set(0,-1,0),s.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),l.up.set(0,-1,0),l.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+t);for(let c of e)this.add(c),c.updateMatrixWorld()}update(t,e){this.parent===null&&this.updateMatrixWorld();let{renderTarget:n,activeMipmapLevel:s}=this;this.coordinateSystem!==t.coordinateSystem&&(this.coordinateSystem=t.coordinateSystem,this.updateCoordinateSystem());let[r,a,o,l,c,h]=this.children,d=t.getRenderTarget(),f=t.getActiveCubeFace(),m=t.getActiveMipmapLevel(),_=t.xr.enabled;t.xr.enabled=!1;let M=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,t.setRenderTarget(n,0,s),t.render(e,r),t.setRenderTarget(n,1,s),t.render(e,a),t.setRenderTarget(n,2,s),t.render(e,o),t.setRenderTarget(n,3,s),t.render(e,l),t.setRenderTarget(n,4,s),t.render(e,c),n.texture.generateMipmaps=M,t.setRenderTarget(n,5,s),t.render(e,h),t.setRenderTarget(d,f,m),t.xr.enabled=_,n.texture.needsPMREMUpdate=!0}},ms=class extends Be{constructor(t=[],e=ri,n,s,r,a,o,l,c,h){super(t,e,n,s,r,a,o,l,c,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(t){this.image=t}},dr=class extends cn{constructor(t=1,e={}){super(t,t,e),this.isWebGLCubeRenderTarget=!0;let n={width:t,height:t,depth:1},s=[n,n,n,n,n,n];this.texture=new ms(s),this._setTextureOptions(e),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(t,e){this.texture.type=e.type,this.texture.colorSpace=e.colorSpace,this.texture.generateMipmaps=e.generateMipmaps,this.texture.minFilter=e.minFilter,this.texture.magFilter=e.magFilter;let n={uniforms:{tEquirect:{value:null}},vertexShader:` + + varying vec3 vWorldDirection; + + vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); + + } + + void main() { + + vWorldDirection = transformDirection( position, modelMatrix ); + + #include + #include + + } + `,fragmentShader:` + + uniform sampler2D tEquirect; + + varying vec3 vWorldDirection; + + #include + + void main() { + + vec3 direction = normalize( vWorldDirection ); + + vec2 sampleUV = equirectUv( direction ); + + gl_FragColor = texture2D( tEquirect, sampleUV ); + + } + `},s=new kn(5,5,5),r=new rn({name:"CubemapFromEquirect",uniforms:oi(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:Re,blending:En});r.uniforms.tEquirect.value=e;let a=new Pe(s,r),o=e.minFilter;return e.minFilter===Xn&&(e.minFilter=nn),new ur(1,10,this).update(t,a),e.minFilter=o,a.geometry.dispose(),a.material.dispose(),this}clear(t,e=!0,n=!0,s=!0){let r=t.getRenderTarget();for(let a=0;a<6;a++)t.setRenderTarget(this,a),t.clear(e,n,s);t.setRenderTarget(r)}},vn=class extends Ee{constructor(){super(),this.isGroup=!0,this.type="Group"}},Wh={type:"move"},Ni=class{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new vn,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new vn,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new N,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new N),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new vn,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new N,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new N),this._grip}dispatchEvent(t){return this._targetRay!==null&&this._targetRay.dispatchEvent(t),this._grip!==null&&this._grip.dispatchEvent(t),this._hand!==null&&this._hand.dispatchEvent(t),this}connect(t){if(t&&t.hand){let e=this._hand;if(e)for(let n of t.hand.values())this._getHandJoint(e,n)}return this.dispatchEvent({type:"connected",data:t}),this}disconnect(t){return this.dispatchEvent({type:"disconnected",data:t}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(t,e,n){let s=null,r=null,a=null,o=this._targetRay,l=this._grip,c=this._hand;if(t&&e.session.visibilityState!=="visible-blurred"){if(c&&t.hand){a=!0;for(let M of t.hand.values()){let p=e.getJointPose(M,n),u=this._getHandJoint(c,M);p!==null&&(u.matrix.fromArray(p.transform.matrix),u.matrix.decompose(u.position,u.rotation,u.scale),u.matrixWorldNeedsUpdate=!0,u.jointRadius=p.radius),u.visible=p!==null}let h=c.joints["index-finger-tip"],d=c.joints["thumb-tip"],f=h.position.distanceTo(d.position),m=.02,_=.005;c.inputState.pinching&&f>m+_?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:t.handedness,target:this})):!c.inputState.pinching&&f<=m-_&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:t.handedness,target:this}))}else l!==null&&t.gripSpace&&(r=e.getPose(t.gripSpace,n),r!==null&&(l.matrix.fromArray(r.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,r.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(r.linearVelocity)):l.hasLinearVelocity=!1,r.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(r.angularVelocity)):l.hasAngularVelocity=!1));o!==null&&(s=e.getPose(t.targetRaySpace,n),s===null&&r!==null&&(s=r),s!==null&&(o.matrix.fromArray(s.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,s.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(s.linearVelocity)):o.hasLinearVelocity=!1,s.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(s.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(Wh)))}return o!==null&&(o.visible=s!==null),l!==null&&(l.visible=r!==null),c!==null&&(c.visible=a!==null),this}_getHandJoint(t,e){if(t.joints[e.jointName]===void 0){let n=new vn;n.matrixAutoUpdate=!1,n.visible=!1,t.joints[e.jointName]=n,t.add(n)}return t.joints[e.jointName]}};var gs=class extends Ee{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new sn,this.environmentIntensity=1,this.environmentRotation=new sn,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(t,e){return super.copy(t,e),t.background!==null&&(this.background=t.background.clone()),t.environment!==null&&(this.environment=t.environment.clone()),t.fog!==null&&(this.fog=t.fog.clone()),this.backgroundBlurriness=t.backgroundBlurriness,this.backgroundIntensity=t.backgroundIntensity,this.backgroundRotation.copy(t.backgroundRotation),this.environmentIntensity=t.environmentIntensity,this.environmentRotation.copy(t.environmentRotation),t.overrideMaterial!==null&&(this.overrideMaterial=t.overrideMaterial.clone()),this.matrixAutoUpdate=t.matrixAutoUpdate,this}toJSON(t){let e=super.toJSON(t);return this.fog!==null&&(e.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(e.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(e.object.backgroundIntensity=this.backgroundIntensity),e.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(e.object.environmentIntensity=this.environmentIntensity),e.object.environmentRotation=this.environmentRotation.toArray(),e}};var Ja=new N,Xh=new N,qh=new Ut,We=class{constructor(t=new N(1,0,0),e=0){this.isPlane=!0,this.normal=t,this.constant=e}set(t,e){return this.normal.copy(t),this.constant=e,this}setComponents(t,e,n,s){return this.normal.set(t,e,n),this.constant=s,this}setFromNormalAndCoplanarPoint(t,e){return this.normal.copy(t),this.constant=-e.dot(this.normal),this}setFromCoplanarPoints(t,e,n){let s=Ja.subVectors(n,e).cross(Xh.subVectors(t,e)).normalize();return this.setFromNormalAndCoplanarPoint(s,t),this}copy(t){return this.normal.copy(t.normal),this.constant=t.constant,this}normalize(){let t=1/this.normal.length();return this.normal.multiplyScalar(t),this.constant*=t,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(t){return this.normal.dot(t)+this.constant}distanceToSphere(t){return this.distanceToPoint(t.center)-t.radius}projectPoint(t,e){return e.copy(t).addScaledVector(this.normal,-this.distanceToPoint(t))}intersectLine(t,e){let n=t.delta(Ja),s=this.normal.dot(n);if(s===0)return this.distanceToPoint(t.start)===0?e.copy(t.start):null;let r=-(t.start.dot(this.normal)+this.constant)/s;return r<0||r>1?null:e.copy(t.start).addScaledVector(n,r)}intersectsLine(t){let e=this.distanceToPoint(t.start),n=this.distanceToPoint(t.end);return e<0&&n>0||n<0&&e>0}intersectsBox(t){return t.intersectsPlane(this)}intersectsSphere(t){return t.intersectsPlane(this)}coplanarPoint(t){return t.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(t,e){let n=e||qh.getNormalMatrix(t),s=this.coplanarPoint(Ja).applyMatrix4(t),r=this.normal.applyMatrix3(n).normalize();return this.constant=-s.dot(r),this}translate(t){return this.constant-=t.dot(this.normal),this}equals(t){return t.normal.equals(this.normal)&&t.constant===this.constant}clone(){return new this.constructor().copy(this)}},Qn=new Li,Yh=new Pt(.5,.5),tr=new N,Fi=class{constructor(t=new We,e=new We,n=new We,s=new We,r=new We,a=new We){this.planes=[t,e,n,s,r,a]}set(t,e,n,s,r,a){let o=this.planes;return o[0].copy(t),o[1].copy(e),o[2].copy(n),o[3].copy(s),o[4].copy(r),o[5].copy(a),this}copy(t){let e=this.planes;for(let n=0;n<6;n++)e[n].copy(t.planes[n]);return this}setFromProjectionMatrix(t,e=en,n=!1){let s=this.planes,r=t.elements,a=r[0],o=r[1],l=r[2],c=r[3],h=r[4],d=r[5],f=r[6],m=r[7],_=r[8],M=r[9],p=r[10],u=r[11],T=r[12],E=r[13],S=r[14],C=r[15];if(s[0].setComponents(c-a,m-h,u-_,C-T).normalize(),s[1].setComponents(c+a,m+h,u+_,C+T).normalize(),s[2].setComponents(c+o,m+d,u+M,C+E).normalize(),s[3].setComponents(c-o,m-d,u-M,C-E).normalize(),n)s[4].setComponents(l,f,p,S).normalize(),s[5].setComponents(c-l,m-f,u-p,C-S).normalize();else if(s[4].setComponents(c-l,m-f,u-p,C-S).normalize(),e===en)s[5].setComponents(c+l,m+f,u+p,C+S).normalize();else if(e===os)s[5].setComponents(l,f,p,S).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+e);return this}intersectsObject(t){if(t.boundingSphere!==void 0)t.boundingSphere===null&&t.computeBoundingSphere(),Qn.copy(t.boundingSphere).applyMatrix4(t.matrixWorld);else{let e=t.geometry;e.boundingSphere===null&&e.computeBoundingSphere(),Qn.copy(e.boundingSphere).applyMatrix4(t.matrixWorld)}return this.intersectsSphere(Qn)}intersectsSprite(t){Qn.center.set(0,0,0);let e=Yh.distanceTo(t.center);return Qn.radius=.7071067811865476+e,Qn.applyMatrix4(t.matrixWorld),this.intersectsSphere(Qn)}intersectsSphere(t){let e=this.planes,n=t.center,s=-t.radius;for(let r=0;r<6;r++)if(e[r].distanceToPoint(n)0?t.max.x:t.min.x,tr.y=s.normal.y>0?t.max.y:t.min.y,tr.z=s.normal.z>0?t.max.z:t.min.z,s.distanceToPoint(tr)<0)return!1}return!0}containsPoint(t){let e=this.planes;for(let n=0;n<6;n++)if(e[n].distanceToPoint(t)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}};var _s=class extends Be{constructor(t,e,n=qn,s,r,a,o=Xe,l=Xe,c,h=Ri,d=1){if(h!==Ri&&h!==Wi)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");let f={width:t,height:e,depth:d};super(f,s,r,a,o,l,h,n,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(t){return super.copy(t),this.source=new Di(Object.assign({},t.image)),this.compareFunction=t.compareFunction,this}toJSON(t){let e=super.toJSON(t);return this.compareFunction!==null&&(e.compareFunction=this.compareFunction),e}},xs=class extends Be{constructor(t=null){super(),this.sourceTexture=t,this.isExternalTexture=!0}copy(t){return super.copy(t),this.sourceTexture=t.sourceTexture,this}},ys=class i extends ze{constructor(t=1,e=1,n=4,s=8,r=1){super(),this.type="CapsuleGeometry",this.parameters={radius:t,height:e,capSegments:n,radialSegments:s,heightSegments:r},e=Math.max(0,e),n=Math.max(1,Math.floor(n)),s=Math.max(3,Math.floor(s)),r=Math.max(1,Math.floor(r));let a=[],o=[],l=[],c=[],h=e/2,d=Math.PI/2*t,f=e,m=2*d+f,_=n*2+r,M=s+1,p=new N,u=new N;for(let T=0;T<=_;T++){let E=0,S=0,C=0,A=0;if(T<=n){let v=T/n,y=v*Math.PI/2;S=-h-t*Math.cos(y),C=t*Math.sin(y),A=-t*Math.cos(y),E=v*d}else if(T<=n+r){let v=(T-n)/r;S=-h+v*e,C=t,A=0,E=d+v*f}else{let v=(T-n-r)/n,y=v*Math.PI/2;S=h+t*Math.sin(y),C=t*Math.cos(y),A=t*Math.sin(y),E=d+f+v*d}let P=Math.max(0,Math.min(1,E/m)),U=0;T===0?U=.5/s:T===_&&(U=-.5/s);for(let v=0;v<=s;v++){let y=v/s,R=y*Math.PI*2,F=Math.sin(R),k=Math.cos(R);u.x=-C*k,u.y=S,u.z=C*F,o.push(u.x,u.y,u.z),p.set(-C*k,A,C*F),p.normalize(),l.push(p.x,p.y,p.z),c.push(y+U,P)}if(T>0){let v=(T-1)*M;for(let y=0;y0&&E(!0),e>0&&E(!1)),this.setIndex(h),this.setAttribute("position",new fe(d,3)),this.setAttribute("normal",new fe(f,3)),this.setAttribute("uv",new fe(m,2));function T(){let S=new N,C=new N,A=0,P=(e-t)/n;for(let U=0;U<=r;U++){let v=[],y=U/r,R=y*(e-t)+t;for(let F=0;F<=s;F++){let k=F/s,H=k*l+o,q=Math.sin(H),W=Math.cos(H);C.x=R*q,C.y=-y*n+p,C.z=R*W,d.push(C.x,C.y,C.z),S.set(q,P,W).normalize(),f.push(S.x,S.y,S.z),m.push(k,1-y),v.push(_++)}M.push(v)}for(let U=0;U0||v!==0)&&(h.push(y,R,k),A+=3),(e>0||v!==r-1)&&(h.push(R,F,k),A+=3)}c.addGroup(u,A,0),u+=A}function E(S){let C=_,A=new Pt,P=new N,U=0,v=S===!0?t:e,y=S===!0?1:-1;for(let F=1;F<=s;F++)d.push(0,p*y,0),f.push(0,y,0),m.push(.5,.5),_++;let R=_;for(let F=0;F<=s;F++){let H=F/s*l+o,q=Math.cos(H),W=Math.sin(H);P.x=v*W,P.y=p*y,P.z=v*q,d.push(P.x,P.y,P.z),f.push(0,y,0),A.x=q*.5+.5,A.y=W*.5*y+.5,m.push(A.x,A.y),_++}for(let F=0;F0)&&m.push(E,S,A),(u!==n-1||l=r)){let o=e[1];t=r)break t}a=n,n=0;break e}break n}for(;n>>1;te;)--a;if(++a,r!==0||a!==s){r>=a&&(a=Math.max(a,1),r=a-1);let o=this.getValueSize();this.times=n.slice(r,a),this.values=this.values.slice(r*o,a*o)}return this}validate(){let t=!0,e=this.getValueSize();e-Math.floor(e)!==0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),t=!1);let n=this.times,s=this.values,r=n.length;r===0&&(console.error("THREE.KeyframeTrack: Track is empty.",this),t=!1);let a=null;for(let o=0;o!==r;o++){let l=n[o];if(typeof l=="number"&&isNaN(l)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,o,l),t=!1;break}if(a!==null&&a>l){console.error("THREE.KeyframeTrack: Out of order keys.",this,o,l,a),t=!1;break}a=l}if(s!==void 0&&Zh(s))for(let o=0,l=s.length;o!==l;++o){let c=s[o];if(isNaN(c)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,o,c),t=!1;break}}return t}optimize(){let t=this.times.slice(),e=this.values.slice(),n=this.getValueSize(),s=this.getInterpolation()===nr,r=t.length-1,a=1;for(let o=1;o0){t[a]=t[r];for(let o=r*n,l=a*n,c=0;c!==n;++c)e[l+c]=e[o+c];++a}return a!==t.length?(this.times=t.slice(0,a),this.values=e.slice(0,a*n)):(this.times=t,this.values=e),this}clone(){let t=this.times.slice(),e=this.values.slice(),n=this.constructor,s=new n(this.name,t,e);return s.createInterpolant=this.createInterpolant,s}};ke.prototype.ValueTypeName="";ke.prototype.TimeBufferType=Float32Array;ke.prototype.ValueBufferType=Float32Array;ke.prototype.DefaultInterpolation=or;var Vn=class extends ke{constructor(t,e,n){super(t,e,n)}};Vn.prototype.ValueTypeName="bool";Vn.prototype.ValueBufferType=Array;Vn.prototype.DefaultInterpolation=rs;Vn.prototype.InterpolantFactoryMethodLinear=void 0;Vn.prototype.InterpolantFactoryMethodSmooth=void 0;var xr=class extends ke{constructor(t,e,n,s){super(t,e,n,s)}};xr.prototype.ValueTypeName="color";var yr=class extends ke{constructor(t,e,n,s){super(t,e,n,s)}};yr.prototype.ValueTypeName="number";var vr=class extends si{constructor(t,e,n,s){super(t,e,n,s)}interpolate_(t,e,n,s){let r=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=(n-e)/(s-e),c=t*o;for(let h=c+o;c!==h;c+=4)qe.slerpFlat(r,0,a,c-o,a,c,l);return r}},Ms=class extends ke{constructor(t,e,n,s){super(t,e,n,s)}InterpolantFactoryMethodLinear(t){return new vr(this.times,this.values,this.getValueSize(),t)}};Ms.prototype.ValueTypeName="quaternion";Ms.prototype.InterpolantFactoryMethodSmooth=void 0;var Hn=class extends ke{constructor(t,e,n){super(t,e,n)}};Hn.prototype.ValueTypeName="string";Hn.prototype.ValueBufferType=Array;Hn.prototype.DefaultInterpolation=rs;Hn.prototype.InterpolantFactoryMethodLinear=void 0;Hn.prototype.InterpolantFactoryMethodSmooth=void 0;var Mr=class extends ke{constructor(t,e,n,s){super(t,e,n,s)}};Mr.prototype.ValueTypeName="vector";var Sr=class{constructor(t,e,n){let s=this,r=!1,a=0,o=0,l,c=[];this.onStart=void 0,this.onLoad=t,this.onProgress=e,this.onError=n,this.abortController=new AbortController,this.itemStart=function(h){o++,r===!1&&s.onStart!==void 0&&s.onStart(h,a,o),r=!0},this.itemEnd=function(h){a++,s.onProgress!==void 0&&s.onProgress(h,a,o),a===o&&(r=!1,s.onLoad!==void 0&&s.onLoad())},this.itemError=function(h){s.onError!==void 0&&s.onError(h)},this.resolveURL=function(h){return l?l(h):h},this.setURLModifier=function(h){return l=h,this},this.addHandler=function(h,d){return c.push(h,d),this},this.removeHandler=function(h){let d=c.indexOf(h);return d!==-1&&c.splice(d,2),this},this.getHandler=function(h){for(let d=0,f=c.length;dm.start-_.start);let f=0;for(let m=1;m 0 + vec4 plane; + #ifdef ALPHA_TO_COVERAGE + float distanceToPlane, distanceGradient; + float clipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + if ( clipOpacity == 0.0 ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + float unionClipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + } + #pragma unroll_loop_end + clipOpacity *= 1.0 - unionClipOpacity; + #endif + diffuseColor.a *= clipOpacity; + if ( diffuseColor.a == 0.0 ) discard; + #else + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + bool clipped = true; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; + } + #pragma unroll_loop_end + if ( clipped ) discard; + #endif + #endif +#endif`,Su=`#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; + uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; +#endif`,bu=`#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; +#endif`,Eu=`#if NUM_CLIPPING_PLANES > 0 + vClipPosition = - mvPosition.xyz; +#endif`,Tu=`#if defined( USE_COLOR_ALPHA ) + diffuseColor *= vColor; +#elif defined( USE_COLOR ) + diffuseColor.rgb *= vColor; +#endif`,wu=`#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) + varying vec3 vColor; +#endif`,Au=`#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + varying vec3 vColor; +#endif`,Cu=`#if defined( USE_COLOR_ALPHA ) + vColor = vec4( 1.0 ); +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + vColor = vec3( 1.0 ); +#endif +#ifdef USE_COLOR + vColor *= color; +#endif +#ifdef USE_INSTANCING_COLOR + vColor.xyz *= instanceColor.xyz; +#endif +#ifdef USE_BATCHING_COLOR + vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) ); + vColor.xyz *= batchingColor.xyz; +#endif`,Ru=`#define PI 3.141592653589793 +#define PI2 6.283185307179586 +#define PI_HALF 1.5707963267948966 +#define RECIPROCAL_PI 0.3183098861837907 +#define RECIPROCAL_PI2 0.15915494309189535 +#define EPSILON 1e-6 +#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +#define whiteComplement( a ) ( 1.0 - saturate( a ) ) +float pow2( const in float x ) { return x*x; } +vec3 pow2( const in vec3 x ) { return x*x; } +float pow3( const in float x ) { return x*x*x; } +float pow4( const in float x ) { float x2 = x*x; return x2*x2; } +float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } +float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } +highp float rand( const in vec2 uv ) { + const highp float a = 12.9898, b = 78.233, c = 43758.5453; + highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); + return fract( sin( sn ) * c ); +} +#ifdef HIGH_PRECISION + float precisionSafeLength( vec3 v ) { return length( v ); } +#else + float precisionSafeLength( vec3 v ) { + float maxComponent = max3( abs( v ) ); + return length( v / maxComponent ) * maxComponent; + } +#endif +struct IncidentLight { + vec3 color; + vec3 direction; + bool visible; +}; +struct ReflectedLight { + vec3 directDiffuse; + vec3 directSpecular; + vec3 indirectDiffuse; + vec3 indirectSpecular; +}; +#ifdef USE_ALPHAHASH + varying vec3 vPosition; +#endif +vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); +} +vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); +} +mat3 transposeMat3( const in mat3 m ) { + mat3 tmp; + tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x ); + tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y ); + tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z ); + return tmp; +} +bool isPerspectiveMatrix( mat4 m ) { + return m[ 2 ][ 3 ] == - 1.0; +} +vec2 equirectUv( in vec3 dir ) { + float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; + float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; + return vec2( u, v ); +} +vec3 BRDF_Lambert( const in vec3 diffuseColor ) { + return RECIPROCAL_PI * diffuseColor; +} +vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} +float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} // validated`,Iu=`#ifdef ENVMAP_TYPE_CUBE_UV + #define cubeUV_minMipLevel 4.0 + #define cubeUV_minTileSize 16.0 + float getFace( vec3 direction ) { + vec3 absDirection = abs( direction ); + float face = - 1.0; + if ( absDirection.x > absDirection.z ) { + if ( absDirection.x > absDirection.y ) + face = direction.x > 0.0 ? 0.0 : 3.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } else { + if ( absDirection.z > absDirection.y ) + face = direction.z > 0.0 ? 2.0 : 5.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } + return face; + } + vec2 getUV( vec3 direction, float face ) { + vec2 uv; + if ( face == 0.0 ) { + uv = vec2( direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 1.0 ) { + uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); + } else if ( face == 2.0 ) { + uv = vec2( - direction.x, direction.y ) / abs( direction.z ); + } else if ( face == 3.0 ) { + uv = vec2( - direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 4.0 ) { + uv = vec2( - direction.x, direction.z ) / abs( direction.y ); + } else { + uv = vec2( direction.x, direction.y ) / abs( direction.z ); + } + return 0.5 * ( uv + 1.0 ); + } + vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { + float face = getFace( direction ); + float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); + mipInt = max( mipInt, cubeUV_minMipLevel ); + float faceSize = exp2( mipInt ); + highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0; + if ( face > 2.0 ) { + uv.y += faceSize; + face -= 3.0; + } + uv.x += face * faceSize; + uv.x += filterInt * 3.0 * cubeUV_minTileSize; + uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize ); + uv.x *= CUBEUV_TEXEL_WIDTH; + uv.y *= CUBEUV_TEXEL_HEIGHT; + #ifdef texture2DGradEXT + return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb; + #else + return texture2D( envMap, uv ).rgb; + #endif + } + #define cubeUV_r0 1.0 + #define cubeUV_m0 - 2.0 + #define cubeUV_r1 0.8 + #define cubeUV_m1 - 1.0 + #define cubeUV_r4 0.4 + #define cubeUV_m4 2.0 + #define cubeUV_r5 0.305 + #define cubeUV_m5 3.0 + #define cubeUV_r6 0.21 + #define cubeUV_m6 4.0 + float roughnessToMip( float roughness ) { + float mip = 0.0; + if ( roughness >= cubeUV_r1 ) { + mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0; + } else if ( roughness >= cubeUV_r4 ) { + mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1; + } else if ( roughness >= cubeUV_r5 ) { + mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4; + } else if ( roughness >= cubeUV_r6 ) { + mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5; + } else { + mip = - 2.0 * log2( 1.16 * roughness ); } + return mip; + } + vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { + float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP ); + float mipF = fract( mip ); + float mipInt = floor( mip ); + vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); + if ( mipF == 0.0 ) { + return vec4( color0, 1.0 ); + } else { + vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); + return vec4( mix( color0, color1, mipF ), 1.0 ); + } + } +#endif`,Pu=`vec3 transformedNormal = objectNormal; +#ifdef USE_TANGENT + vec3 transformedTangent = objectTangent; +#endif +#ifdef USE_BATCHING + mat3 bm = mat3( batchingMatrix ); + transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); + transformedNormal = bm * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = bm * transformedTangent; + #endif +#endif +#ifdef USE_INSTANCING + mat3 im = mat3( instanceMatrix ); + transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); + transformedNormal = im * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = im * transformedTangent; + #endif +#endif +transformedNormal = normalMatrix * transformedNormal; +#ifdef FLIP_SIDED + transformedNormal = - transformedNormal; +#endif +#ifdef USE_TANGENT + transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; + #ifdef FLIP_SIDED + transformedTangent = - transformedTangent; + #endif +#endif`,Du=`#ifdef USE_DISPLACEMENTMAP + uniform sampler2D displacementMap; + uniform float displacementScale; + uniform float displacementBias; +#endif`,Lu=`#ifdef USE_DISPLACEMENTMAP + transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); +#endif`,Uu=`#ifdef USE_EMISSIVEMAP + vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); + #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE + emissiveColor = sRGBTransferEOTF( emissiveColor ); + #endif + totalEmissiveRadiance *= emissiveColor.rgb; +#endif`,Nu=`#ifdef USE_EMISSIVEMAP + uniform sampler2D emissiveMap; +#endif`,Fu="gl_FragColor = linearToOutputTexel( gl_FragColor );",Ou=`vec4 LinearTransferOETF( in vec4 value ) { + return value; +} +vec4 sRGBTransferEOTF( in vec4 value ) { + return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a ); +} +vec4 sRGBTransferOETF( in vec4 value ) { + return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); +}`,Bu=`#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vec3 cameraToFrag; + if ( isOrthographic ) { + cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToFrag = normalize( vWorldPosition - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vec3 reflectVec = reflect( cameraToFrag, worldNormal ); + #else + vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); + #endif + #else + vec3 reflectVec = vReflect; + #endif + #ifdef ENVMAP_TYPE_CUBE + vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); + #else + vec4 envColor = vec4( 0.0 ); + #endif + #ifdef ENVMAP_BLENDING_MULTIPLY + outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_MIX ) + outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_ADD ) + outgoingLight += envColor.xyz * specularStrength * reflectivity; + #endif +#endif`,zu=`#ifdef USE_ENVMAP + uniform float envMapIntensity; + uniform float flipEnvMap; + uniform mat3 envMapRotation; + #ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; + #else + uniform sampler2D envMap; + #endif + +#endif`,ku=`#ifdef USE_ENVMAP + uniform float reflectivity; + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + varying vec3 vWorldPosition; + uniform float refractionRatio; + #else + varying vec3 vReflect; + #endif +#endif`,Vu=`#ifdef USE_ENVMAP + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + + varying vec3 vWorldPosition; + #else + varying vec3 vReflect; + uniform float refractionRatio; + #endif +#endif`,Hu=`#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vWorldPosition = worldPosition.xyz; + #else + vec3 cameraToVertex; + if ( isOrthographic ) { + cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vReflect = reflect( cameraToVertex, worldNormal ); + #else + vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); + #endif + #endif +#endif`,Gu=`#ifdef USE_FOG + vFogDepth = - mvPosition.z; +#endif`,Wu=`#ifdef USE_FOG + varying float vFogDepth; +#endif`,Xu=`#ifdef USE_FOG + #ifdef FOG_EXP2 + float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); + #else + float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); + #endif + gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); +#endif`,qu=`#ifdef USE_FOG + uniform vec3 fogColor; + varying float vFogDepth; + #ifdef FOG_EXP2 + uniform float fogDensity; + #else + uniform float fogNear; + uniform float fogFar; + #endif +#endif`,Yu=`#ifdef USE_GRADIENTMAP + uniform sampler2D gradientMap; +#endif +vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { + float dotNL = dot( normal, lightDirection ); + vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); + #ifdef USE_GRADIENTMAP + return vec3( texture2D( gradientMap, coord ).r ); + #else + vec2 fw = fwidth( coord ) * 0.5; + return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); + #endif +}`,Zu=`#ifdef USE_LIGHTMAP + uniform sampler2D lightMap; + uniform float lightMapIntensity; +#endif`,Ju=`LambertMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularStrength = specularStrength;`,$u=`varying vec3 vViewPosition; +struct LambertMaterial { + vec3 diffuseColor; + float specularStrength; +}; +void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Lambert +#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,Ku=`uniform bool receiveShadow; +uniform vec3 ambientLightColor; +#if defined( USE_LIGHT_PROBES ) + uniform vec3 lightProbe[ 9 ]; +#endif +vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { + float x = normal.x, y = normal.y, z = normal.z; + vec3 result = shCoefficients[ 0 ] * 0.886227; + result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; + result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; + result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; + result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; + result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; + result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); + result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; + result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); + return result; +} +vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); + return irradiance; +} +vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { + vec3 irradiance = ambientLightColor; + return irradiance; +} +float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { + float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); + if ( cutoffDistance > 0.0 ) { + distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); + } + return distanceFalloff; +} +float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { + return smoothstep( coneCosine, penumbraCosine, angleCosine ); +} +#if NUM_DIR_LIGHTS > 0 + struct DirectionalLight { + vec3 direction; + vec3 color; + }; + uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; + void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { + light.color = directionalLight.color; + light.direction = directionalLight.direction; + light.visible = true; + } +#endif +#if NUM_POINT_LIGHTS > 0 + struct PointLight { + vec3 position; + vec3 color; + float distance; + float decay; + }; + uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; + void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = pointLight.position - geometryPosition; + light.direction = normalize( lVector ); + float lightDistance = length( lVector ); + light.color = pointLight.color; + light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } +#endif +#if NUM_SPOT_LIGHTS > 0 + struct SpotLight { + vec3 position; + vec3 direction; + vec3 color; + float distance; + float decay; + float coneCos; + float penumbraCos; + }; + uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; + void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = spotLight.position - geometryPosition; + light.direction = normalize( lVector ); + float angleCos = dot( light.direction, spotLight.direction ); + float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); + if ( spotAttenuation > 0.0 ) { + float lightDistance = length( lVector ); + light.color = spotLight.color * spotAttenuation; + light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } else { + light.color = vec3( 0.0 ); + light.visible = false; + } + } +#endif +#if NUM_RECT_AREA_LIGHTS > 0 + struct RectAreaLight { + vec3 color; + vec3 position; + vec3 halfWidth; + vec3 halfHeight; + }; + uniform sampler2D ltc_1; uniform sampler2D ltc_2; + uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; +#endif +#if NUM_HEMI_LIGHTS > 0 + struct HemisphereLight { + vec3 direction; + vec3 skyColor; + vec3 groundColor; + }; + uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; + vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { + float dotNL = dot( normal, hemiLight.direction ); + float hemiDiffuseWeight = 0.5 * dotNL + 0.5; + vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); + return irradiance; + } +#endif`,ju=`#ifdef USE_ENVMAP + vec3 getIBLIrradiance( const in vec3 normal ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 ); + return PI * envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 reflectVec = reflect( - viewDir, normal ); + reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) ); + reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness ); + return envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + #ifdef USE_ANISOTROPY + vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 bentNormal = cross( bitangent, viewDir ); + bentNormal = normalize( cross( bentNormal, bitangent ) ); + bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); + return getIBLRadiance( viewDir, bentNormal, roughness ); + #else + return vec3( 0.0 ); + #endif + } + #endif +#endif`,Qu=`ToonMaterial material; +material.diffuseColor = diffuseColor.rgb;`,td=`varying vec3 vViewPosition; +struct ToonMaterial { + vec3 diffuseColor; +}; +void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Toon +#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,ed=`BlinnPhongMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularColor = specular; +material.specularShininess = shininess; +material.specularStrength = specularStrength;`,nd=`varying vec3 vViewPosition; +struct BlinnPhongMaterial { + vec3 diffuseColor; + vec3 specularColor; + float specularShininess; + float specularStrength; +}; +void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); + reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; +} +void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_BlinnPhong +#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,id=`PhysicalMaterial material; +material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor ); +vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); +float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); +material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; +material.roughness = min( material.roughness, 1.0 ); +#ifdef IOR + material.ior = ior; + #ifdef USE_SPECULAR + float specularIntensityFactor = specularIntensity; + vec3 specularColorFactor = specularColor; + #ifdef USE_SPECULAR_COLORMAP + specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; + #endif + material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); + #else + float specularIntensityFactor = 1.0; + vec3 specularColorFactor = vec3( 1.0 ); + material.specularF90 = 1.0; + #endif + material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor ); +#else + material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor ); + material.specularF90 = 1.0; +#endif +#ifdef USE_CLEARCOAT + material.clearcoat = clearcoat; + material.clearcoatRoughness = clearcoatRoughness; + material.clearcoatF0 = vec3( 0.04 ); + material.clearcoatF90 = 1.0; + #ifdef USE_CLEARCOATMAP + material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; + #endif + #ifdef USE_CLEARCOAT_ROUGHNESSMAP + material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; + #endif + material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); + material.clearcoatRoughness += geometryRoughness; + material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); +#endif +#ifdef USE_DISPERSION + material.dispersion = dispersion; +#endif +#ifdef USE_IRIDESCENCE + material.iridescence = iridescence; + material.iridescenceIOR = iridescenceIOR; + #ifdef USE_IRIDESCENCEMAP + material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; + #endif + #ifdef USE_IRIDESCENCE_THICKNESSMAP + material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; + #else + material.iridescenceThickness = iridescenceThicknessMaximum; + #endif +#endif +#ifdef USE_SHEEN + material.sheenColor = sheenColor; + #ifdef USE_SHEEN_COLORMAP + material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; + #endif + material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 ); + #ifdef USE_SHEEN_ROUGHNESSMAP + material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; + #endif +#endif +#ifdef USE_ANISOTROPY + #ifdef USE_ANISOTROPYMAP + mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); + vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; + vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; + #else + vec2 anisotropyV = anisotropyVector; + #endif + material.anisotropy = length( anisotropyV ); + if( material.anisotropy == 0.0 ) { + anisotropyV = vec2( 1.0, 0.0 ); + } else { + anisotropyV /= material.anisotropy; + material.anisotropy = saturate( material.anisotropy ); + } + material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); + material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; + material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; +#endif`,sd=`struct PhysicalMaterial { + vec3 diffuseColor; + float roughness; + vec3 specularColor; + float specularF90; + float dispersion; + #ifdef USE_CLEARCOAT + float clearcoat; + float clearcoatRoughness; + vec3 clearcoatF0; + float clearcoatF90; + #endif + #ifdef USE_IRIDESCENCE + float iridescence; + float iridescenceIOR; + float iridescenceThickness; + vec3 iridescenceFresnel; + vec3 iridescenceF0; + #endif + #ifdef USE_SHEEN + vec3 sheenColor; + float sheenRoughness; + #endif + #ifdef IOR + float ior; + #endif + #ifdef USE_TRANSMISSION + float transmission; + float transmissionAlpha; + float thickness; + float attenuationDistance; + vec3 attenuationColor; + #endif + #ifdef USE_ANISOTROPY + float anisotropy; + float alphaT; + vec3 anisotropyT; + vec3 anisotropyB; + #endif +}; +vec3 clearcoatSpecularDirect = vec3( 0.0 ); +vec3 clearcoatSpecularIndirect = vec3( 0.0 ); +vec3 sheenSpecularDirect = vec3( 0.0 ); +vec3 sheenSpecularIndirect = vec3(0.0 ); +vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { + float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); + float x2 = x * x; + float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); + return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); +} +float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { + float a2 = pow2( alpha ); + float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); + float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); + return 0.5 / max( gv + gl, EPSILON ); +} +float D_GGX( const in float alpha, const in float dotNH ) { + float a2 = pow2( alpha ); + float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; + return RECIPROCAL_PI * a2 / pow2( denom ); +} +#ifdef USE_ANISOTROPY + float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { + float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); + float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); + float v = 0.5 / ( gv + gl ); + return saturate(v); + } + float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { + float a2 = alphaT * alphaB; + highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); + highp float v2 = dot( v, v ); + float w2 = a2 / v2; + return RECIPROCAL_PI * a2 * pow2 ( w2 ); + } +#endif +#ifdef USE_CLEARCOAT + vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { + vec3 f0 = material.clearcoatF0; + float f90 = material.clearcoatF90; + float roughness = material.clearcoatRoughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + return F * ( V * D ); + } +#endif +vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { + vec3 f0 = material.specularColor; + float f90 = material.specularF90; + float roughness = material.roughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + #ifdef USE_IRIDESCENCE + F = mix( F, material.iridescenceFresnel, material.iridescence ); + #endif + #ifdef USE_ANISOTROPY + float dotTL = dot( material.anisotropyT, lightDir ); + float dotTV = dot( material.anisotropyT, viewDir ); + float dotTH = dot( material.anisotropyT, halfDir ); + float dotBL = dot( material.anisotropyB, lightDir ); + float dotBV = dot( material.anisotropyB, viewDir ); + float dotBH = dot( material.anisotropyB, halfDir ); + float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); + float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); + #else + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + #endif + return F * ( V * D ); +} +vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { + const float LUT_SIZE = 64.0; + const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; + const float LUT_BIAS = 0.5 / LUT_SIZE; + float dotNV = saturate( dot( N, V ) ); + vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); + uv = uv * LUT_SCALE + LUT_BIAS; + return uv; +} +float LTC_ClippedSphereFormFactor( const in vec3 f ) { + float l = length( f ); + return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); +} +vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { + float x = dot( v1, v2 ); + float y = abs( x ); + float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; + float b = 3.4175940 + ( 4.1616724 + y ) * y; + float v = a / b; + float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; + return cross( v1, v2 ) * theta_sintheta; +} +vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { + vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; + vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; + vec3 lightNormal = cross( v1, v2 ); + if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); + vec3 T1, T2; + T1 = normalize( V - N * dot( V, N ) ); + T2 = - cross( N, T1 ); + mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) ); + vec3 coords[ 4 ]; + coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); + coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); + coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); + coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); + coords[ 0 ] = normalize( coords[ 0 ] ); + coords[ 1 ] = normalize( coords[ 1 ] ); + coords[ 2 ] = normalize( coords[ 2 ] ); + coords[ 3 ] = normalize( coords[ 3 ] ); + vec3 vectorFormFactor = vec3( 0.0 ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); + float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); + return vec3( result ); +} +#if defined( USE_SHEEN ) +float D_Charlie( float roughness, float dotNH ) { + float alpha = pow2( roughness ); + float invAlpha = 1.0 / alpha; + float cos2h = dotNH * dotNH; + float sin2h = max( 1.0 - cos2h, 0.0078125 ); + return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); +} +float V_Neubelt( float dotNV, float dotNL ) { + return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); +} +vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float D = D_Charlie( sheenRoughness, dotNH ); + float V = V_Neubelt( dotNV, dotNL ); + return sheenColor * ( D * V ); +} +#endif +float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + float r2 = roughness * roughness; + float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95; + float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72; + float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) ); + return saturate( DG * RECIPROCAL_PI ); +} +vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 ); + const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 ); + vec4 r = roughness * c0 + c1; + float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y; + vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw; + return fab; +} +vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { + vec2 fab = DFGApprox( normal, viewDir, roughness ); + return specularColor * fab.x + specularF90 * fab.y; +} +#ifdef USE_IRIDESCENCE +void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#else +void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#endif + vec2 fab = DFGApprox( normal, viewDir, roughness ); + #ifdef USE_IRIDESCENCE + vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); + #else + vec3 Fr = specularColor; + #endif + vec3 FssEss = Fr * fab.x + specularF90 * fab.y; + float Ess = fab.x + fab.y; + float Ems = 1.0 - Ess; + vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); + singleScatter += FssEss; + multiScatter += Fms * Ems; +} +#if NUM_RECT_AREA_LIGHTS > 0 + void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + vec3 normal = geometryNormal; + vec3 viewDir = geometryViewDir; + vec3 position = geometryPosition; + vec3 lightPos = rectAreaLight.position; + vec3 halfWidth = rectAreaLight.halfWidth; + vec3 halfHeight = rectAreaLight.halfHeight; + vec3 lightColor = rectAreaLight.color; + float roughness = material.roughness; + vec3 rectCoords[ 4 ]; + rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; + rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; + rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; + vec2 uv = LTC_Uv( normal, viewDir, roughness ); + vec4 t1 = texture2D( ltc_1, uv ); + vec4 t2 = texture2D( ltc_2, uv ); + mat3 mInv = mat3( + vec3( t1.x, 0, t1.y ), + vec3( 0, 1, 0 ), + vec3( t1.z, 0, t1.w ) + ); + vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y ); + reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); + reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); + } +#endif +void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + #ifdef USE_CLEARCOAT + float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); + vec3 ccIrradiance = dotNLcc * directLight.color; + clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); + #endif + #ifdef USE_SHEEN + sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); + #endif + reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material ); + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { + #ifdef USE_CLEARCOAT + clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); + #endif + #ifdef USE_SHEEN + sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); + #endif + vec3 singleScattering = vec3( 0.0 ); + vec3 multiScattering = vec3( 0.0 ); + vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; + #ifdef USE_IRIDESCENCE + computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering ); + #else + computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering ); + #endif + vec3 totalScattering = singleScattering + multiScattering; + vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) ); + reflectedLight.indirectSpecular += radiance * singleScattering; + reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance; + reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance; +} +#define RE_Direct RE_Direct_Physical +#define RE_Direct_RectArea RE_Direct_RectArea_Physical +#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical +#define RE_IndirectSpecular RE_IndirectSpecular_Physical +float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { + return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); +}`,rd=` +vec3 geometryPosition = - vViewPosition; +vec3 geometryNormal = normal; +vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); +vec3 geometryClearcoatNormal = vec3( 0.0 ); +#ifdef USE_CLEARCOAT + geometryClearcoatNormal = clearcoatNormal; +#endif +#ifdef USE_IRIDESCENCE + float dotNVi = saturate( dot( normal, geometryViewDir ) ); + if ( material.iridescenceThickness == 0.0 ) { + material.iridescence = 0.0; + } else { + material.iridescence = saturate( material.iridescence ); + } + if ( material.iridescence > 0.0 ) { + material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); + material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); + } +#endif +IncidentLight directLight; +#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) + PointLight pointLight; + #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + pointLight = pointLights[ i ]; + getPointLightInfo( pointLight, geometryPosition, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) + pointLightShadow = pointLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) + SpotLight spotLight; + vec4 spotColor; + vec3 spotLightCoord; + bool inSpotLightMap; + #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + spotLight = spotLights[ i ]; + getSpotLightInfo( spotLight, geometryPosition, directLight ); + #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX + #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS + #else + #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #endif + #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) + spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; + inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); + spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); + directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; + #endif + #undef SPOT_LIGHT_MAP_INDEX + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + spotLightShadow = spotLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) + DirectionalLight directionalLight; + #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + directionalLight = directionalLights[ i ]; + getDirectionalLightInfo( directionalLight, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + directionalLightShadow = directionalLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) + RectAreaLight rectAreaLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { + rectAreaLight = rectAreaLights[ i ]; + RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if defined( RE_IndirectDiffuse ) + vec3 iblIrradiance = vec3( 0.0 ); + vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); + #if defined( USE_LIGHT_PROBES ) + irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); + #endif + #if ( NUM_HEMI_LIGHTS > 0 ) + #pragma unroll_loop_start + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); + } + #pragma unroll_loop_end + #endif +#endif +#if defined( RE_IndirectSpecular ) + vec3 radiance = vec3( 0.0 ); + vec3 clearcoatRadiance = vec3( 0.0 ); +#endif`,ad=`#if defined( RE_IndirectDiffuse ) + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; + irradiance += lightMapIrradiance; + #endif + #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV ) + iblIrradiance += getIBLIrradiance( geometryNormal ); + #endif +#endif +#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) + #ifdef USE_ANISOTROPY + radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); + #else + radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); + #endif + #ifdef USE_CLEARCOAT + clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); + #endif +#endif`,od=`#if defined( RE_IndirectDiffuse ) + RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif +#if defined( RE_IndirectSpecular ) + RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif`,ld=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) + gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; +#endif`,cd=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) + uniform float logDepthBufFC; + varying float vFragDepth; + varying float vIsPerspective; +#endif`,hd=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER + varying float vFragDepth; + varying float vIsPerspective; +#endif`,ud=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER + vFragDepth = 1.0 + gl_Position.w; + vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); +#endif`,dd=`#ifdef USE_MAP + vec4 sampledDiffuseColor = texture2D( map, vMapUv ); + #ifdef DECODE_VIDEO_TEXTURE + sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); + #endif + diffuseColor *= sampledDiffuseColor; +#endif`,fd=`#ifdef USE_MAP + uniform sampler2D map; +#endif`,pd=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + #if defined( USE_POINTS_UV ) + vec2 uv = vUv; + #else + vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; + #endif +#endif +#ifdef USE_MAP + diffuseColor *= texture2D( map, uv ); +#endif +#ifdef USE_ALPHAMAP + diffuseColor.a *= texture2D( alphaMap, uv ).g; +#endif`,md=`#if defined( USE_POINTS_UV ) + varying vec2 vUv; +#else + #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + uniform mat3 uvTransform; + #endif +#endif +#ifdef USE_MAP + uniform sampler2D map; +#endif +#ifdef USE_ALPHAMAP + uniform sampler2D alphaMap; +#endif`,gd=`float metalnessFactor = metalness; +#ifdef USE_METALNESSMAP + vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); + metalnessFactor *= texelMetalness.b; +#endif`,_d=`#ifdef USE_METALNESSMAP + uniform sampler2D metalnessMap; +#endif`,xd=`#ifdef USE_INSTANCING_MORPH + float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; + } +#endif`,yd=`#if defined( USE_MORPHCOLORS ) + vColor *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + #if defined( USE_COLOR_ALPHA ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; + #elif defined( USE_COLOR ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; + #endif + } +#endif`,vd=`#ifdef USE_MORPHNORMALS + objectNormal *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; + } +#endif`,Md=`#ifdef USE_MORPHTARGETS + #ifndef USE_INSTANCING_MORPH + uniform float morphTargetBaseInfluence; + uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + #endif + uniform sampler2DArray morphTargetsTexture; + uniform ivec2 morphTargetsTextureSize; + vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { + int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; + int y = texelIndex / morphTargetsTextureSize.x; + int x = texelIndex - y * morphTargetsTextureSize.x; + ivec3 morphUV = ivec3( x, y, morphTargetIndex ); + return texelFetch( morphTargetsTexture, morphUV, 0 ); + } +#endif`,Sd=`#ifdef USE_MORPHTARGETS + transformed *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; + } +#endif`,bd=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; +#ifdef FLAT_SHADED + vec3 fdx = dFdx( vViewPosition ); + vec3 fdy = dFdy( vViewPosition ); + vec3 normal = normalize( cross( fdx, fdy ) ); +#else + vec3 normal = normalize( vNormal ); + #ifdef DOUBLE_SIDED + normal *= faceDirection; + #endif +#endif +#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) + #ifdef USE_TANGENT + mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn = getTangentFrame( - vViewPosition, normal, + #if defined( USE_NORMALMAP ) + vNormalMapUv + #elif defined( USE_CLEARCOAT_NORMALMAP ) + vClearcoatNormalMapUv + #else + vUv + #endif + ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn[0] *= faceDirection; + tbn[1] *= faceDirection; + #endif +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + #ifdef USE_TANGENT + mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn2[0] *= faceDirection; + tbn2[1] *= faceDirection; + #endif +#endif +vec3 nonPerturbedNormal = normal;`,Ed=`#ifdef USE_NORMALMAP_OBJECTSPACE + normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + #ifdef FLIP_SIDED + normal = - normal; + #endif + #ifdef DOUBLE_SIDED + normal = normal * faceDirection; + #endif + normal = normalize( normalMatrix * normal ); +#elif defined( USE_NORMALMAP_TANGENTSPACE ) + vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + mapN.xy *= normalScale; + normal = normalize( tbn * mapN ); +#elif defined( USE_BUMPMAP ) + normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); +#endif`,Td=`#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`,wd=`#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`,Ad=`#ifndef FLAT_SHADED + vNormal = normalize( transformedNormal ); + #ifdef USE_TANGENT + vTangent = normalize( transformedTangent ); + vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); + #endif +#endif`,Cd=`#ifdef USE_NORMALMAP + uniform sampler2D normalMap; + uniform vec2 normalScale; +#endif +#ifdef USE_NORMALMAP_OBJECTSPACE + uniform mat3 normalMatrix; +#endif +#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) + mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { + vec3 q0 = dFdx( eye_pos.xyz ); + vec3 q1 = dFdy( eye_pos.xyz ); + vec2 st0 = dFdx( uv.st ); + vec2 st1 = dFdy( uv.st ); + vec3 N = surf_norm; + vec3 q1perp = cross( q1, N ); + vec3 q0perp = cross( N, q0 ); + vec3 T = q1perp * st0.x + q0perp * st1.x; + vec3 B = q1perp * st0.y + q0perp * st1.y; + float det = max( dot( T, T ), dot( B, B ) ); + float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); + return mat3( T * scale, B * scale, N ); + } +#endif`,Rd=`#ifdef USE_CLEARCOAT + vec3 clearcoatNormal = nonPerturbedNormal; +#endif`,Id=`#ifdef USE_CLEARCOAT_NORMALMAP + vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; + clearcoatMapN.xy *= clearcoatNormalScale; + clearcoatNormal = normalize( tbn2 * clearcoatMapN ); +#endif`,Pd=`#ifdef USE_CLEARCOATMAP + uniform sampler2D clearcoatMap; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform sampler2D clearcoatNormalMap; + uniform vec2 clearcoatNormalScale; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform sampler2D clearcoatRoughnessMap; +#endif`,Dd=`#ifdef USE_IRIDESCENCEMAP + uniform sampler2D iridescenceMap; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform sampler2D iridescenceThicknessMap; +#endif`,Ld=`#ifdef OPAQUE +diffuseColor.a = 1.0; +#endif +#ifdef USE_TRANSMISSION +diffuseColor.a *= material.transmissionAlpha; +#endif +gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,Ud=`vec3 packNormalToRGB( const in vec3 normal ) { + return normalize( normal ) * 0.5 + 0.5; +} +vec3 unpackRGBToNormal( const in vec3 rgb ) { + return 2.0 * rgb.xyz - 1.0; +} +const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.; +const float Inv255 = 1. / 255.; +const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); +const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g ); +const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b ); +const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a ); +vec4 packDepthToRGBA( const in float v ) { + if( v <= 0.0 ) + return vec4( 0., 0., 0., 0. ); + if( v >= 1.0 ) + return vec4( 1., 1., 1., 1. ); + float vuf; + float af = modf( v * PackFactors.a, vuf ); + float bf = modf( vuf * ShiftRight8, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af ); +} +vec3 packDepthToRGB( const in float v ) { + if( v <= 0.0 ) + return vec3( 0., 0., 0. ); + if( v >= 1.0 ) + return vec3( 1., 1., 1. ); + float vuf; + float bf = modf( v * PackFactors.b, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec3( vuf * Inv255, gf * PackUpscale, bf ); +} +vec2 packDepthToRG( const in float v ) { + if( v <= 0.0 ) + return vec2( 0., 0. ); + if( v >= 1.0 ) + return vec2( 1., 1. ); + float vuf; + float gf = modf( v * 256., vuf ); + return vec2( vuf * Inv255, gf ); +} +float unpackRGBAToDepth( const in vec4 v ) { + return dot( v, UnpackFactors4 ); +} +float unpackRGBToDepth( const in vec3 v ) { + return dot( v, UnpackFactors3 ); +} +float unpackRGToDepth( const in vec2 v ) { + return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g; +} +vec4 pack2HalfToRGBA( const in vec2 v ) { + vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); + return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); +} +vec2 unpackRGBATo2Half( const in vec4 v ) { + return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); +} +float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { + return ( viewZ + near ) / ( near - far ); +} +float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { + return depth * ( near - far ) - near; +} +float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { + return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); +} +float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { + return ( near * far ) / ( ( far - near ) * depth - far ); +}`,Nd=`#ifdef PREMULTIPLIED_ALPHA + gl_FragColor.rgb *= gl_FragColor.a; +#endif`,Fd=`vec4 mvPosition = vec4( transformed, 1.0 ); +#ifdef USE_BATCHING + mvPosition = batchingMatrix * mvPosition; +#endif +#ifdef USE_INSTANCING + mvPosition = instanceMatrix * mvPosition; +#endif +mvPosition = modelViewMatrix * mvPosition; +gl_Position = projectionMatrix * mvPosition;`,Od=`#ifdef DITHERING + gl_FragColor.rgb = dithering( gl_FragColor.rgb ); +#endif`,Bd=`#ifdef DITHERING + vec3 dithering( vec3 color ) { + float grid_position = rand( gl_FragCoord.xy ); + vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); + dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); + return color + dither_shift_RGB; + } +#endif`,zd=`float roughnessFactor = roughness; +#ifdef USE_ROUGHNESSMAP + vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); + roughnessFactor *= texelRoughness.g; +#endif`,kd=`#ifdef USE_ROUGHNESSMAP + uniform sampler2D roughnessMap; +#endif`,Vd=`#if NUM_SPOT_LIGHT_COORDS > 0 + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#if NUM_SPOT_LIGHT_MAPS > 0 + uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif + float texture2DCompare( sampler2D depths, vec2 uv, float compare ) { + float depth = unpackRGBAToDepth( texture2D( depths, uv ) ); + #ifdef USE_REVERSED_DEPTH_BUFFER + return step( depth, compare ); + #else + return step( compare, depth ); + #endif + } + vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) { + return unpackRGBATo2Half( texture2D( shadow, uv ) ); + } + float VSMShadow( sampler2D shadow, vec2 uv, float compare ) { + float occlusion = 1.0; + vec2 distribution = texture2DDistribution( shadow, uv ); + #ifdef USE_REVERSED_DEPTH_BUFFER + float hard_shadow = step( distribution.x, compare ); + #else + float hard_shadow = step( compare, distribution.x ); + #endif + if ( hard_shadow != 1.0 ) { + float distance = compare - distribution.x; + float variance = max( 0.00000, distribution.y * distribution.y ); + float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 ); + } + return occlusion; + } + float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { + float shadow = 1.0; + shadowCoord.xyz /= shadowCoord.w; + shadowCoord.z += shadowBias; + bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; + bool frustumTest = inFrustum && shadowCoord.z <= 1.0; + if ( frustumTest ) { + #if defined( SHADOWMAP_TYPE_PCF ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx0 = - texelSize.x * shadowRadius; + float dy0 = - texelSize.y * shadowRadius; + float dx1 = + texelSize.x * shadowRadius; + float dy1 = + texelSize.y * shadowRadius; + float dx2 = dx0 / 2.0; + float dy2 = dy0 / 2.0; + float dx3 = dx1 / 2.0; + float dy3 = dy1 / 2.0; + shadow = ( + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z ) + ) * ( 1.0 / 17.0 ); + #elif defined( SHADOWMAP_TYPE_PCF_SOFT ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx = texelSize.x; + float dy = texelSize.y; + vec2 uv = shadowCoord.xy; + vec2 f = fract( uv * shadowMapSize + 0.5 ); + uv -= f * texelSize; + shadow = ( + texture2DCompare( shadowMap, uv, shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ), + f.x ), + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ), + f.x ), + f.y ) + ) * ( 1.0 / 9.0 ); + #elif defined( SHADOWMAP_TYPE_VSM ) + shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z ); + #else + shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } + vec2 cubeToUV( vec3 v, float texelSizeY ) { + vec3 absV = abs( v ); + float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) ); + absV *= scaleToCube; + v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY ); + vec2 planar = v.xy; + float almostATexel = 1.5 * texelSizeY; + float almostOne = 1.0 - almostATexel; + if ( absV.z >= almostOne ) { + if ( v.z > 0.0 ) + planar.x = 4.0 - v.x; + } else if ( absV.x >= almostOne ) { + float signX = sign( v.x ); + planar.x = v.z * signX + 2.0 * signX; + } else if ( absV.y >= almostOne ) { + float signY = sign( v.y ); + planar.x = v.x + 2.0 * signY + 2.0; + planar.y = v.z * signY - 2.0; + } + return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 ); + } + float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { + float shadow = 1.0; + vec3 lightToPosition = shadowCoord.xyz; + + float lightToPositionLength = length( lightToPosition ); + if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) { + float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias; + vec3 bd3D = normalize( lightToPosition ); + vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) ); + #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM ) + vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y; + shadow = ( + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp ) + ) * ( 1.0 / 9.0 ); + #else + shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } +#endif`,Hd=`#if NUM_SPOT_LIGHT_COORDS > 0 + uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif +#endif`,Gd=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) + vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + vec4 shadowWorldPosition; +#endif +#if defined( USE_SHADOWMAP ) + #if NUM_DIR_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); + vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); + vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif +#endif +#if NUM_SPOT_LIGHT_COORDS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { + shadowWorldPosition = worldPosition; + #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; + #endif + vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end +#endif`,Wd=`float getShadowMask() { + float shadow = 1.0; + #ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + directionalLight = directionalLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { + spotLight = spotLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + pointLight = pointLightShadows[ i ]; + shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; + } + #pragma unroll_loop_end + #endif + #endif + return shadow; +}`,Xd=`#ifdef USE_SKINNING + mat4 boneMatX = getBoneMatrix( skinIndex.x ); + mat4 boneMatY = getBoneMatrix( skinIndex.y ); + mat4 boneMatZ = getBoneMatrix( skinIndex.z ); + mat4 boneMatW = getBoneMatrix( skinIndex.w ); +#endif`,qd=`#ifdef USE_SKINNING + uniform mat4 bindMatrix; + uniform mat4 bindMatrixInverse; + uniform highp sampler2D boneTexture; + mat4 getBoneMatrix( const in float i ) { + int size = textureSize( boneTexture, 0 ).x; + int j = int( i ) * 4; + int x = j % size; + int y = j / size; + vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); + vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); + vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); + vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); + return mat4( v1, v2, v3, v4 ); + } +#endif`,Yd=`#ifdef USE_SKINNING + vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); + vec4 skinned = vec4( 0.0 ); + skinned += boneMatX * skinVertex * skinWeight.x; + skinned += boneMatY * skinVertex * skinWeight.y; + skinned += boneMatZ * skinVertex * skinWeight.z; + skinned += boneMatW * skinVertex * skinWeight.w; + transformed = ( bindMatrixInverse * skinned ).xyz; +#endif`,Zd=`#ifdef USE_SKINNING + mat4 skinMatrix = mat4( 0.0 ); + skinMatrix += skinWeight.x * boneMatX; + skinMatrix += skinWeight.y * boneMatY; + skinMatrix += skinWeight.z * boneMatZ; + skinMatrix += skinWeight.w * boneMatW; + skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; + objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; + #ifdef USE_TANGENT + objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; + #endif +#endif`,Jd=`float specularStrength; +#ifdef USE_SPECULARMAP + vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); + specularStrength = texelSpecular.r; +#else + specularStrength = 1.0; +#endif`,$d=`#ifdef USE_SPECULARMAP + uniform sampler2D specularMap; +#endif`,Kd=`#if defined( TONE_MAPPING ) + gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); +#endif`,jd=`#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +uniform float toneMappingExposure; +vec3 LinearToneMapping( vec3 color ) { + return saturate( toneMappingExposure * color ); +} +vec3 ReinhardToneMapping( vec3 color ) { + color *= toneMappingExposure; + return saturate( color / ( vec3( 1.0 ) + color ) ); +} +vec3 CineonToneMapping( vec3 color ) { + color *= toneMappingExposure; + color = max( vec3( 0.0 ), color - 0.004 ); + return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); +} +vec3 RRTAndODTFit( vec3 v ) { + vec3 a = v * ( v + 0.0245786 ) - 0.000090537; + vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; + return a / b; +} +vec3 ACESFilmicToneMapping( vec3 color ) { + const mat3 ACESInputMat = mat3( + vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), + vec3( 0.04823, 0.01566, 0.83777 ) + ); + const mat3 ACESOutputMat = mat3( + vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), + vec3( -0.07367, -0.00605, 1.07602 ) + ); + color *= toneMappingExposure / 0.6; + color = ACESInputMat * color; + color = RRTAndODTFit( color ); + color = ACESOutputMat * color; + return saturate( color ); +} +const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3( + vec3( 1.6605, - 0.1246, - 0.0182 ), + vec3( - 0.5876, 1.1329, - 0.1006 ), + vec3( - 0.0728, - 0.0083, 1.1187 ) +); +const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( + vec3( 0.6274, 0.0691, 0.0164 ), + vec3( 0.3293, 0.9195, 0.0880 ), + vec3( 0.0433, 0.0113, 0.8956 ) +); +vec3 agxDefaultContrastApprox( vec3 x ) { + vec3 x2 = x * x; + vec3 x4 = x2 * x2; + return + 15.5 * x4 * x2 + - 40.14 * x4 * x + + 31.96 * x4 + - 6.868 * x2 * x + + 0.4298 * x2 + + 0.1191 * x + - 0.00232; +} +vec3 AgXToneMapping( vec3 color ) { + const mat3 AgXInsetMatrix = mat3( + vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), + vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), + vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) + ); + const mat3 AgXOutsetMatrix = mat3( + vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), + vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), + vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) + ); + const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069; + color *= toneMappingExposure; + color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; + color = AgXInsetMatrix * color; + color = max( color, 1e-10 ); color = log2( color ); + color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv ); + color = clamp( color, 0.0, 1.0 ); + color = agxDefaultContrastApprox( color ); + color = AgXOutsetMatrix * color; + color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) ); + color = LINEAR_REC2020_TO_LINEAR_SRGB * color; + color = clamp( color, 0.0, 1.0 ); + return color; +} +vec3 NeutralToneMapping( vec3 color ) { + const float StartCompression = 0.8 - 0.04; + const float Desaturation = 0.15; + color *= toneMappingExposure; + float x = min( color.r, min( color.g, color.b ) ); + float offset = x < 0.08 ? x - 6.25 * x * x : 0.04; + color -= offset; + float peak = max( color.r, max( color.g, color.b ) ); + if ( peak < StartCompression ) return color; + float d = 1. - StartCompression; + float newPeak = 1. - d * d / ( peak + d - StartCompression ); + color *= newPeak / peak; + float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); + return mix( color, vec3( newPeak ), g ); +} +vec3 CustomToneMapping( vec3 color ) { return color; }`,Qd=`#ifdef USE_TRANSMISSION + material.transmission = transmission; + material.transmissionAlpha = 1.0; + material.thickness = thickness; + material.attenuationDistance = attenuationDistance; + material.attenuationColor = attenuationColor; + #ifdef USE_TRANSMISSIONMAP + material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; + #endif + #ifdef USE_THICKNESSMAP + material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; + #endif + vec3 pos = vWorldPosition; + vec3 v = normalize( cameraPosition - pos ); + vec3 n = inverseTransformDirection( normal, viewMatrix ); + vec4 transmitted = getIBLVolumeRefraction( + n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90, + pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness, + material.attenuationColor, material.attenuationDistance ); + material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); + totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); +#endif`,tf=`#ifdef USE_TRANSMISSION + uniform float transmission; + uniform float thickness; + uniform float attenuationDistance; + uniform vec3 attenuationColor; + #ifdef USE_TRANSMISSIONMAP + uniform sampler2D transmissionMap; + #endif + #ifdef USE_THICKNESSMAP + uniform sampler2D thicknessMap; + #endif + uniform vec2 transmissionSamplerSize; + uniform sampler2D transmissionSamplerMap; + uniform mat4 modelMatrix; + uniform mat4 projectionMatrix; + varying vec3 vWorldPosition; + float w0( float a ) { + return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); + } + float w1( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); + } + float w2( float a ){ + return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); + } + float w3( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * a ); + } + float g0( float a ) { + return w0( a ) + w1( a ); + } + float g1( float a ) { + return w2( a ) + w3( a ); + } + float h0( float a ) { + return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); + } + float h1( float a ) { + return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); + } + vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { + uv = uv * texelSize.zw + 0.5; + vec2 iuv = floor( uv ); + vec2 fuv = fract( uv ); + float g0x = g0( fuv.x ); + float g1x = g1( fuv.x ); + float h0x = h0( fuv.x ); + float h1x = h1( fuv.x ); + float h0y = h0( fuv.y ); + float h1y = h1( fuv.y ); + vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + + g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); + } + vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { + vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); + vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); + vec2 fLodSizeInv = 1.0 / fLodSize; + vec2 cLodSizeInv = 1.0 / cLodSize; + vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); + vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); + return mix( fSample, cSample, fract( lod ) ); + } + vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { + vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); + vec3 modelScale; + modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); + modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); + modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); + return normalize( refractionVector ) * thickness * modelScale; + } + float applyIorToRoughness( const in float roughness, const in float ior ) { + return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); + } + vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { + float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); + return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); + } + vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { + if ( isinf( attenuationDistance ) ) { + return vec3( 1.0 ); + } else { + vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; + vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; + } + } + vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, + const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, + const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness, + const in vec3 attenuationColor, const in float attenuationDistance ) { + vec4 transmittedLight; + vec3 transmittance; + #ifdef USE_DISPERSION + float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion; + vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread ); + for ( int i = 0; i < 3; i ++ ) { + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] ); + transmittedLight[ i ] = transmissionSample[ i ]; + transmittedLight.a += transmissionSample.a; + transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ]; + } + transmittedLight.a /= 3.0; + #else + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); + transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); + #endif + vec3 attenuatedColor = transmittance * transmittedLight.rgb; + vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); + float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; + return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); + } +#endif`,ef=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + varying vec2 vNormalMapUv; +#endif +#ifdef USE_EMISSIVEMAP + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_SPECULARMAP + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`,nf=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + uniform mat3 mapTransform; + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + uniform mat3 alphaMapTransform; + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + uniform mat3 lightMapTransform; + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + uniform mat3 aoMapTransform; + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + uniform mat3 bumpMapTransform; + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + uniform mat3 normalMapTransform; + varying vec2 vNormalMapUv; +#endif +#ifdef USE_DISPLACEMENTMAP + uniform mat3 displacementMapTransform; + varying vec2 vDisplacementMapUv; +#endif +#ifdef USE_EMISSIVEMAP + uniform mat3 emissiveMapTransform; + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + uniform mat3 metalnessMapTransform; + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + uniform mat3 roughnessMapTransform; + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + uniform mat3 anisotropyMapTransform; + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + uniform mat3 clearcoatMapTransform; + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform mat3 clearcoatNormalMapTransform; + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform mat3 clearcoatRoughnessMapTransform; + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + uniform mat3 sheenColorMapTransform; + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + uniform mat3 sheenRoughnessMapTransform; + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + uniform mat3 iridescenceMapTransform; + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform mat3 iridescenceThicknessMapTransform; + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SPECULARMAP + uniform mat3 specularMapTransform; + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + uniform mat3 specularColorMapTransform; + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + uniform mat3 specularIntensityMapTransform; + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`,sf=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + vUv = vec3( uv, 1 ).xy; +#endif +#ifdef USE_MAP + vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ALPHAMAP + vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_LIGHTMAP + vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_AOMAP + vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_BUMPMAP + vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_NORMALMAP + vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_DISPLACEMENTMAP + vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_EMISSIVEMAP + vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_METALNESSMAP + vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ROUGHNESSMAP + vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ANISOTROPYMAP + vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOATMAP + vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCEMAP + vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_COLORMAP + vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULARMAP + vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_COLORMAP + vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_TRANSMISSIONMAP + vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_THICKNESSMAP + vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; +#endif`,rf=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 + vec4 worldPosition = vec4( transformed, 1.0 ); + #ifdef USE_BATCHING + worldPosition = batchingMatrix * worldPosition; + #endif + #ifdef USE_INSTANCING + worldPosition = instanceMatrix * worldPosition; + #endif + worldPosition = modelMatrix * worldPosition; +#endif`,af=`varying vec2 vUv; +uniform mat3 uvTransform; +void main() { + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + gl_Position = vec4( position.xy, 1.0, 1.0 ); +}`,of=`uniform sampler2D t2D; +uniform float backgroundIntensity; +varying vec2 vUv; +void main() { + vec4 texColor = texture2D( t2D, vUv ); + #ifdef DECODE_VIDEO_TEXTURE + texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`,lf=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`,cf=`#ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; +#elif defined( ENVMAP_TYPE_CUBE_UV ) + uniform sampler2D envMap; +#endif +uniform float flipEnvMap; +uniform float backgroundBlurriness; +uniform float backgroundIntensity; +uniform mat3 backgroundRotation; +varying vec3 vWorldDirection; +#include +void main() { + #ifdef ENVMAP_TYPE_CUBE + vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) ); + #elif defined( ENVMAP_TYPE_CUBE_UV ) + vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness ); + #else + vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`,hf=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`,uf=`uniform samplerCube tCube; +uniform float tFlip; +uniform float opacity; +varying vec3 vWorldDirection; +void main() { + vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); + gl_FragColor = texColor; + gl_FragColor.a *= opacity; + #include + #include +}`,df=`#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vHighPrecisionZW = gl_Position.zw; +}`,ff=`#if DEPTH_PACKING == 3200 + uniform float opacity; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + vec4 diffuseColor = vec4( 1.0 ); + #include + #if DEPTH_PACKING == 3200 + diffuseColor.a = opacity; + #endif + #include + #include + #include + #include + #include + #ifdef USE_REVERSED_DEPTH_BUFFER + float fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ]; + #else + float fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5; + #endif + #if DEPTH_PACKING == 3200 + gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); + #elif DEPTH_PACKING == 3201 + gl_FragColor = packDepthToRGBA( fragCoordZ ); + #elif DEPTH_PACKING == 3202 + gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 ); + #elif DEPTH_PACKING == 3203 + gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); + #endif +}`,pf=`#define DISTANCE +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vWorldPosition = worldPosition.xyz; +}`,mf=`#define DISTANCE +uniform vec3 referencePosition; +uniform float nearDistance; +uniform float farDistance; +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +#include +void main () { + vec4 diffuseColor = vec4( 1.0 ); + #include + #include + #include + #include + #include + float dist = length( vWorldPosition - referencePosition ); + dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); + dist = saturate( dist ); + gl_FragColor = packDepthToRGBA( dist ); +}`,gf=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include +}`,_f=`uniform sampler2D tEquirect; +varying vec3 vWorldDirection; +#include +void main() { + vec3 direction = normalize( vWorldDirection ); + vec2 sampleUV = equirectUv( direction ); + gl_FragColor = texture2D( tEquirect, sampleUV ); + #include + #include +}`,xf=`uniform float scale; +attribute float lineDistance; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vLineDistance = scale * lineDistance; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,yf=`uniform vec3 diffuse; +uniform float opacity; +uniform float dashSize; +uniform float totalSize; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + if ( mod( vLineDistance, totalSize ) > dashSize ) { + discard; + } + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`,vf=`#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) + #include + #include + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,Mf=`uniform vec3 diffuse; +uniform float opacity; +#ifndef FLAT_SHADED + varying vec3 vNormal; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; + #else + reflectedLight.indirectDiffuse += vec3( 1.0 ); + #endif + #include + reflectedLight.indirectDiffuse *= diffuseColor.rgb; + vec3 outgoingLight = reflectedLight.indirectDiffuse; + #include + #include + #include + #include + #include + #include + #include +}`,Sf=`#define LAMBERT +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`,bf=`#define LAMBERT +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`,Ef=`#define MATCAP +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; +}`,Tf=`#define MATCAP +uniform vec3 diffuse; +uniform float opacity; +uniform sampler2D matcap; +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 viewDir = normalize( vViewPosition ); + vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); + vec3 y = cross( viewDir, x ); + vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; + #ifdef USE_MATCAP + vec4 matcapColor = texture2D( matcap, uv ); + #else + vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); + #endif + vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; + #include + #include + #include + #include + #include + #include +}`,wf=`#define NORMAL +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + vViewPosition = - mvPosition.xyz; +#endif +}`,Af=`#define NORMAL +uniform float opacity; +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); + #include + #include + #include + #include + gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a ); + #ifdef OPAQUE + gl_FragColor.a = 1.0; + #endif +}`,Cf=`#define PHONG +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`,Rf=`#define PHONG +uniform vec3 diffuse; +uniform vec3 emissive; +uniform vec3 specular; +uniform float shininess; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`,If=`#define STANDARD +varying vec3 vViewPosition; +#ifdef USE_TRANSMISSION + varying vec3 vWorldPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +#ifdef USE_TRANSMISSION + vWorldPosition = worldPosition.xyz; +#endif +}`,Pf=`#define STANDARD +#ifdef PHYSICAL + #define IOR + #define USE_SPECULAR +#endif +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float roughness; +uniform float metalness; +uniform float opacity; +#ifdef IOR + uniform float ior; +#endif +#ifdef USE_SPECULAR + uniform float specularIntensity; + uniform vec3 specularColor; + #ifdef USE_SPECULAR_COLORMAP + uniform sampler2D specularColorMap; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + uniform sampler2D specularIntensityMap; + #endif +#endif +#ifdef USE_CLEARCOAT + uniform float clearcoat; + uniform float clearcoatRoughness; +#endif +#ifdef USE_DISPERSION + uniform float dispersion; +#endif +#ifdef USE_IRIDESCENCE + uniform float iridescence; + uniform float iridescenceIOR; + uniform float iridescenceThicknessMinimum; + uniform float iridescenceThicknessMaximum; +#endif +#ifdef USE_SHEEN + uniform vec3 sheenColor; + uniform float sheenRoughness; + #ifdef USE_SHEEN_COLORMAP + uniform sampler2D sheenColorMap; + #endif + #ifdef USE_SHEEN_ROUGHNESSMAP + uniform sampler2D sheenRoughnessMap; + #endif +#endif +#ifdef USE_ANISOTROPY + uniform vec2 anisotropyVector; + #ifdef USE_ANISOTROPYMAP + uniform sampler2D anisotropyMap; + #endif +#endif +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; + vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; + #include + vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; + #ifdef USE_SHEEN + float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor ); + outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect; + #endif + #ifdef USE_CLEARCOAT + float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); + vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); + outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; + #endif + #include + #include + #include + #include + #include + #include +}`,Df=`#define TOON +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +}`,Lf=`#define TOON +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include +}`,Uf=`uniform float size; +uniform float scale; +#include +#include +#include +#include +#include +#include +#ifdef USE_POINTS_UV + varying vec2 vUv; + uniform mat3 uvTransform; +#endif +void main() { + #ifdef USE_POINTS_UV + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + #endif + #include + #include + #include + #include + #include + #include + gl_PointSize = size; + #ifdef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); + #endif + #include + #include + #include + #include +}`,Nf=`uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`,Ff=`#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,Of=`uniform vec3 color; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); + #include + #include + #include +}`,Bf=`uniform float rotation; +uniform vec2 center; +#include +#include +#include +#include +#include +void main() { + #include + vec4 mvPosition = modelViewMatrix[ 3 ]; + vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) ); + #ifndef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) scale *= - mvPosition.z; + #endif + vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; + vec2 rotatedPosition; + rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; + rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; + mvPosition.xy += rotatedPosition; + gl_Position = projectionMatrix * mvPosition; + #include + #include + #include +}`,zf=`uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include +}`,Ot={alphahash_fragment:au,alphahash_pars_fragment:ou,alphamap_fragment:lu,alphamap_pars_fragment:cu,alphatest_fragment:hu,alphatest_pars_fragment:uu,aomap_fragment:du,aomap_pars_fragment:fu,batching_pars_vertex:pu,batching_vertex:mu,begin_vertex:gu,beginnormal_vertex:_u,bsdfs:xu,iridescence_fragment:yu,bumpmap_pars_fragment:vu,clipping_planes_fragment:Mu,clipping_planes_pars_fragment:Su,clipping_planes_pars_vertex:bu,clipping_planes_vertex:Eu,color_fragment:Tu,color_pars_fragment:wu,color_pars_vertex:Au,color_vertex:Cu,common:Ru,cube_uv_reflection_fragment:Iu,defaultnormal_vertex:Pu,displacementmap_pars_vertex:Du,displacementmap_vertex:Lu,emissivemap_fragment:Uu,emissivemap_pars_fragment:Nu,colorspace_fragment:Fu,colorspace_pars_fragment:Ou,envmap_fragment:Bu,envmap_common_pars_fragment:zu,envmap_pars_fragment:ku,envmap_pars_vertex:Vu,envmap_physical_pars_fragment:ju,envmap_vertex:Hu,fog_vertex:Gu,fog_pars_vertex:Wu,fog_fragment:Xu,fog_pars_fragment:qu,gradientmap_pars_fragment:Yu,lightmap_pars_fragment:Zu,lights_lambert_fragment:Ju,lights_lambert_pars_fragment:$u,lights_pars_begin:Ku,lights_toon_fragment:Qu,lights_toon_pars_fragment:td,lights_phong_fragment:ed,lights_phong_pars_fragment:nd,lights_physical_fragment:id,lights_physical_pars_fragment:sd,lights_fragment_begin:rd,lights_fragment_maps:ad,lights_fragment_end:od,logdepthbuf_fragment:ld,logdepthbuf_pars_fragment:cd,logdepthbuf_pars_vertex:hd,logdepthbuf_vertex:ud,map_fragment:dd,map_pars_fragment:fd,map_particle_fragment:pd,map_particle_pars_fragment:md,metalnessmap_fragment:gd,metalnessmap_pars_fragment:_d,morphinstance_vertex:xd,morphcolor_vertex:yd,morphnormal_vertex:vd,morphtarget_pars_vertex:Md,morphtarget_vertex:Sd,normal_fragment_begin:bd,normal_fragment_maps:Ed,normal_pars_fragment:Td,normal_pars_vertex:wd,normal_vertex:Ad,normalmap_pars_fragment:Cd,clearcoat_normal_fragment_begin:Rd,clearcoat_normal_fragment_maps:Id,clearcoat_pars_fragment:Pd,iridescence_pars_fragment:Dd,opaque_fragment:Ld,packing:Ud,premultiplied_alpha_fragment:Nd,project_vertex:Fd,dithering_fragment:Od,dithering_pars_fragment:Bd,roughnessmap_fragment:zd,roughnessmap_pars_fragment:kd,shadowmap_pars_fragment:Vd,shadowmap_pars_vertex:Hd,shadowmap_vertex:Gd,shadowmask_pars_fragment:Wd,skinbase_vertex:Xd,skinning_pars_vertex:qd,skinning_vertex:Yd,skinnormal_vertex:Zd,specularmap_fragment:Jd,specularmap_pars_fragment:$d,tonemapping_fragment:Kd,tonemapping_pars_fragment:jd,transmission_fragment:Qd,transmission_pars_fragment:tf,uv_pars_fragment:ef,uv_pars_vertex:nf,uv_vertex:sf,worldpos_vertex:rf,background_vert:af,background_frag:of,backgroundCube_vert:lf,backgroundCube_frag:cf,cube_vert:hf,cube_frag:uf,depth_vert:df,depth_frag:ff,distanceRGBA_vert:pf,distanceRGBA_frag:mf,equirect_vert:gf,equirect_frag:_f,linedashed_vert:xf,linedashed_frag:yf,meshbasic_vert:vf,meshbasic_frag:Mf,meshlambert_vert:Sf,meshlambert_frag:bf,meshmatcap_vert:Ef,meshmatcap_frag:Tf,meshnormal_vert:wf,meshnormal_frag:Af,meshphong_vert:Cf,meshphong_frag:Rf,meshphysical_vert:If,meshphysical_frag:Pf,meshtoon_vert:Df,meshtoon_frag:Lf,points_vert:Uf,points_frag:Nf,shadow_vert:Ff,shadow_frag:Of,sprite_vert:Bf,sprite_frag:zf},st={common:{diffuse:{value:new zt(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Ut},alphaMap:{value:null},alphaMapTransform:{value:new Ut},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Ut}},envmap:{envMap:{value:null},envMapRotation:{value:new Ut},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Ut}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Ut}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Ut},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Ut},normalScale:{value:new Pt(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Ut},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Ut}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Ut}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Ut}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new zt(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new zt(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Ut},alphaTest:{value:0},uvTransform:{value:new Ut}},sprite:{diffuse:{value:new zt(16777215)},opacity:{value:1},center:{value:new Pt(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Ut},alphaMap:{value:null},alphaMapTransform:{value:new Ut},alphaTest:{value:0}}},dn={basic:{uniforms:Te([st.common,st.specularmap,st.envmap,st.aomap,st.lightmap,st.fog]),vertexShader:Ot.meshbasic_vert,fragmentShader:Ot.meshbasic_frag},lambert:{uniforms:Te([st.common,st.specularmap,st.envmap,st.aomap,st.lightmap,st.emissivemap,st.bumpmap,st.normalmap,st.displacementmap,st.fog,st.lights,{emissive:{value:new zt(0)}}]),vertexShader:Ot.meshlambert_vert,fragmentShader:Ot.meshlambert_frag},phong:{uniforms:Te([st.common,st.specularmap,st.envmap,st.aomap,st.lightmap,st.emissivemap,st.bumpmap,st.normalmap,st.displacementmap,st.fog,st.lights,{emissive:{value:new zt(0)},specular:{value:new zt(1118481)},shininess:{value:30}}]),vertexShader:Ot.meshphong_vert,fragmentShader:Ot.meshphong_frag},standard:{uniforms:Te([st.common,st.envmap,st.aomap,st.lightmap,st.emissivemap,st.bumpmap,st.normalmap,st.displacementmap,st.roughnessmap,st.metalnessmap,st.fog,st.lights,{emissive:{value:new zt(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Ot.meshphysical_vert,fragmentShader:Ot.meshphysical_frag},toon:{uniforms:Te([st.common,st.aomap,st.lightmap,st.emissivemap,st.bumpmap,st.normalmap,st.displacementmap,st.gradientmap,st.fog,st.lights,{emissive:{value:new zt(0)}}]),vertexShader:Ot.meshtoon_vert,fragmentShader:Ot.meshtoon_frag},matcap:{uniforms:Te([st.common,st.bumpmap,st.normalmap,st.displacementmap,st.fog,{matcap:{value:null}}]),vertexShader:Ot.meshmatcap_vert,fragmentShader:Ot.meshmatcap_frag},points:{uniforms:Te([st.points,st.fog]),vertexShader:Ot.points_vert,fragmentShader:Ot.points_frag},dashed:{uniforms:Te([st.common,st.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Ot.linedashed_vert,fragmentShader:Ot.linedashed_frag},depth:{uniforms:Te([st.common,st.displacementmap]),vertexShader:Ot.depth_vert,fragmentShader:Ot.depth_frag},normal:{uniforms:Te([st.common,st.bumpmap,st.normalmap,st.displacementmap,{opacity:{value:1}}]),vertexShader:Ot.meshnormal_vert,fragmentShader:Ot.meshnormal_frag},sprite:{uniforms:Te([st.sprite,st.fog]),vertexShader:Ot.sprite_vert,fragmentShader:Ot.sprite_frag},background:{uniforms:{uvTransform:{value:new Ut},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Ot.background_vert,fragmentShader:Ot.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new Ut}},vertexShader:Ot.backgroundCube_vert,fragmentShader:Ot.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Ot.cube_vert,fragmentShader:Ot.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Ot.equirect_vert,fragmentShader:Ot.equirect_frag},distanceRGBA:{uniforms:Te([st.common,st.displacementmap,{referencePosition:{value:new N},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Ot.distanceRGBA_vert,fragmentShader:Ot.distanceRGBA_frag},shadow:{uniforms:Te([st.lights,st.fog,{color:{value:new zt(0)},opacity:{value:1}}]),vertexShader:Ot.shadow_vert,fragmentShader:Ot.shadow_frag}};dn.physical={uniforms:Te([dn.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Ut},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Ut},clearcoatNormalScale:{value:new Pt(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Ut},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Ut},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Ut},sheen:{value:0},sheenColor:{value:new zt(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Ut},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Ut},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Ut},transmissionSamplerSize:{value:new Pt},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Ut},attenuationDistance:{value:0},attenuationColor:{value:new zt(0)},specularColor:{value:new zt(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Ut},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Ut},anisotropyVector:{value:new Pt},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Ut}}]),vertexShader:Ot.meshphysical_vert,fragmentShader:Ot.meshphysical_frag};var _a={r:0,b:0,g:0},li=new sn,kf=new ue;function Vf(i,t,e,n,s,r,a){let o=new zt(0),l=r===!0?0:1,c,h,d=null,f=0,m=null;function _(E){let S=E.isScene===!0?E.background:null;return S&&S.isTexture&&(S=(E.backgroundBlurriness>0?e:t).get(S)),S}function M(E){let S=!1,C=_(E);C===null?u(o,l):C&&C.isColor&&(u(C,1),S=!0);let A=i.xr.getEnvironmentBlendMode();A==="additive"?n.buffers.color.setClear(0,0,0,1,a):A==="alpha-blend"&&n.buffers.color.setClear(0,0,0,0,a),(i.autoClear||S)&&(n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),i.clear(i.autoClearColor,i.autoClearDepth,i.autoClearStencil))}function p(E,S){let C=_(S);C&&(C.isCubeTexture||C.mapping===ws)?(h===void 0&&(h=new Pe(new kn(1,1,1),new rn({name:"BackgroundCubeMaterial",uniforms:oi(dn.backgroundCube.uniforms),vertexShader:dn.backgroundCube.vertexShader,fragmentShader:dn.backgroundCube.fragmentShader,side:Re,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),h.geometry.deleteAttribute("normal"),h.geometry.deleteAttribute("uv"),h.onBeforeRender=function(A,P,U){this.matrixWorld.copyPosition(U.matrixWorld)},Object.defineProperty(h.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),s.update(h)),li.copy(S.backgroundRotation),li.x*=-1,li.y*=-1,li.z*=-1,C.isCubeTexture&&C.isRenderTargetTexture===!1&&(li.y*=-1,li.z*=-1),h.material.uniforms.envMap.value=C,h.material.uniforms.flipEnvMap.value=C.isCubeTexture&&C.isRenderTargetTexture===!1?-1:1,h.material.uniforms.backgroundBlurriness.value=S.backgroundBlurriness,h.material.uniforms.backgroundIntensity.value=S.backgroundIntensity,h.material.uniforms.backgroundRotation.value.setFromMatrix4(kf.makeRotationFromEuler(li)),h.material.toneMapped=Gt.getTransfer(C.colorSpace)!==Yt,(d!==C||f!==C.version||m!==i.toneMapping)&&(h.material.needsUpdate=!0,d=C,f=C.version,m=i.toneMapping),h.layers.enableAll(),E.unshift(h,h.geometry,h.material,0,0,null)):C&&C.isTexture&&(c===void 0&&(c=new Pe(new ii(2,2),new rn({name:"BackgroundMaterial",uniforms:oi(dn.background.uniforms),vertexShader:dn.background.vertexShader,fragmentShader:dn.background.fragmentShader,side:Sn,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute("normal"),Object.defineProperty(c.material,"map",{get:function(){return this.uniforms.t2D.value}}),s.update(c)),c.material.uniforms.t2D.value=C,c.material.uniforms.backgroundIntensity.value=S.backgroundIntensity,c.material.toneMapped=Gt.getTransfer(C.colorSpace)!==Yt,C.matrixAutoUpdate===!0&&C.updateMatrix(),c.material.uniforms.uvTransform.value.copy(C.matrix),(d!==C||f!==C.version||m!==i.toneMapping)&&(c.material.needsUpdate=!0,d=C,f=C.version,m=i.toneMapping),c.layers.enableAll(),E.unshift(c,c.geometry,c.material,0,0,null))}function u(E,S){E.getRGB(_a,Ao(i)),n.buffers.color.setClear(_a.r,_a.g,_a.b,S,a)}function T(){h!==void 0&&(h.geometry.dispose(),h.material.dispose(),h=void 0),c!==void 0&&(c.geometry.dispose(),c.material.dispose(),c=void 0)}return{getClearColor:function(){return o},setClearColor:function(E,S=1){o.set(E),l=S,u(o,l)},getClearAlpha:function(){return l},setClearAlpha:function(E){l=E,u(o,l)},render:M,addToRenderList:p,dispose:T}}function Hf(i,t){let e=i.getParameter(i.MAX_VERTEX_ATTRIBS),n={},s=f(null),r=s,a=!1;function o(y,R,F,k,H){let q=!1,W=d(k,F,R);r!==W&&(r=W,c(r.object)),q=m(y,k,F,H),q&&_(y,k,F,H),H!==null&&t.update(H,i.ELEMENT_ARRAY_BUFFER),(q||a)&&(a=!1,S(y,R,F,k),H!==null&&i.bindBuffer(i.ELEMENT_ARRAY_BUFFER,t.get(H).buffer))}function l(){return i.createVertexArray()}function c(y){return i.bindVertexArray(y)}function h(y){return i.deleteVertexArray(y)}function d(y,R,F){let k=F.wireframe===!0,H=n[y.id];H===void 0&&(H={},n[y.id]=H);let q=H[R.id];q===void 0&&(q={},H[R.id]=q);let W=q[k];return W===void 0&&(W=f(l()),q[k]=W),W}function f(y){let R=[],F=[],k=[];for(let H=0;H=0){let ct=H[V],bt=q[V];if(bt===void 0&&(V==="instanceMatrix"&&y.instanceMatrix&&(bt=y.instanceMatrix),V==="instanceColor"&&y.instanceColor&&(bt=y.instanceColor)),ct===void 0||ct.attribute!==bt||bt&&ct.data!==bt.data)return!0;W++}return r.attributesNum!==W||r.index!==k}function _(y,R,F,k){let H={},q=R.attributes,W=0,et=F.getAttributes();for(let V in et)if(et[V].location>=0){let ct=q[V];ct===void 0&&(V==="instanceMatrix"&&y.instanceMatrix&&(ct=y.instanceMatrix),V==="instanceColor"&&y.instanceColor&&(ct=y.instanceColor));let bt={};bt.attribute=ct,ct&&ct.data&&(bt.data=ct.data),H[V]=bt,W++}r.attributes=H,r.attributesNum=W,r.index=k}function M(){let y=r.newAttributes;for(let R=0,F=y.length;R=0){let rt=H[et];if(rt===void 0&&(et==="instanceMatrix"&&y.instanceMatrix&&(rt=y.instanceMatrix),et==="instanceColor"&&y.instanceColor&&(rt=y.instanceColor)),rt!==void 0){let ct=rt.normalized,bt=rt.itemSize,kt=t.get(rt);if(kt===void 0)continue;let Kt=kt.buffer,ie=kt.type,Xt=kt.bytesPerElement,Y=ie===i.INT||ie===i.UNSIGNED_INT||rt.gpuType===Or;if(rt.isInterleavedBufferAttribute){let $=rt.data,ft=$.stride,It=rt.offset;if($.isInstancedInterleavedBuffer){for(let St=0;St0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.HIGH_FLOAT).precision>0)return"highp";P="mediump"}return P==="mediump"&&i.getShaderPrecisionFormat(i.VERTEX_SHADER,i.MEDIUM_FLOAT).precision>0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let c=e.precision!==void 0?e.precision:"highp",h=l(c);h!==c&&(console.warn("THREE.WebGLRenderer:",c,"not supported, using",h,"instead."),c=h);let d=e.logarithmicDepthBuffer===!0,f=e.reversedDepthBuffer===!0&&t.has("EXT_clip_control"),m=i.getParameter(i.MAX_TEXTURE_IMAGE_UNITS),_=i.getParameter(i.MAX_VERTEX_TEXTURE_IMAGE_UNITS),M=i.getParameter(i.MAX_TEXTURE_SIZE),p=i.getParameter(i.MAX_CUBE_MAP_TEXTURE_SIZE),u=i.getParameter(i.MAX_VERTEX_ATTRIBS),T=i.getParameter(i.MAX_VERTEX_UNIFORM_VECTORS),E=i.getParameter(i.MAX_VARYING_VECTORS),S=i.getParameter(i.MAX_FRAGMENT_UNIFORM_VECTORS),C=_>0,A=i.getParameter(i.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:r,getMaxPrecision:l,textureFormatReadable:a,textureTypeReadable:o,precision:c,logarithmicDepthBuffer:d,reversedDepthBuffer:f,maxTextures:m,maxVertexTextures:_,maxTextureSize:M,maxCubemapSize:p,maxAttributes:u,maxVertexUniforms:T,maxVaryings:E,maxFragmentUniforms:S,vertexTextures:C,maxSamples:A}}function Xf(i){let t=this,e=null,n=0,s=!1,r=!1,a=new We,o=new Ut,l={value:null,needsUpdate:!1};this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(d,f){let m=d.length!==0||f||n!==0||s;return s=f,n=d.length,m},this.beginShadows=function(){r=!0,h(null)},this.endShadows=function(){r=!1},this.setGlobalState=function(d,f){e=h(d,f,0)},this.setState=function(d,f,m){let _=d.clippingPlanes,M=d.clipIntersection,p=d.clipShadows,u=i.get(d);if(!s||_===null||_.length===0||r&&!p)r?h(null):c();else{let T=r?0:n,E=T*4,S=u.clippingState||null;l.value=S,S=h(_,f,E,m);for(let C=0;C!==E;++C)S[C]=e[C];u.clippingState=S,this.numIntersection=M?this.numPlanes:0,this.numPlanes+=T}};function c(){l.value!==e&&(l.value=e,l.needsUpdate=n>0),t.numPlanes=n,t.numIntersection=0}function h(d,f,m,_){let M=d!==null?d.length:0,p=null;if(M!==0){if(p=l.value,_!==!0||p===null){let u=m+M*4,T=f.matrixWorldInverse;o.getNormalMatrix(T),(p===null||p.length0){let c=new dr(l.height);return c.fromEquirectangularTexture(i,a),t.set(a,c),a.addEventListener("dispose",s),e(c.texture,a.mapping)}else return null}}return a}function s(a){let o=a.target;o.removeEventListener("dispose",s);let l=t.get(o);l!==void 0&&(t.delete(o),l.dispose())}function r(){t=new WeakMap}return{get:n,dispose:r}}var Yi=4,_c=[.125,.215,.35,.446,.526,.582],ui=20,Po=new Es,xc=new zt,Do=null,Lo=0,Uo=0,No=!1,hi=(1+Math.sqrt(5))/2,qi=1/hi,yc=[new N(-hi,qi,0),new N(hi,qi,0),new N(-qi,0,hi),new N(qi,0,hi),new N(0,hi,-qi),new N(0,hi,qi),new N(-1,1,-1),new N(1,1,-1),new N(-1,1,1),new N(1,1,1)],Yf=new N,va=class{constructor(t){this._renderer=t,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(t,e=0,n=.1,s=100,r={}){let{size:a=256,position:o=Yf}=r;Do=this._renderer.getRenderTarget(),Lo=this._renderer.getActiveCubeFace(),Uo=this._renderer.getActiveMipmapLevel(),No=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(a);let l=this._allocateTargets();return l.depthBuffer=!0,this._sceneToCubeUV(t,n,s,l,o),e>0&&this._blur(l,0,0,e),this._applyPMREM(l),this._cleanup(l),l}fromEquirectangular(t,e=null){return this._fromTexture(t,e)}fromCubemap(t,e=null){return this._fromTexture(t,e)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=Sc(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=Mc(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(t){this._lodMax=Math.floor(Math.log2(t)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let t=0;t2?C:0,C,C),d.setRenderTarget(s),u&&d.render(p,l),d.render(t,l)}p.geometry.dispose(),p.material.dispose(),d.toneMapping=m,d.autoClear=f,t.background=T}_textureToCubeUV(t,e){let n=this._renderer,s=t.mapping===ri||t.mapping===ai;s?(this._cubemapMaterial===null&&(this._cubemapMaterial=Sc()),this._cubemapMaterial.uniforms.flipEnvMap.value=t.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=Mc());let r=s?this._cubemapMaterial:this._equirectMaterial,a=new Pe(this._lodPlanes[0],r),o=r.uniforms;o.envMap.value=t;let l=this._cubeSize;xa(e,0,0,3*l,2*l),n.setRenderTarget(e),n.render(a,Po)}_applyPMREM(t){let e=this._renderer,n=e.autoClear;e.autoClear=!1;let s=this._lodPlanes.length;for(let r=1;rui&&console.warn(`sigmaRadians, ${r}, is too large and will clip, as it requested ${p} samples when the maximum is set to ${ui}`);let u=[],T=0;for(let P=0;PE-Yi?s-E+Yi:0),A=4*(this._cubeSize-S);xa(e,C,A,3*S,2*S),l.setRenderTarget(e),l.render(d,Po)}};function Zf(i){let t=[],e=[],n=[],s=i,r=i-Yi+1+_c.length;for(let a=0;ai-Yi?l=_c[a-i+Yi-1]:a===0&&(l=0),n.push(l);let c=1/(o-2),h=-c,d=1+c,f=[h,h,d,h,d,d,h,h,d,d,h,d],m=6,_=6,M=3,p=2,u=1,T=new Float32Array(M*_*m),E=new Float32Array(p*_*m),S=new Float32Array(u*_*m);for(let A=0;A2?0:-1,v=[P,U,0,P+2/3,U,0,P+2/3,U+1,0,P,U,0,P+2/3,U+1,0,P,U+1,0];T.set(v,M*_*A),E.set(f,p*_*A);let y=[A,A,A,A,A,A];S.set(y,u*_*A)}let C=new ze;C.setAttribute("position",new be(T,M)),C.setAttribute("uv",new be(E,p)),C.setAttribute("faceIndex",new be(S,u)),t.push(C),s>Yi&&s--}return{lodPlanes:t,sizeLods:e,sigmas:n}}function vc(i,t,e){let n=new cn(i,t,e);return n.texture.mapping=ws,n.texture.name="PMREM.cubeUv",n.scissorTest=!0,n}function xa(i,t,e,n,s){i.viewport.set(t,e,n,s),i.scissor.set(t,e,n,s)}function Jf(i,t,e){let n=new Float32Array(ui),s=new N(0,1,0);return new rn({name:"SphericalGaussianBlur",defines:{n:ui,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/e,CUBEUV_MAX_MIP:`${i}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:n},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:s}},vertexShader:Xo(),fragmentShader:` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform int samples; + uniform float weights[ n ]; + uniform bool latitudinal; + uniform float dTheta; + uniform float mipInt; + uniform vec3 poleAxis; + + #define ENVMAP_TYPE_CUBE_UV + #include + + vec3 getSample( float theta, vec3 axis ) { + + float cosTheta = cos( theta ); + // Rodrigues' axis-angle rotation + vec3 sampleDirection = vOutputDirection * cosTheta + + cross( axis, vOutputDirection ) * sin( theta ) + + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); + + return bilinearCubeUV( envMap, sampleDirection, mipInt ); + + } + + void main() { + + vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); + + if ( all( equal( axis, vec3( 0.0 ) ) ) ) { + + axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); + + } + + axis = normalize( axis ); + + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); + + for ( int i = 1; i < n; i++ ) { + + if ( i >= samples ) { + + break; + + } + + float theta = dTheta * float( i ); + gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); + gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); + + } + + } + `,blending:En,depthTest:!1,depthWrite:!1})}function Mc(){return new rn({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Xo(),fragmentShader:` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + + #include + + void main() { + + vec3 outputDirection = normalize( vOutputDirection ); + vec2 uv = equirectUv( outputDirection ); + + gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); + + } + `,blending:En,depthTest:!1,depthWrite:!1})}function Sc(){return new rn({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Xo(),fragmentShader:` + + precision mediump float; + precision mediump int; + + uniform float flipEnvMap; + + varying vec3 vOutputDirection; + + uniform samplerCube envMap; + + void main() { + + gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); + + } + `,blending:En,depthTest:!1,depthWrite:!1})}function Xo(){return` + + precision mediump float; + precision mediump int; + + attribute float faceIndex; + + varying vec3 vOutputDirection; + + // RH coordinate system; PMREM face-indexing convention + vec3 getDirection( vec2 uv, float face ) { + + uv = 2.0 * uv - 1.0; + + vec3 direction = vec3( uv, 1.0 ); + + if ( face == 0.0 ) { + + direction = direction.zyx; // ( 1, v, u ) pos x + + } else if ( face == 1.0 ) { + + direction = direction.xzy; + direction.xz *= -1.0; // ( -u, 1, -v ) pos y + + } else if ( face == 2.0 ) { + + direction.x *= -1.0; // ( -u, v, 1 ) pos z + + } else if ( face == 3.0 ) { + + direction = direction.zyx; + direction.xz *= -1.0; // ( -1, v, -u ) neg x + + } else if ( face == 4.0 ) { + + direction = direction.xzy; + direction.xy *= -1.0; // ( -u, -1, v ) neg y + + } else if ( face == 5.0 ) { + + direction.z *= -1.0; // ( u, v, -1 ) neg z + + } + + return direction; + + } + + void main() { + + vOutputDirection = getDirection( uv, faceIndex ); + gl_Position = vec4( position, 1.0 ); + + } + `}function $f(i){let t=new WeakMap,e=null;function n(o){if(o&&o.isTexture){let l=o.mapping,c=l===Ur||l===Nr,h=l===ri||l===ai;if(c||h){let d=t.get(o),f=d!==void 0?d.texture.pmremVersion:0;if(o.isRenderTargetTexture&&o.pmremVersion!==f)return e===null&&(e=new va(i)),d=c?e.fromEquirectangular(o,d):e.fromCubemap(o,d),d.texture.pmremVersion=o.pmremVersion,t.set(o,d),d.texture;if(d!==void 0)return d.texture;{let m=o.image;return c&&m&&m.height>0||h&&m&&s(m)?(e===null&&(e=new va(i)),d=c?e.fromEquirectangular(o):e.fromCubemap(o),d.texture.pmremVersion=o.pmremVersion,t.set(o,d),o.addEventListener("dispose",r),d.texture):null}}}return o}function s(o){let l=0,c=6;for(let h=0;ht.maxTextureSize&&(C=Math.ceil(S/t.maxTextureSize),S=t.maxTextureSize);let A=new Float32Array(S*C*4*d),P=new cs(A,S,C,d);P.type=un,P.needsUpdate=!0;let U=E*4;for(let y=0;y0)return i;let s=t*e,r=Ec[s];if(r===void 0&&(r=new Float32Array(s),Ec[s]=r),t!==0){n.toArray(r,0);for(let a=1,o=0;a!==t;++a)o+=e,i[a].toArray(r,o)}return r}function pe(i,t){if(i.length!==t.length)return!1;for(let e=0,n=i.length;e":" "} ${o}: ${e[a]}`)}return n.join(` +`)}var Pc=new Ut;function Yp(i){Gt._getMatrix(Pc,Gt.workingColorSpace,i);let t=`mat3( ${Pc.elements.map(e=>e.toFixed(4))} )`;switch(Gt.getTransfer(i)){case as:return[t,"LinearTransferOETF"];case Yt:return[t,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space: ",i),[t,"LinearTransferOETF"]}}function Dc(i,t,e){let n=i.getShaderParameter(t,i.COMPILE_STATUS),r=(i.getShaderInfoLog(t)||"").trim();if(n&&r==="")return"";let a=/ERROR: 0:(\d+)/.exec(r);if(a){let o=parseInt(a[1]);return e.toUpperCase()+` + +`+r+` + +`+qp(i.getShaderSource(t),o)}else return r}function Zp(i,t){let e=Yp(t);return[`vec4 ${i}( vec4 value ) {`,` return ${e[1]}( vec4( value.rgb * ${e[0]}, value.a ) );`,"}"].join(` +`)}function Jp(i,t){let e;switch(t){case Jl:e="Linear";break;case $l:e="Reinhard";break;case Kl:e="Cineon";break;case Lr:e="ACESFilmic";break;case Ql:e="AgX";break;case tc:e="Neutral";break;case jl:e="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",t),e="Linear"}return"vec3 "+i+"( vec3 color ) { return "+e+"ToneMapping( color ); }"}var ya=new N;function $p(){Gt.getLuminanceCoefficients(ya);let i=ya.x.toFixed(4),t=ya.y.toFixed(4),e=ya.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${i}, ${t}, ${e} );`," return dot( weights, rgb );","}"].join(` +`)}function Kp(i){return[i.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",i.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(Ds).join(` +`)}function jp(i){let t=[];for(let e in i){let n=i[e];n!==!1&&t.push("#define "+e+" "+n)}return t.join(` +`)}function Qp(i,t){let e={},n=i.getProgramParameter(t,i.ACTIVE_ATTRIBUTES);for(let s=0;s/gm;function ko(i){return i.replace(tm,nm)}var em=new Map;function nm(i,t){let e=Ot[t];if(e===void 0){let n=em.get(t);if(n!==void 0)e=Ot[n],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',t,n);else throw new Error("Can not resolve #include <"+t+">")}return ko(e)}var im=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function Nc(i){return i.replace(im,sm)}function sm(i,t,e,n){let s="";for(let r=parseInt(t);r0&&(p+=` +`),u=["#define SHADER_TYPE "+e.shaderType,"#define SHADER_NAME "+e.shaderName,_].filter(Ds).join(` +`),u.length>0&&(u+=` +`)):(p=[Fc(e),"#define SHADER_TYPE "+e.shaderType,"#define SHADER_NAME "+e.shaderName,_,e.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",e.batching?"#define USE_BATCHING":"",e.batchingColor?"#define USE_BATCHING_COLOR":"",e.instancing?"#define USE_INSTANCING":"",e.instancingColor?"#define USE_INSTANCING_COLOR":"",e.instancingMorph?"#define USE_INSTANCING_MORPH":"",e.useFog&&e.fog?"#define USE_FOG":"",e.useFog&&e.fogExp2?"#define FOG_EXP2":"",e.map?"#define USE_MAP":"",e.envMap?"#define USE_ENVMAP":"",e.envMap?"#define "+h:"",e.lightMap?"#define USE_LIGHTMAP":"",e.aoMap?"#define USE_AOMAP":"",e.bumpMap?"#define USE_BUMPMAP":"",e.normalMap?"#define USE_NORMALMAP":"",e.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",e.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",e.displacementMap?"#define USE_DISPLACEMENTMAP":"",e.emissiveMap?"#define USE_EMISSIVEMAP":"",e.anisotropy?"#define USE_ANISOTROPY":"",e.anisotropyMap?"#define USE_ANISOTROPYMAP":"",e.clearcoatMap?"#define USE_CLEARCOATMAP":"",e.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",e.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",e.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",e.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",e.specularMap?"#define USE_SPECULARMAP":"",e.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",e.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",e.roughnessMap?"#define USE_ROUGHNESSMAP":"",e.metalnessMap?"#define USE_METALNESSMAP":"",e.alphaMap?"#define USE_ALPHAMAP":"",e.alphaHash?"#define USE_ALPHAHASH":"",e.transmission?"#define USE_TRANSMISSION":"",e.transmissionMap?"#define USE_TRANSMISSIONMAP":"",e.thicknessMap?"#define USE_THICKNESSMAP":"",e.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",e.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",e.mapUv?"#define MAP_UV "+e.mapUv:"",e.alphaMapUv?"#define ALPHAMAP_UV "+e.alphaMapUv:"",e.lightMapUv?"#define LIGHTMAP_UV "+e.lightMapUv:"",e.aoMapUv?"#define AOMAP_UV "+e.aoMapUv:"",e.emissiveMapUv?"#define EMISSIVEMAP_UV "+e.emissiveMapUv:"",e.bumpMapUv?"#define BUMPMAP_UV "+e.bumpMapUv:"",e.normalMapUv?"#define NORMALMAP_UV "+e.normalMapUv:"",e.displacementMapUv?"#define DISPLACEMENTMAP_UV "+e.displacementMapUv:"",e.metalnessMapUv?"#define METALNESSMAP_UV "+e.metalnessMapUv:"",e.roughnessMapUv?"#define ROUGHNESSMAP_UV "+e.roughnessMapUv:"",e.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+e.anisotropyMapUv:"",e.clearcoatMapUv?"#define CLEARCOATMAP_UV "+e.clearcoatMapUv:"",e.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+e.clearcoatNormalMapUv:"",e.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+e.clearcoatRoughnessMapUv:"",e.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+e.iridescenceMapUv:"",e.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+e.iridescenceThicknessMapUv:"",e.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+e.sheenColorMapUv:"",e.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+e.sheenRoughnessMapUv:"",e.specularMapUv?"#define SPECULARMAP_UV "+e.specularMapUv:"",e.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+e.specularColorMapUv:"",e.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+e.specularIntensityMapUv:"",e.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+e.transmissionMapUv:"",e.thicknessMapUv?"#define THICKNESSMAP_UV "+e.thicknessMapUv:"",e.vertexTangents&&e.flatShading===!1?"#define USE_TANGENT":"",e.vertexColors?"#define USE_COLOR":"",e.vertexAlphas?"#define USE_COLOR_ALPHA":"",e.vertexUv1s?"#define USE_UV1":"",e.vertexUv2s?"#define USE_UV2":"",e.vertexUv3s?"#define USE_UV3":"",e.pointsUvs?"#define USE_POINTS_UV":"",e.flatShading?"#define FLAT_SHADED":"",e.skinning?"#define USE_SKINNING":"",e.morphTargets?"#define USE_MORPHTARGETS":"",e.morphNormals&&e.flatShading===!1?"#define USE_MORPHNORMALS":"",e.morphColors?"#define USE_MORPHCOLORS":"",e.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+e.morphTextureStride:"",e.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+e.morphTargetsCount:"",e.doubleSided?"#define DOUBLE_SIDED":"",e.flipSided?"#define FLIP_SIDED":"",e.shadowMapEnabled?"#define USE_SHADOWMAP":"",e.shadowMapEnabled?"#define "+l:"",e.sizeAttenuation?"#define USE_SIZEATTENUATION":"",e.numLightProbes>0?"#define USE_LIGHT_PROBES":"",e.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",e.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH"," uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",` +`].filter(Ds).join(` +`),u=[Fc(e),"#define SHADER_TYPE "+e.shaderType,"#define SHADER_NAME "+e.shaderName,_,e.useFog&&e.fog?"#define USE_FOG":"",e.useFog&&e.fogExp2?"#define FOG_EXP2":"",e.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",e.map?"#define USE_MAP":"",e.matcap?"#define USE_MATCAP":"",e.envMap?"#define USE_ENVMAP":"",e.envMap?"#define "+c:"",e.envMap?"#define "+h:"",e.envMap?"#define "+d:"",f?"#define CUBEUV_TEXEL_WIDTH "+f.texelWidth:"",f?"#define CUBEUV_TEXEL_HEIGHT "+f.texelHeight:"",f?"#define CUBEUV_MAX_MIP "+f.maxMip+".0":"",e.lightMap?"#define USE_LIGHTMAP":"",e.aoMap?"#define USE_AOMAP":"",e.bumpMap?"#define USE_BUMPMAP":"",e.normalMap?"#define USE_NORMALMAP":"",e.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",e.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",e.emissiveMap?"#define USE_EMISSIVEMAP":"",e.anisotropy?"#define USE_ANISOTROPY":"",e.anisotropyMap?"#define USE_ANISOTROPYMAP":"",e.clearcoat?"#define USE_CLEARCOAT":"",e.clearcoatMap?"#define USE_CLEARCOATMAP":"",e.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",e.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",e.dispersion?"#define USE_DISPERSION":"",e.iridescence?"#define USE_IRIDESCENCE":"",e.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",e.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",e.specularMap?"#define USE_SPECULARMAP":"",e.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",e.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",e.roughnessMap?"#define USE_ROUGHNESSMAP":"",e.metalnessMap?"#define USE_METALNESSMAP":"",e.alphaMap?"#define USE_ALPHAMAP":"",e.alphaTest?"#define USE_ALPHATEST":"",e.alphaHash?"#define USE_ALPHAHASH":"",e.sheen?"#define USE_SHEEN":"",e.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",e.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",e.transmission?"#define USE_TRANSMISSION":"",e.transmissionMap?"#define USE_TRANSMISSIONMAP":"",e.thicknessMap?"#define USE_THICKNESSMAP":"",e.vertexTangents&&e.flatShading===!1?"#define USE_TANGENT":"",e.vertexColors||e.instancingColor||e.batchingColor?"#define USE_COLOR":"",e.vertexAlphas?"#define USE_COLOR_ALPHA":"",e.vertexUv1s?"#define USE_UV1":"",e.vertexUv2s?"#define USE_UV2":"",e.vertexUv3s?"#define USE_UV3":"",e.pointsUvs?"#define USE_POINTS_UV":"",e.gradientMap?"#define USE_GRADIENTMAP":"",e.flatShading?"#define FLAT_SHADED":"",e.doubleSided?"#define DOUBLE_SIDED":"",e.flipSided?"#define FLIP_SIDED":"",e.shadowMapEnabled?"#define USE_SHADOWMAP":"",e.shadowMapEnabled?"#define "+l:"",e.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",e.numLightProbes>0?"#define USE_LIGHT_PROBES":"",e.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",e.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",e.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",e.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",e.toneMapping!==Tn?"#define TONE_MAPPING":"",e.toneMapping!==Tn?Ot.tonemapping_pars_fragment:"",e.toneMapping!==Tn?Jp("toneMapping",e.toneMapping):"",e.dithering?"#define DITHERING":"",e.opaque?"#define OPAQUE":"",Ot.colorspace_pars_fragment,Zp("linearToOutputTexel",e.outputColorSpace),$p(),e.useDepthPacking?"#define DEPTH_PACKING "+e.depthPacking:"",` +`].filter(Ds).join(` +`)),a=ko(a),a=Lc(a,e),a=Uc(a,e),o=ko(o),o=Lc(o,e),o=Uc(o,e),a=Nc(a),o=Nc(o),e.isRawShaderMaterial!==!0&&(T=`#version 300 es +`,p=[m,"#define attribute in","#define varying out","#define texture2D texture"].join(` +`)+` +`+p,u=["#define varying in",e.glslVersion===bo?"":"layout(location = 0) out highp vec4 pc_fragColor;",e.glslVersion===bo?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(` +`)+` +`+u);let E=T+p+a,S=T+u+o,C=Ic(s,s.VERTEX_SHADER,E),A=Ic(s,s.FRAGMENT_SHADER,S);s.attachShader(M,C),s.attachShader(M,A),e.index0AttributeName!==void 0?s.bindAttribLocation(M,0,e.index0AttributeName):e.morphTargets===!0&&s.bindAttribLocation(M,0,"position"),s.linkProgram(M);function P(R){if(i.debug.checkShaderErrors){let F=s.getProgramInfoLog(M)||"",k=s.getShaderInfoLog(C)||"",H=s.getShaderInfoLog(A)||"",q=F.trim(),W=k.trim(),et=H.trim(),V=!0,rt=!0;if(s.getProgramParameter(M,s.LINK_STATUS)===!1)if(V=!1,typeof i.debug.onShaderError=="function")i.debug.onShaderError(s,M,C,A);else{let ct=Dc(s,C,"vertex"),bt=Dc(s,A,"fragment");console.error("THREE.WebGLProgram: Shader Error "+s.getError()+" - VALIDATE_STATUS "+s.getProgramParameter(M,s.VALIDATE_STATUS)+` + +Material Name: `+R.name+` +Material Type: `+R.type+` + +Program Info Log: `+q+` +`+ct+` +`+bt)}else q!==""?console.warn("THREE.WebGLProgram: Program Info Log:",q):(W===""||et==="")&&(rt=!1);rt&&(R.diagnostics={runnable:V,programLog:q,vertexShader:{log:W,prefix:p},fragmentShader:{log:et,prefix:u}})}s.deleteShader(C),s.deleteShader(A),U=new Zi(s,M),v=Qp(s,M)}let U;this.getUniforms=function(){return U===void 0&&P(this),U};let v;this.getAttributes=function(){return v===void 0&&P(this),v};let y=e.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return y===!1&&(y=s.getProgramParameter(M,Wp)),y},this.destroy=function(){n.releaseStatesOfProgram(this),s.deleteProgram(M),this.program=void 0},this.type=e.shaderType,this.name=e.shaderName,this.id=Xp++,this.cacheKey=t,this.usedTimes=1,this.program=M,this.vertexShader=C,this.fragmentShader=A,this}var um=0,Vo=class{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(t){let e=t.vertexShader,n=t.fragmentShader,s=this._getShaderStage(e),r=this._getShaderStage(n),a=this._getShaderCacheForMaterial(t);return a.has(s)===!1&&(a.add(s),s.usedTimes++),a.has(r)===!1&&(a.add(r),r.usedTimes++),this}remove(t){let e=this.materialCache.get(t);for(let n of e)n.usedTimes--,n.usedTimes===0&&this.shaderCache.delete(n.code);return this.materialCache.delete(t),this}getVertexShaderID(t){return this._getShaderStage(t.vertexShader).id}getFragmentShaderID(t){return this._getShaderStage(t.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(t){let e=this.materialCache,n=e.get(t);return n===void 0&&(n=new Set,e.set(t,n)),n}_getShaderStage(t){let e=this.shaderCache,n=e.get(t);return n===void 0&&(n=new Ho(t),e.set(t,n)),n}},Ho=class{constructor(t){this.id=um++,this.code=t,this.usedTimes=0}};function dm(i,t,e,n,s,r,a){let o=new hs,l=new Vo,c=new Set,h=[],d=s.logarithmicDepthBuffer,f=s.vertexTextures,m=s.precision,_={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function M(v){return c.add(v),v===0?"uv":`uv${v}`}function p(v,y,R,F,k){let H=F.fog,q=k.geometry,W=v.isMeshStandardMaterial?F.environment:null,et=(v.isMeshStandardMaterial?e:t).get(v.envMap||W),V=et&&et.mapping===ws?et.image.height:null,rt=_[v.type];v.precision!==null&&(m=s.getMaxPrecision(v.precision),m!==v.precision&&console.warn("THREE.WebGLProgram.getParameters:",v.precision,"not supported, using",m,"instead."));let ct=q.morphAttributes.position||q.morphAttributes.normal||q.morphAttributes.color,bt=ct!==void 0?ct.length:0,kt=0;q.morphAttributes.position!==void 0&&(kt=1),q.morphAttributes.normal!==void 0&&(kt=2),q.morphAttributes.color!==void 0&&(kt=3);let Kt,ie,Xt,Y;if(rt){let qt=dn[rt];Kt=qt.vertexShader,ie=qt.fragmentShader}else Kt=v.vertexShader,ie=v.fragmentShader,l.update(v),Xt=l.getVertexShaderID(v),Y=l.getFragmentShaderID(v);let $=i.getRenderTarget(),ft=i.state.buffers.depth.getReversed(),It=k.isInstancedMesh===!0,St=k.isBatchedMesh===!0,Ht=!!v.map,ye=!!v.matcap,w=!!et,se=!!v.aoMap,Lt=!!v.lightMap,Ct=!!v.bumpMap,gt=!!v.normalMap,re=!!v.displacementMap,_t=!!v.emissiveMap,Ft=!!v.metalnessMap,_e=!!v.roughnessMap,he=v.anisotropy>0,b=v.clearcoat>0,g=v.dispersion>0,O=v.iridescence>0,X=v.sheen>0,J=v.transmission>0,G=he&&!!v.anisotropyMap,Mt=b&&!!v.clearcoatMap,nt=b&&!!v.clearcoatNormalMap,xt=b&&!!v.clearcoatRoughnessMap,yt=O&&!!v.iridescenceMap,Q=O&&!!v.iridescenceThicknessMap,lt=X&&!!v.sheenColorMap,At=X&&!!v.sheenRoughnessMap,vt=!!v.specularMap,at=!!v.specularColorMap,Nt=!!v.specularIntensityMap,I=J&&!!v.transmissionMap,tt=J&&!!v.thicknessMap,it=!!v.gradientMap,ut=!!v.alphaMap,K=v.alphaTest>0,Z=!!v.alphaHash,mt=!!v.extensions,Dt=Tn;v.toneMapped&&($===null||$.isXRRenderTarget===!0)&&(Dt=i.toneMapping);let jt={shaderID:rt,shaderType:v.type,shaderName:v.name,vertexShader:Kt,fragmentShader:ie,defines:v.defines,customVertexShaderID:Xt,customFragmentShaderID:Y,isRawShaderMaterial:v.isRawShaderMaterial===!0,glslVersion:v.glslVersion,precision:m,batching:St,batchingColor:St&&k._colorsTexture!==null,instancing:It,instancingColor:It&&k.instanceColor!==null,instancingMorph:It&&k.morphTexture!==null,supportsVertexTextures:f,outputColorSpace:$===null?i.outputColorSpace:$.isXRRenderTarget===!0?$.texture.colorSpace:bn,alphaToCoverage:!!v.alphaToCoverage,map:Ht,matcap:ye,envMap:w,envMapMode:w&&et.mapping,envMapCubeUVHeight:V,aoMap:se,lightMap:Lt,bumpMap:Ct,normalMap:gt,displacementMap:f&&re,emissiveMap:_t,normalMapObjectSpace:gt&&v.normalMapType===sc,normalMapTangentSpace:gt&&v.normalMapType===Mo,metalnessMap:Ft,roughnessMap:_e,anisotropy:he,anisotropyMap:G,clearcoat:b,clearcoatMap:Mt,clearcoatNormalMap:nt,clearcoatRoughnessMap:xt,dispersion:g,iridescence:O,iridescenceMap:yt,iridescenceThicknessMap:Q,sheen:X,sheenColorMap:lt,sheenRoughnessMap:At,specularMap:vt,specularColorMap:at,specularIntensityMap:Nt,transmission:J,transmissionMap:I,thicknessMap:tt,gradientMap:it,opaque:v.transparent===!1&&v.blending===ei&&v.alphaToCoverage===!1,alphaMap:ut,alphaTest:K,alphaHash:Z,combine:v.combine,mapUv:Ht&&M(v.map.channel),aoMapUv:se&&M(v.aoMap.channel),lightMapUv:Lt&&M(v.lightMap.channel),bumpMapUv:Ct&&M(v.bumpMap.channel),normalMapUv:gt&&M(v.normalMap.channel),displacementMapUv:re&&M(v.displacementMap.channel),emissiveMapUv:_t&&M(v.emissiveMap.channel),metalnessMapUv:Ft&&M(v.metalnessMap.channel),roughnessMapUv:_e&&M(v.roughnessMap.channel),anisotropyMapUv:G&&M(v.anisotropyMap.channel),clearcoatMapUv:Mt&&M(v.clearcoatMap.channel),clearcoatNormalMapUv:nt&&M(v.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:xt&&M(v.clearcoatRoughnessMap.channel),iridescenceMapUv:yt&&M(v.iridescenceMap.channel),iridescenceThicknessMapUv:Q&&M(v.iridescenceThicknessMap.channel),sheenColorMapUv:lt&&M(v.sheenColorMap.channel),sheenRoughnessMapUv:At&&M(v.sheenRoughnessMap.channel),specularMapUv:vt&&M(v.specularMap.channel),specularColorMapUv:at&&M(v.specularColorMap.channel),specularIntensityMapUv:Nt&&M(v.specularIntensityMap.channel),transmissionMapUv:I&&M(v.transmissionMap.channel),thicknessMapUv:tt&&M(v.thicknessMap.channel),alphaMapUv:ut&&M(v.alphaMap.channel),vertexTangents:!!q.attributes.tangent&&(gt||he),vertexColors:v.vertexColors,vertexAlphas:v.vertexColors===!0&&!!q.attributes.color&&q.attributes.color.itemSize===4,pointsUvs:k.isPoints===!0&&!!q.attributes.uv&&(Ht||ut),fog:!!H,useFog:v.fog===!0,fogExp2:!!H&&H.isFogExp2,flatShading:v.flatShading===!0&&v.wireframe===!1,sizeAttenuation:v.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:ft,skinning:k.isSkinnedMesh===!0,morphTargets:q.morphAttributes.position!==void 0,morphNormals:q.morphAttributes.normal!==void 0,morphColors:q.morphAttributes.color!==void 0,morphTargetsCount:bt,morphTextureStride:kt,numDirLights:y.directional.length,numPointLights:y.point.length,numSpotLights:y.spot.length,numSpotLightMaps:y.spotLightMap.length,numRectAreaLights:y.rectArea.length,numHemiLights:y.hemi.length,numDirLightShadows:y.directionalShadowMap.length,numPointLightShadows:y.pointShadowMap.length,numSpotLightShadows:y.spotShadowMap.length,numSpotLightShadowsWithMaps:y.numSpotLightShadowsWithMaps,numLightProbes:y.numLightProbes,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:v.dithering,shadowMapEnabled:i.shadowMap.enabled&&R.length>0,shadowMapType:i.shadowMap.type,toneMapping:Dt,decodeVideoTexture:Ht&&v.map.isVideoTexture===!0&&Gt.getTransfer(v.map.colorSpace)===Yt,decodeVideoTextureEmissive:_t&&v.emissiveMap.isVideoTexture===!0&&Gt.getTransfer(v.emissiveMap.colorSpace)===Yt,premultipliedAlpha:v.premultipliedAlpha,doubleSided:v.side===Ye,flipSided:v.side===Re,useDepthPacking:v.depthPacking>=0,depthPacking:v.depthPacking||0,index0AttributeName:v.index0AttributeName,extensionClipCullDistance:mt&&v.extensions.clipCullDistance===!0&&n.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(mt&&v.extensions.multiDraw===!0||St)&&n.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:n.has("KHR_parallel_shader_compile"),customProgramCacheKey:v.customProgramCacheKey()};return jt.vertexUv1s=c.has(1),jt.vertexUv2s=c.has(2),jt.vertexUv3s=c.has(3),c.clear(),jt}function u(v){let y=[];if(v.shaderID?y.push(v.shaderID):(y.push(v.customVertexShaderID),y.push(v.customFragmentShaderID)),v.defines!==void 0)for(let R in v.defines)y.push(R),y.push(v.defines[R]);return v.isRawShaderMaterial===!1&&(T(y,v),E(y,v),y.push(i.outputColorSpace)),y.push(v.customProgramCacheKey),y.join()}function T(v,y){v.push(y.precision),v.push(y.outputColorSpace),v.push(y.envMapMode),v.push(y.envMapCubeUVHeight),v.push(y.mapUv),v.push(y.alphaMapUv),v.push(y.lightMapUv),v.push(y.aoMapUv),v.push(y.bumpMapUv),v.push(y.normalMapUv),v.push(y.displacementMapUv),v.push(y.emissiveMapUv),v.push(y.metalnessMapUv),v.push(y.roughnessMapUv),v.push(y.anisotropyMapUv),v.push(y.clearcoatMapUv),v.push(y.clearcoatNormalMapUv),v.push(y.clearcoatRoughnessMapUv),v.push(y.iridescenceMapUv),v.push(y.iridescenceThicknessMapUv),v.push(y.sheenColorMapUv),v.push(y.sheenRoughnessMapUv),v.push(y.specularMapUv),v.push(y.specularColorMapUv),v.push(y.specularIntensityMapUv),v.push(y.transmissionMapUv),v.push(y.thicknessMapUv),v.push(y.combine),v.push(y.fogExp2),v.push(y.sizeAttenuation),v.push(y.morphTargetsCount),v.push(y.morphAttributeCount),v.push(y.numDirLights),v.push(y.numPointLights),v.push(y.numSpotLights),v.push(y.numSpotLightMaps),v.push(y.numHemiLights),v.push(y.numRectAreaLights),v.push(y.numDirLightShadows),v.push(y.numPointLightShadows),v.push(y.numSpotLightShadows),v.push(y.numSpotLightShadowsWithMaps),v.push(y.numLightProbes),v.push(y.shadowMapType),v.push(y.toneMapping),v.push(y.numClippingPlanes),v.push(y.numClipIntersection),v.push(y.depthPacking)}function E(v,y){o.disableAll(),y.supportsVertexTextures&&o.enable(0),y.instancing&&o.enable(1),y.instancingColor&&o.enable(2),y.instancingMorph&&o.enable(3),y.matcap&&o.enable(4),y.envMap&&o.enable(5),y.normalMapObjectSpace&&o.enable(6),y.normalMapTangentSpace&&o.enable(7),y.clearcoat&&o.enable(8),y.iridescence&&o.enable(9),y.alphaTest&&o.enable(10),y.vertexColors&&o.enable(11),y.vertexAlphas&&o.enable(12),y.vertexUv1s&&o.enable(13),y.vertexUv2s&&o.enable(14),y.vertexUv3s&&o.enable(15),y.vertexTangents&&o.enable(16),y.anisotropy&&o.enable(17),y.alphaHash&&o.enable(18),y.batching&&o.enable(19),y.dispersion&&o.enable(20),y.batchingColor&&o.enable(21),y.gradientMap&&o.enable(22),v.push(o.mask),o.disableAll(),y.fog&&o.enable(0),y.useFog&&o.enable(1),y.flatShading&&o.enable(2),y.logarithmicDepthBuffer&&o.enable(3),y.reversedDepthBuffer&&o.enable(4),y.skinning&&o.enable(5),y.morphTargets&&o.enable(6),y.morphNormals&&o.enable(7),y.morphColors&&o.enable(8),y.premultipliedAlpha&&o.enable(9),y.shadowMapEnabled&&o.enable(10),y.doubleSided&&o.enable(11),y.flipSided&&o.enable(12),y.useDepthPacking&&o.enable(13),y.dithering&&o.enable(14),y.transmission&&o.enable(15),y.sheen&&o.enable(16),y.opaque&&o.enable(17),y.pointsUvs&&o.enable(18),y.decodeVideoTexture&&o.enable(19),y.decodeVideoTextureEmissive&&o.enable(20),y.alphaToCoverage&&o.enable(21),v.push(o.mask)}function S(v){let y=_[v.type],R;if(y){let F=dn[y];R=mc.clone(F.uniforms)}else R=v.uniforms;return R}function C(v,y){let R;for(let F=0,k=h.length;F0?n.push(u):m.transparent===!0?s.push(u):e.push(u)}function l(d,f,m,_,M,p){let u=a(d,f,m,_,M,p);m.transmission>0?n.unshift(u):m.transparent===!0?s.unshift(u):e.unshift(u)}function c(d,f){e.length>1&&e.sort(d||pm),n.length>1&&n.sort(f||Oc),s.length>1&&s.sort(f||Oc)}function h(){for(let d=t,f=i.length;d=r.length?(a=new Bc,r.push(a)):a=r[s],a}function e(){i=new WeakMap}return{get:t,dispose:e}}function gm(){let i={};return{get:function(t){if(i[t.id]!==void 0)return i[t.id];let e;switch(t.type){case"DirectionalLight":e={direction:new N,color:new zt};break;case"SpotLight":e={position:new N,direction:new N,color:new zt,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":e={position:new N,color:new zt,distance:0,decay:0};break;case"HemisphereLight":e={direction:new N,skyColor:new zt,groundColor:new zt};break;case"RectAreaLight":e={color:new zt,position:new N,halfWidth:new N,halfHeight:new N};break}return i[t.id]=e,e}}}function _m(){let i={};return{get:function(t){if(i[t.id]!==void 0)return i[t.id];let e;switch(t.type){case"DirectionalLight":e={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Pt};break;case"SpotLight":e={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Pt};break;case"PointLight":e={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Pt,shadowCameraNear:1,shadowCameraFar:1e3};break}return i[t.id]=e,e}}}var xm=0;function ym(i,t){return(t.castShadow?2:0)-(i.castShadow?2:0)+(t.map?1:0)-(i.map?1:0)}function vm(i){let t=new gm,e=_m(),n={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let c=0;c<9;c++)n.probe.push(new N);let s=new N,r=new ue,a=new ue;function o(c){let h=0,d=0,f=0;for(let v=0;v<9;v++)n.probe[v].set(0,0,0);let m=0,_=0,M=0,p=0,u=0,T=0,E=0,S=0,C=0,A=0,P=0;c.sort(ym);for(let v=0,y=c.length;v0&&(i.has("OES_texture_float_linear")===!0?(n.rectAreaLTC1=st.LTC_FLOAT_1,n.rectAreaLTC2=st.LTC_FLOAT_2):(n.rectAreaLTC1=st.LTC_HALF_1,n.rectAreaLTC2=st.LTC_HALF_2)),n.ambient[0]=h,n.ambient[1]=d,n.ambient[2]=f;let U=n.hash;(U.directionalLength!==m||U.pointLength!==_||U.spotLength!==M||U.rectAreaLength!==p||U.hemiLength!==u||U.numDirectionalShadows!==T||U.numPointShadows!==E||U.numSpotShadows!==S||U.numSpotMaps!==C||U.numLightProbes!==P)&&(n.directional.length=m,n.spot.length=M,n.rectArea.length=p,n.point.length=_,n.hemi.length=u,n.directionalShadow.length=T,n.directionalShadowMap.length=T,n.pointShadow.length=E,n.pointShadowMap.length=E,n.spotShadow.length=S,n.spotShadowMap.length=S,n.directionalShadowMatrix.length=T,n.pointShadowMatrix.length=E,n.spotLightMatrix.length=S+C-A,n.spotLightMap.length=C,n.numSpotLightShadowsWithMaps=A,n.numLightProbes=P,U.directionalLength=m,U.pointLength=_,U.spotLength=M,U.rectAreaLength=p,U.hemiLength=u,U.numDirectionalShadows=T,U.numPointShadows=E,U.numSpotShadows=S,U.numSpotMaps=C,U.numLightProbes=P,n.version=xm++)}function l(c,h){let d=0,f=0,m=0,_=0,M=0,p=h.matrixWorldInverse;for(let u=0,T=c.length;u=a.length?(o=new zc(i),a.push(o)):o=a[r],o}function n(){t=new WeakMap}return{get:e,dispose:n}}var Sm=`void main() { + gl_Position = vec4( position, 1.0 ); +}`,bm=`uniform sampler2D shadow_pass; +uniform vec2 resolution; +uniform float radius; +#include +void main() { + const float samples = float( VSM_SAMPLES ); + float mean = 0.0; + float squared_mean = 0.0; + float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); + float uvStart = samples <= 1.0 ? 0.0 : - 1.0; + for ( float i = 0.0; i < samples; i ++ ) { + float uvOffset = uvStart + i * uvStride; + #ifdef HORIZONTAL_PASS + vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) ); + mean += distribution.x; + squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; + #else + float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) ); + mean += depth; + squared_mean += depth * depth; + #endif + } + mean = mean / samples; + squared_mean = squared_mean / samples; + float std_dev = sqrt( squared_mean - mean * mean ); + gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) ); +}`;function Em(i,t,e){let n=new Fi,s=new Pt,r=new Pt,a=new le,o=new fr({depthPacking:ic}),l=new pr,c={},h=e.maxTextureSize,d={[Sn]:Re,[Re]:Sn,[Ye]:Ye},f=new rn({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Pt},radius:{value:4}},vertexShader:Sm,fragmentShader:bm}),m=f.clone();m.defines.HORIZONTAL_PASS=1;let _=new ze;_.setAttribute("position",new be(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let M=new Pe(_,f),p=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=ao;let u=this.type;this.render=function(A,P,U){if(p.enabled===!1||p.autoUpdate===!1&&p.needsUpdate===!1||A.length===0)return;let v=i.getRenderTarget(),y=i.getActiveCubeFace(),R=i.getActiveMipmapLevel(),F=i.state;F.setBlending(En),F.buffers.depth.getReversed()===!0?F.buffers.color.setClear(0,0,0,0):F.buffers.color.setClear(1,1,1,1),F.buffers.depth.setTest(!0),F.setScissorTest(!1);let k=u!==hn&&this.type===hn,H=u===hn&&this.type!==hn;for(let q=0,W=A.length;qh||s.y>h)&&(s.x>h&&(r.x=Math.floor(h/rt.x),s.x=r.x*rt.x,V.mapSize.x=r.x),s.y>h&&(r.y=Math.floor(h/rt.y),s.y=r.y*rt.y,V.mapSize.y=r.y)),V.map===null||k===!0||H===!0){let bt=this.type!==hn?{minFilter:Xe,magFilter:Xe}:{};V.map!==null&&V.map.dispose(),V.map=new cn(s.x,s.y,bt),V.map.texture.name=et.name+".shadowMap",V.camera.updateProjectionMatrix()}i.setRenderTarget(V.map),i.clear();let ct=V.getViewportCount();for(let bt=0;bt0||P.map&&P.alphaTest>0||P.alphaToCoverage===!0){let F=y.uuid,k=P.uuid,H=c[F];H===void 0&&(H={},c[F]=H);let q=H[k];q===void 0&&(q=y.clone(),H[k]=q,P.addEventListener("dispose",C)),y=q}if(y.visible=P.visible,y.wireframe=P.wireframe,v===hn?y.side=P.shadowSide!==null?P.shadowSide:P.side:y.side=P.shadowSide!==null?P.shadowSide:d[P.side],y.alphaMap=P.alphaMap,y.alphaTest=P.alphaToCoverage===!0?.5:P.alphaTest,y.map=P.map,y.clipShadows=P.clipShadows,y.clippingPlanes=P.clippingPlanes,y.clipIntersection=P.clipIntersection,y.displacementMap=P.displacementMap,y.displacementScale=P.displacementScale,y.displacementBias=P.displacementBias,y.wireframeLinewidth=P.wireframeLinewidth,y.linewidth=P.linewidth,U.isPointLight===!0&&y.isMeshDistanceMaterial===!0){let F=i.properties.get(y);F.light=U}return y}function S(A,P,U,v,y){if(A.visible===!1)return;if(A.layers.test(P.layers)&&(A.isMesh||A.isLine||A.isPoints)&&(A.castShadow||A.receiveShadow&&y===hn)&&(!A.frustumCulled||n.intersectsObject(A))){A.modelViewMatrix.multiplyMatrices(U.matrixWorldInverse,A.matrixWorld);let k=t.update(A),H=A.material;if(Array.isArray(H)){let q=k.groups;for(let W=0,et=q.length;W=1):V.indexOf("OpenGL ES")!==-1&&(et=parseFloat(/^OpenGL ES (\d)/.exec(V)[1]),W=et>=2);let rt=null,ct={},bt=i.getParameter(i.SCISSOR_BOX),kt=i.getParameter(i.VIEWPORT),Kt=new le().fromArray(bt),ie=new le().fromArray(kt);function Xt(I,tt,it,ut){let K=new Uint8Array(4),Z=i.createTexture();i.bindTexture(I,Z),i.texParameteri(I,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(I,i.TEXTURE_MAG_FILTER,i.NEAREST);for(let mt=0;mt"u"?!1:/OculusBrowser/g.test(navigator.userAgent),c=new Pt,h=new WeakMap,d,f=new WeakMap,m=!1;try{m=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function _(b,g){return m?new OffscreenCanvas(b,g):ls("canvas")}function M(b,g,O){let X=1,J=he(b);if((J.width>O||J.height>O)&&(X=O/Math.max(J.width,J.height)),X<1)if(typeof HTMLImageElement<"u"&&b instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&b instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&b instanceof ImageBitmap||typeof VideoFrame<"u"&&b instanceof VideoFrame){let G=Math.floor(X*J.width),Mt=Math.floor(X*J.height);d===void 0&&(d=_(G,Mt));let nt=g?_(G,Mt):d;return nt.width=G,nt.height=Mt,nt.getContext("2d").drawImage(b,0,0,G,Mt),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+J.width+"x"+J.height+") to ("+G+"x"+Mt+")."),nt}else return"data"in b&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+J.width+"x"+J.height+")."),b;return b}function p(b){return b.generateMipmaps}function u(b){i.generateMipmap(b)}function T(b){return b.isWebGLCubeRenderTarget?i.TEXTURE_CUBE_MAP:b.isWebGL3DRenderTarget?i.TEXTURE_3D:b.isWebGLArrayRenderTarget||b.isCompressedArrayTexture?i.TEXTURE_2D_ARRAY:i.TEXTURE_2D}function E(b,g,O,X,J=!1){if(b!==null){if(i[b]!==void 0)return i[b];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+b+"'")}let G=g;if(g===i.RED&&(O===i.FLOAT&&(G=i.R32F),O===i.HALF_FLOAT&&(G=i.R16F),O===i.UNSIGNED_BYTE&&(G=i.R8)),g===i.RED_INTEGER&&(O===i.UNSIGNED_BYTE&&(G=i.R8UI),O===i.UNSIGNED_SHORT&&(G=i.R16UI),O===i.UNSIGNED_INT&&(G=i.R32UI),O===i.BYTE&&(G=i.R8I),O===i.SHORT&&(G=i.R16I),O===i.INT&&(G=i.R32I)),g===i.RG&&(O===i.FLOAT&&(G=i.RG32F),O===i.HALF_FLOAT&&(G=i.RG16F),O===i.UNSIGNED_BYTE&&(G=i.RG8)),g===i.RG_INTEGER&&(O===i.UNSIGNED_BYTE&&(G=i.RG8UI),O===i.UNSIGNED_SHORT&&(G=i.RG16UI),O===i.UNSIGNED_INT&&(G=i.RG32UI),O===i.BYTE&&(G=i.RG8I),O===i.SHORT&&(G=i.RG16I),O===i.INT&&(G=i.RG32I)),g===i.RGB_INTEGER&&(O===i.UNSIGNED_BYTE&&(G=i.RGB8UI),O===i.UNSIGNED_SHORT&&(G=i.RGB16UI),O===i.UNSIGNED_INT&&(G=i.RGB32UI),O===i.BYTE&&(G=i.RGB8I),O===i.SHORT&&(G=i.RGB16I),O===i.INT&&(G=i.RGB32I)),g===i.RGBA_INTEGER&&(O===i.UNSIGNED_BYTE&&(G=i.RGBA8UI),O===i.UNSIGNED_SHORT&&(G=i.RGBA16UI),O===i.UNSIGNED_INT&&(G=i.RGBA32UI),O===i.BYTE&&(G=i.RGBA8I),O===i.SHORT&&(G=i.RGBA16I),O===i.INT&&(G=i.RGBA32I)),g===i.RGB&&(O===i.UNSIGNED_INT_5_9_9_9_REV&&(G=i.RGB9_E5),O===i.UNSIGNED_INT_10F_11F_11F_REV&&(G=i.R11F_G11F_B10F)),g===i.RGBA){let Mt=J?as:Gt.getTransfer(X);O===i.FLOAT&&(G=i.RGBA32F),O===i.HALF_FLOAT&&(G=i.RGBA16F),O===i.UNSIGNED_BYTE&&(G=Mt===Yt?i.SRGB8_ALPHA8:i.RGBA8),O===i.UNSIGNED_SHORT_4_4_4_4&&(G=i.RGBA4),O===i.UNSIGNED_SHORT_5_5_5_1&&(G=i.RGB5_A1)}return(G===i.R16F||G===i.R32F||G===i.RG16F||G===i.RG32F||G===i.RGBA16F||G===i.RGBA32F)&&t.get("EXT_color_buffer_float"),G}function S(b,g){let O;return b?g===null||g===qn||g===Gi?O=i.DEPTH24_STENCIL8:g===un?O=i.DEPTH32F_STENCIL8:g===Vi&&(O=i.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):g===null||g===qn||g===Gi?O=i.DEPTH_COMPONENT24:g===un?O=i.DEPTH_COMPONENT32F:g===Vi&&(O=i.DEPTH_COMPONENT16),O}function C(b,g){return p(b)===!0||b.isFramebufferTexture&&b.minFilter!==Xe&&b.minFilter!==nn?Math.log2(Math.max(g.width,g.height))+1:b.mipmaps!==void 0&&b.mipmaps.length>0?b.mipmaps.length:b.isCompressedTexture&&Array.isArray(b.image)?g.mipmaps.length:1}function A(b){let g=b.target;g.removeEventListener("dispose",A),U(g),g.isVideoTexture&&h.delete(g)}function P(b){let g=b.target;g.removeEventListener("dispose",P),y(g)}function U(b){let g=n.get(b);if(g.__webglInit===void 0)return;let O=b.source,X=f.get(O);if(X){let J=X[g.__cacheKey];J.usedTimes--,J.usedTimes===0&&v(b),Object.keys(X).length===0&&f.delete(O)}n.remove(b)}function v(b){let g=n.get(b);i.deleteTexture(g.__webglTexture);let O=b.source,X=f.get(O);delete X[g.__cacheKey],a.memory.textures--}function y(b){let g=n.get(b);if(b.depthTexture&&(b.depthTexture.dispose(),n.remove(b.depthTexture)),b.isWebGLCubeRenderTarget)for(let X=0;X<6;X++){if(Array.isArray(g.__webglFramebuffer[X]))for(let J=0;J=s.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+b+" texture units while this GPU supports only "+s.maxTextures),R+=1,b}function H(b){let g=[];return g.push(b.wrapS),g.push(b.wrapT),g.push(b.wrapR||0),g.push(b.magFilter),g.push(b.minFilter),g.push(b.anisotropy),g.push(b.internalFormat),g.push(b.format),g.push(b.type),g.push(b.generateMipmaps),g.push(b.premultiplyAlpha),g.push(b.flipY),g.push(b.unpackAlignment),g.push(b.colorSpace),g.join()}function q(b,g){let O=n.get(b);if(b.isVideoTexture&&Ft(b),b.isRenderTargetTexture===!1&&b.isExternalTexture!==!0&&b.version>0&&O.__version!==b.version){let X=b.image;if(X===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(X.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{Y(O,b,g);return}}else b.isExternalTexture&&(O.__webglTexture=b.sourceTexture?b.sourceTexture:null);e.bindTexture(i.TEXTURE_2D,O.__webglTexture,i.TEXTURE0+g)}function W(b,g){let O=n.get(b);if(b.isRenderTargetTexture===!1&&b.version>0&&O.__version!==b.version){Y(O,b,g);return}e.bindTexture(i.TEXTURE_2D_ARRAY,O.__webglTexture,i.TEXTURE0+g)}function et(b,g){let O=n.get(b);if(b.isRenderTargetTexture===!1&&b.version>0&&O.__version!==b.version){Y(O,b,g);return}e.bindTexture(i.TEXTURE_3D,O.__webglTexture,i.TEXTURE0+g)}function V(b,g){let O=n.get(b);if(b.version>0&&O.__version!==b.version){$(O,b,g);return}e.bindTexture(i.TEXTURE_CUBE_MAP,O.__webglTexture,i.TEXTURE0+g)}let rt={[rr]:i.REPEAT,[Fn]:i.CLAMP_TO_EDGE,[ar]:i.MIRRORED_REPEAT},ct={[Xe]:i.NEAREST,[ec]:i.NEAREST_MIPMAP_NEAREST,[As]:i.NEAREST_MIPMAP_LINEAR,[nn]:i.LINEAR,[Fr]:i.LINEAR_MIPMAP_NEAREST,[Xn]:i.LINEAR_MIPMAP_LINEAR},bt={[rc]:i.NEVER,[uc]:i.ALWAYS,[ac]:i.LESS,[So]:i.LEQUAL,[oc]:i.EQUAL,[hc]:i.GEQUAL,[lc]:i.GREATER,[cc]:i.NOTEQUAL};function kt(b,g){if(g.type===un&&t.has("OES_texture_float_linear")===!1&&(g.magFilter===nn||g.magFilter===Fr||g.magFilter===As||g.magFilter===Xn||g.minFilter===nn||g.minFilter===Fr||g.minFilter===As||g.minFilter===Xn)&&console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),i.texParameteri(b,i.TEXTURE_WRAP_S,rt[g.wrapS]),i.texParameteri(b,i.TEXTURE_WRAP_T,rt[g.wrapT]),(b===i.TEXTURE_3D||b===i.TEXTURE_2D_ARRAY)&&i.texParameteri(b,i.TEXTURE_WRAP_R,rt[g.wrapR]),i.texParameteri(b,i.TEXTURE_MAG_FILTER,ct[g.magFilter]),i.texParameteri(b,i.TEXTURE_MIN_FILTER,ct[g.minFilter]),g.compareFunction&&(i.texParameteri(b,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE),i.texParameteri(b,i.TEXTURE_COMPARE_FUNC,bt[g.compareFunction])),t.has("EXT_texture_filter_anisotropic")===!0){if(g.magFilter===Xe||g.minFilter!==As&&g.minFilter!==Xn||g.type===un&&t.has("OES_texture_float_linear")===!1)return;if(g.anisotropy>1||n.get(g).__currentAnisotropy){let O=t.get("EXT_texture_filter_anisotropic");i.texParameterf(b,O.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(g.anisotropy,s.getMaxAnisotropy())),n.get(g).__currentAnisotropy=g.anisotropy}}}function Kt(b,g){let O=!1;b.__webglInit===void 0&&(b.__webglInit=!0,g.addEventListener("dispose",A));let X=g.source,J=f.get(X);J===void 0&&(J={},f.set(X,J));let G=H(g);if(G!==b.__cacheKey){J[G]===void 0&&(J[G]={texture:i.createTexture(),usedTimes:0},a.memory.textures++,O=!0),J[G].usedTimes++;let Mt=J[b.__cacheKey];Mt!==void 0&&(J[b.__cacheKey].usedTimes--,Mt.usedTimes===0&&v(g)),b.__cacheKey=G,b.__webglTexture=J[G].texture}return O}function ie(b,g,O){return Math.floor(Math.floor(b/O)/g)}function Xt(b,g,O,X){let G=b.updateRanges;if(G.length===0)e.texSubImage2D(i.TEXTURE_2D,0,0,0,g.width,g.height,O,X,g.data);else{G.sort((Q,lt)=>Q.start-lt.start);let Mt=0;for(let Q=1;Q0){I&&tt&&e.texStorage2D(i.TEXTURE_2D,ut,vt,Nt[0].width,Nt[0].height);for(let K=0,Z=Nt.length;K0){let mt=Io(at.width,at.height,g.format,g.type);for(let Dt of g.layerUpdates){let jt=at.data.subarray(Dt*mt/at.data.BYTES_PER_ELEMENT,(Dt+1)*mt/at.data.BYTES_PER_ELEMENT);e.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,K,0,0,Dt,at.width,at.height,1,lt,jt)}g.clearLayerUpdates()}else e.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,K,0,0,0,at.width,at.height,Q.depth,lt,at.data)}else e.compressedTexImage3D(i.TEXTURE_2D_ARRAY,K,vt,at.width,at.height,Q.depth,0,at.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else I?it&&e.texSubImage3D(i.TEXTURE_2D_ARRAY,K,0,0,0,at.width,at.height,Q.depth,lt,At,at.data):e.texImage3D(i.TEXTURE_2D_ARRAY,K,vt,at.width,at.height,Q.depth,0,lt,At,at.data)}else{I&&tt&&e.texStorage2D(i.TEXTURE_2D,ut,vt,Nt[0].width,Nt[0].height);for(let K=0,Z=Nt.length;K0){let K=Io(Q.width,Q.height,g.format,g.type);for(let Z of g.layerUpdates){let mt=Q.data.subarray(Z*K/Q.data.BYTES_PER_ELEMENT,(Z+1)*K/Q.data.BYTES_PER_ELEMENT);e.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,Z,Q.width,Q.height,1,lt,At,mt)}g.clearLayerUpdates()}else e.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,0,Q.width,Q.height,Q.depth,lt,At,Q.data)}else e.texImage3D(i.TEXTURE_2D_ARRAY,0,vt,Q.width,Q.height,Q.depth,0,lt,At,Q.data);else if(g.isData3DTexture)I?(tt&&e.texStorage3D(i.TEXTURE_3D,ut,vt,Q.width,Q.height,Q.depth),it&&e.texSubImage3D(i.TEXTURE_3D,0,0,0,0,Q.width,Q.height,Q.depth,lt,At,Q.data)):e.texImage3D(i.TEXTURE_3D,0,vt,Q.width,Q.height,Q.depth,0,lt,At,Q.data);else if(g.isFramebufferTexture){if(tt)if(I)e.texStorage2D(i.TEXTURE_2D,ut,vt,Q.width,Q.height);else{let K=Q.width,Z=Q.height;for(let mt=0;mt>=1,Z>>=1}}else if(Nt.length>0){if(I&&tt){let K=he(Nt[0]);e.texStorage2D(i.TEXTURE_2D,ut,vt,K.width,K.height)}for(let K=0,Z=Nt.length;K0&&ut++;let Z=he(lt[0]);e.texStorage2D(i.TEXTURE_CUBE_MAP,ut,Nt,Z.width,Z.height)}for(let Z=0;Z<6;Z++)if(Q){I?it&&e.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Z,0,0,0,lt[Z].width,lt[Z].height,vt,at,lt[Z].data):e.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Z,0,Nt,lt[Z].width,lt[Z].height,0,vt,at,lt[Z].data);for(let mt=0;mt>G),At=Math.max(1,g.height>>G);J===i.TEXTURE_3D||J===i.TEXTURE_2D_ARRAY?e.texImage3D(J,G,xt,lt,At,g.depth,0,Mt,nt,null):e.texImage2D(J,G,xt,lt,At,0,Mt,nt,null)}e.bindFramebuffer(i.FRAMEBUFFER,b),_t(g)?o.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,X,J,Q.__webglTexture,0,re(g)):(J===i.TEXTURE_2D||J>=i.TEXTURE_CUBE_MAP_POSITIVE_X&&J<=i.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&i.framebufferTexture2D(i.FRAMEBUFFER,X,J,Q.__webglTexture,G),e.bindFramebuffer(i.FRAMEBUFFER,null)}function It(b,g,O){if(i.bindRenderbuffer(i.RENDERBUFFER,b),g.depthBuffer){let X=g.depthTexture,J=X&&X.isDepthTexture?X.type:null,G=S(g.stencilBuffer,J),Mt=g.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,nt=re(g);_t(g)?o.renderbufferStorageMultisampleEXT(i.RENDERBUFFER,nt,G,g.width,g.height):O?i.renderbufferStorageMultisample(i.RENDERBUFFER,nt,G,g.width,g.height):i.renderbufferStorage(i.RENDERBUFFER,G,g.width,g.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,Mt,i.RENDERBUFFER,b)}else{let X=g.textures;for(let J=0;J{delete g.__boundDepthTexture,delete g.__depthDisposeCallback,X.removeEventListener("dispose",J)};X.addEventListener("dispose",J),g.__depthDisposeCallback=J}g.__boundDepthTexture=X}if(b.depthTexture&&!g.__autoAllocateDepthBuffer){if(O)throw new Error("target.depthTexture not supported in Cube render targets");let X=b.texture.mipmaps;X&&X.length>0?St(g.__webglFramebuffer[0],b):St(g.__webglFramebuffer,b)}else if(O){g.__webglDepthbuffer=[];for(let X=0;X<6;X++)if(e.bindFramebuffer(i.FRAMEBUFFER,g.__webglFramebuffer[X]),g.__webglDepthbuffer[X]===void 0)g.__webglDepthbuffer[X]=i.createRenderbuffer(),It(g.__webglDepthbuffer[X],b,!1);else{let J=b.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,G=g.__webglDepthbuffer[X];i.bindRenderbuffer(i.RENDERBUFFER,G),i.framebufferRenderbuffer(i.FRAMEBUFFER,J,i.RENDERBUFFER,G)}}else{let X=b.texture.mipmaps;if(X&&X.length>0?e.bindFramebuffer(i.FRAMEBUFFER,g.__webglFramebuffer[0]):e.bindFramebuffer(i.FRAMEBUFFER,g.__webglFramebuffer),g.__webglDepthbuffer===void 0)g.__webglDepthbuffer=i.createRenderbuffer(),It(g.__webglDepthbuffer,b,!1);else{let J=b.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,G=g.__webglDepthbuffer;i.bindRenderbuffer(i.RENDERBUFFER,G),i.framebufferRenderbuffer(i.FRAMEBUFFER,J,i.RENDERBUFFER,G)}}e.bindFramebuffer(i.FRAMEBUFFER,null)}function ye(b,g,O){let X=n.get(b);g!==void 0&&ft(X.__webglFramebuffer,b,b.texture,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,0),O!==void 0&&Ht(b)}function w(b){let g=b.texture,O=n.get(b),X=n.get(g);b.addEventListener("dispose",P);let J=b.textures,G=b.isWebGLCubeRenderTarget===!0,Mt=J.length>1;if(Mt||(X.__webglTexture===void 0&&(X.__webglTexture=i.createTexture()),X.__version=g.version,a.memory.textures++),G){O.__webglFramebuffer=[];for(let nt=0;nt<6;nt++)if(g.mipmaps&&g.mipmaps.length>0){O.__webglFramebuffer[nt]=[];for(let xt=0;xt0){O.__webglFramebuffer=[];for(let nt=0;nt0&&_t(b)===!1){O.__webglMultisampledFramebuffer=i.createFramebuffer(),O.__webglColorRenderbuffer=[],e.bindFramebuffer(i.FRAMEBUFFER,O.__webglMultisampledFramebuffer);for(let nt=0;nt0)for(let xt=0;xt0)for(let xt=0;xt0){if(_t(b)===!1){let g=b.textures,O=b.width,X=b.height,J=i.COLOR_BUFFER_BIT,G=b.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,Mt=n.get(b),nt=g.length>1;if(nt)for(let yt=0;yt0?e.bindFramebuffer(i.DRAW_FRAMEBUFFER,Mt.__webglFramebuffer[0]):e.bindFramebuffer(i.DRAW_FRAMEBUFFER,Mt.__webglFramebuffer);for(let yt=0;yt0&&t.has("WEBGL_multisampled_render_to_texture")===!0&&g.__useRenderToTexture!==!1}function Ft(b){let g=a.render.frame;h.get(b)!==g&&(h.set(b,g),b.update())}function _e(b,g){let O=b.colorSpace,X=b.format,J=b.type;return b.isCompressedTexture===!0||b.isVideoTexture===!0||O!==bn&&O!==wn&&(Gt.getTransfer(O)===Yt?(X!==Ze||J!==an)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",O)),g}function he(b){return typeof HTMLImageElement<"u"&&b instanceof HTMLImageElement?(c.width=b.naturalWidth||b.width,c.height=b.naturalHeight||b.height):typeof VideoFrame<"u"&&b instanceof VideoFrame?(c.width=b.displayWidth,c.height=b.displayHeight):(c.width=b.width,c.height=b.height),c}this.allocateTextureUnit=k,this.resetTextureUnits=F,this.setTexture2D=q,this.setTexture2DArray=W,this.setTexture3D=et,this.setTextureCube=V,this.rebindTextures=ye,this.setupRenderTarget=w,this.updateRenderTargetMipmap=se,this.updateMultisampleRenderTarget=gt,this.setupDepthRenderbuffer=Ht,this.setupFrameBufferTexture=ft,this.useMultisampledRTT=_t}function Cm(i,t){function e(n,s=wn){let r,a=Gt.getTransfer(s);if(n===an)return i.UNSIGNED_BYTE;if(n===Br)return i.UNSIGNED_SHORT_4_4_4_4;if(n===zr)return i.UNSIGNED_SHORT_5_5_5_1;if(n===mo)return i.UNSIGNED_INT_5_9_9_9_REV;if(n===go)return i.UNSIGNED_INT_10F_11F_11F_REV;if(n===fo)return i.BYTE;if(n===po)return i.SHORT;if(n===Vi)return i.UNSIGNED_SHORT;if(n===Or)return i.INT;if(n===qn)return i.UNSIGNED_INT;if(n===un)return i.FLOAT;if(n===Hi)return i.HALF_FLOAT;if(n===_o)return i.ALPHA;if(n===xo)return i.RGB;if(n===Ze)return i.RGBA;if(n===Ri)return i.DEPTH_COMPONENT;if(n===Wi)return i.DEPTH_STENCIL;if(n===yo)return i.RED;if(n===kr)return i.RED_INTEGER;if(n===vo)return i.RG;if(n===Vr)return i.RG_INTEGER;if(n===Hr)return i.RGBA_INTEGER;if(n===Cs||n===Rs||n===Is||n===Ps)if(a===Yt)if(r=t.get("WEBGL_compressed_texture_s3tc_srgb"),r!==null){if(n===Cs)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===Rs)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===Is)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===Ps)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(r=t.get("WEBGL_compressed_texture_s3tc"),r!==null){if(n===Cs)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===Rs)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===Is)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===Ps)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(n===Gr||n===Wr||n===Xr||n===qr)if(r=t.get("WEBGL_compressed_texture_pvrtc"),r!==null){if(n===Gr)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===Wr)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===Xr)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===qr)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(n===Yr||n===Zr||n===Jr)if(r=t.get("WEBGL_compressed_texture_etc"),r!==null){if(n===Yr||n===Zr)return a===Yt?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(n===Jr)return a===Yt?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(n===$r||n===Kr||n===jr||n===Qr||n===ta||n===ea||n===na||n===ia||n===sa||n===ra||n===aa||n===oa||n===la||n===ca)if(r=t.get("WEBGL_compressed_texture_astc"),r!==null){if(n===$r)return a===Yt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===Kr)return a===Yt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===jr)return a===Yt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===Qr)return a===Yt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===ta)return a===Yt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===ea)return a===Yt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===na)return a===Yt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===ia)return a===Yt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===sa)return a===Yt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===ra)return a===Yt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===aa)return a===Yt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===oa)return a===Yt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===la)return a===Yt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===ca)return a===Yt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(n===ha||n===ua||n===da)if(r=t.get("EXT_texture_compression_bptc"),r!==null){if(n===ha)return a===Yt?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===ua)return r.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===da)return r.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(n===fa||n===pa||n===ma||n===ga)if(r=t.get("EXT_texture_compression_rgtc"),r!==null){if(n===fa)return r.COMPRESSED_RED_RGTC1_EXT;if(n===pa)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===ma)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===ga)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return n===Gi?i.UNSIGNED_INT_24_8:i[n]!==void 0?i[n]:null}return{convert:e}}var Rm=` +void main() { + + gl_Position = vec4( position, 1.0 ); + +}`,Im=` +uniform sampler2DArray depthColor; +uniform float depthWidth; +uniform float depthHeight; + +void main() { + + vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); + + if ( coord.x >= 1.0 ) { + + gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; + + } else { + + gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; + + } + +}`,Go=class{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(t,e){if(this.texture===null){let n=new xs(t.texture);(t.depthNear!==e.depthNear||t.depthFar!==e.depthFar)&&(this.depthNear=t.depthNear,this.depthFar=t.depthFar),this.texture=n}}getMesh(t){if(this.texture!==null&&this.mesh===null){let e=t.cameras[0].viewport,n=new rn({vertexShader:Rm,fragmentShader:Im,uniforms:{depthColor:{value:this.texture},depthWidth:{value:e.z},depthHeight:{value:e.w}}});this.mesh=new Pe(new ii(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},Wo=class extends ln{constructor(t,e){super();let n=this,s=null,r=1,a=null,o="local-floor",l=1,c=null,h=null,d=null,f=null,m=null,_=null,M=typeof XRWebGLBinding<"u",p=new Go,u={},T=e.getContextAttributes(),E=null,S=null,C=[],A=[],P=new Pt,U=null,v=new Se;v.viewport=new le;let y=new Se;y.viewport=new le;let R=[v,y],F=new Er,k=null,H=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(Y){let $=C[Y];return $===void 0&&($=new Ni,C[Y]=$),$.getTargetRaySpace()},this.getControllerGrip=function(Y){let $=C[Y];return $===void 0&&($=new Ni,C[Y]=$),$.getGripSpace()},this.getHand=function(Y){let $=C[Y];return $===void 0&&($=new Ni,C[Y]=$),$.getHandSpace()};function q(Y){let $=A.indexOf(Y.inputSource);if($===-1)return;let ft=C[$];ft!==void 0&&(ft.update(Y.inputSource,Y.frame,c||a),ft.dispatchEvent({type:Y.type,data:Y.inputSource}))}function W(){s.removeEventListener("select",q),s.removeEventListener("selectstart",q),s.removeEventListener("selectend",q),s.removeEventListener("squeeze",q),s.removeEventListener("squeezestart",q),s.removeEventListener("squeezeend",q),s.removeEventListener("end",W),s.removeEventListener("inputsourceschange",et);for(let Y=0;Y=0&&(A[It]=null,C[It].disconnect(ft))}for(let $=0;$=A.length){A.push(ft),It=Ht;break}else if(A[Ht]===null){A[Ht]=ft,It=Ht;break}if(It===-1)break}let St=C[It];St&&St.connect(ft)}}let V=new N,rt=new N;function ct(Y,$,ft){V.setFromMatrixPosition($.matrixWorld),rt.setFromMatrixPosition(ft.matrixWorld);let It=V.distanceTo(rt),St=$.projectionMatrix.elements,Ht=ft.projectionMatrix.elements,ye=St[14]/(St[10]-1),w=St[14]/(St[10]+1),se=(St[9]+1)/St[5],Lt=(St[9]-1)/St[5],Ct=(St[8]-1)/St[0],gt=(Ht[8]+1)/Ht[0],re=ye*Ct,_t=ye*gt,Ft=It/(-Ct+gt),_e=Ft*-Ct;if($.matrixWorld.decompose(Y.position,Y.quaternion,Y.scale),Y.translateX(_e),Y.translateZ(Ft),Y.matrixWorld.compose(Y.position,Y.quaternion,Y.scale),Y.matrixWorldInverse.copy(Y.matrixWorld).invert(),St[10]===-1)Y.projectionMatrix.copy($.projectionMatrix),Y.projectionMatrixInverse.copy($.projectionMatrixInverse);else{let he=ye+Ft,b=w+Ft,g=re-_e,O=_t+(It-_e),X=se*w/b*he,J=Lt*w/b*he;Y.projectionMatrix.makePerspective(g,O,X,J,he,b),Y.projectionMatrixInverse.copy(Y.projectionMatrix).invert()}}function bt(Y,$){$===null?Y.matrixWorld.copy(Y.matrix):Y.matrixWorld.multiplyMatrices($.matrixWorld,Y.matrix),Y.matrixWorldInverse.copy(Y.matrixWorld).invert()}this.updateCamera=function(Y){if(s===null)return;let $=Y.near,ft=Y.far;p.texture!==null&&(p.depthNear>0&&($=p.depthNear),p.depthFar>0&&(ft=p.depthFar)),F.near=y.near=v.near=$,F.far=y.far=v.far=ft,(k!==F.near||H!==F.far)&&(s.updateRenderState({depthNear:F.near,depthFar:F.far}),k=F.near,H=F.far),F.layers.mask=Y.layers.mask|6,v.layers.mask=F.layers.mask&3,y.layers.mask=F.layers.mask&5;let It=Y.parent,St=F.cameras;bt(F,It);for(let Ht=0;Ht0&&(p.alphaTest.value=u.alphaTest);let T=t.get(u),E=T.envMap,S=T.envMapRotation;E&&(p.envMap.value=E,ci.copy(S),ci.x*=-1,ci.y*=-1,ci.z*=-1,E.isCubeTexture&&E.isRenderTargetTexture===!1&&(ci.y*=-1,ci.z*=-1),p.envMapRotation.value.setFromMatrix4(Pm.makeRotationFromEuler(ci)),p.flipEnvMap.value=E.isCubeTexture&&E.isRenderTargetTexture===!1?-1:1,p.reflectivity.value=u.reflectivity,p.ior.value=u.ior,p.refractionRatio.value=u.refractionRatio),u.lightMap&&(p.lightMap.value=u.lightMap,p.lightMapIntensity.value=u.lightMapIntensity,e(u.lightMap,p.lightMapTransform)),u.aoMap&&(p.aoMap.value=u.aoMap,p.aoMapIntensity.value=u.aoMapIntensity,e(u.aoMap,p.aoMapTransform))}function a(p,u){p.diffuse.value.copy(u.color),p.opacity.value=u.opacity,u.map&&(p.map.value=u.map,e(u.map,p.mapTransform))}function o(p,u){p.dashSize.value=u.dashSize,p.totalSize.value=u.dashSize+u.gapSize,p.scale.value=u.scale}function l(p,u,T,E){p.diffuse.value.copy(u.color),p.opacity.value=u.opacity,p.size.value=u.size*T,p.scale.value=E*.5,u.map&&(p.map.value=u.map,e(u.map,p.uvTransform)),u.alphaMap&&(p.alphaMap.value=u.alphaMap,e(u.alphaMap,p.alphaMapTransform)),u.alphaTest>0&&(p.alphaTest.value=u.alphaTest)}function c(p,u){p.diffuse.value.copy(u.color),p.opacity.value=u.opacity,p.rotation.value=u.rotation,u.map&&(p.map.value=u.map,e(u.map,p.mapTransform)),u.alphaMap&&(p.alphaMap.value=u.alphaMap,e(u.alphaMap,p.alphaMapTransform)),u.alphaTest>0&&(p.alphaTest.value=u.alphaTest)}function h(p,u){p.specular.value.copy(u.specular),p.shininess.value=Math.max(u.shininess,1e-4)}function d(p,u){u.gradientMap&&(p.gradientMap.value=u.gradientMap)}function f(p,u){p.metalness.value=u.metalness,u.metalnessMap&&(p.metalnessMap.value=u.metalnessMap,e(u.metalnessMap,p.metalnessMapTransform)),p.roughness.value=u.roughness,u.roughnessMap&&(p.roughnessMap.value=u.roughnessMap,e(u.roughnessMap,p.roughnessMapTransform)),u.envMap&&(p.envMapIntensity.value=u.envMapIntensity)}function m(p,u,T){p.ior.value=u.ior,u.sheen>0&&(p.sheenColor.value.copy(u.sheenColor).multiplyScalar(u.sheen),p.sheenRoughness.value=u.sheenRoughness,u.sheenColorMap&&(p.sheenColorMap.value=u.sheenColorMap,e(u.sheenColorMap,p.sheenColorMapTransform)),u.sheenRoughnessMap&&(p.sheenRoughnessMap.value=u.sheenRoughnessMap,e(u.sheenRoughnessMap,p.sheenRoughnessMapTransform))),u.clearcoat>0&&(p.clearcoat.value=u.clearcoat,p.clearcoatRoughness.value=u.clearcoatRoughness,u.clearcoatMap&&(p.clearcoatMap.value=u.clearcoatMap,e(u.clearcoatMap,p.clearcoatMapTransform)),u.clearcoatRoughnessMap&&(p.clearcoatRoughnessMap.value=u.clearcoatRoughnessMap,e(u.clearcoatRoughnessMap,p.clearcoatRoughnessMapTransform)),u.clearcoatNormalMap&&(p.clearcoatNormalMap.value=u.clearcoatNormalMap,e(u.clearcoatNormalMap,p.clearcoatNormalMapTransform),p.clearcoatNormalScale.value.copy(u.clearcoatNormalScale),u.side===Re&&p.clearcoatNormalScale.value.negate())),u.dispersion>0&&(p.dispersion.value=u.dispersion),u.iridescence>0&&(p.iridescence.value=u.iridescence,p.iridescenceIOR.value=u.iridescenceIOR,p.iridescenceThicknessMinimum.value=u.iridescenceThicknessRange[0],p.iridescenceThicknessMaximum.value=u.iridescenceThicknessRange[1],u.iridescenceMap&&(p.iridescenceMap.value=u.iridescenceMap,e(u.iridescenceMap,p.iridescenceMapTransform)),u.iridescenceThicknessMap&&(p.iridescenceThicknessMap.value=u.iridescenceThicknessMap,e(u.iridescenceThicknessMap,p.iridescenceThicknessMapTransform))),u.transmission>0&&(p.transmission.value=u.transmission,p.transmissionSamplerMap.value=T.texture,p.transmissionSamplerSize.value.set(T.width,T.height),u.transmissionMap&&(p.transmissionMap.value=u.transmissionMap,e(u.transmissionMap,p.transmissionMapTransform)),p.thickness.value=u.thickness,u.thicknessMap&&(p.thicknessMap.value=u.thicknessMap,e(u.thicknessMap,p.thicknessMapTransform)),p.attenuationDistance.value=u.attenuationDistance,p.attenuationColor.value.copy(u.attenuationColor)),u.anisotropy>0&&(p.anisotropyVector.value.set(u.anisotropy*Math.cos(u.anisotropyRotation),u.anisotropy*Math.sin(u.anisotropyRotation)),u.anisotropyMap&&(p.anisotropyMap.value=u.anisotropyMap,e(u.anisotropyMap,p.anisotropyMapTransform))),p.specularIntensity.value=u.specularIntensity,p.specularColor.value.copy(u.specularColor),u.specularColorMap&&(p.specularColorMap.value=u.specularColorMap,e(u.specularColorMap,p.specularColorMapTransform)),u.specularIntensityMap&&(p.specularIntensityMap.value=u.specularIntensityMap,e(u.specularIntensityMap,p.specularIntensityMapTransform))}function _(p,u){u.matcap&&(p.matcap.value=u.matcap)}function M(p,u){let T=t.get(u).light;p.referencePosition.value.setFromMatrixPosition(T.matrixWorld),p.nearDistance.value=T.shadow.camera.near,p.farDistance.value=T.shadow.camera.far}return{refreshFogUniforms:n,refreshMaterialUniforms:s}}function Lm(i,t,e,n){let s={},r={},a=[],o=i.getParameter(i.MAX_UNIFORM_BUFFER_BINDINGS);function l(T,E){let S=E.program;n.uniformBlockBinding(T,S)}function c(T,E){let S=s[T.id];S===void 0&&(_(T),S=h(T),s[T.id]=S,T.addEventListener("dispose",p));let C=E.program;n.updateUBOMapping(T,C);let A=t.render.frame;r[T.id]!==A&&(f(T),r[T.id]=A)}function h(T){let E=d();T.__bindingPointIndex=E;let S=i.createBuffer(),C=T.__size,A=T.usage;return i.bindBuffer(i.UNIFORM_BUFFER,S),i.bufferData(i.UNIFORM_BUFFER,C,A),i.bindBuffer(i.UNIFORM_BUFFER,null),i.bindBufferBase(i.UNIFORM_BUFFER,E,S),S}function d(){for(let T=0;T0&&(S+=C-A),T.__size=S,T.__cache={},this}function M(T){let E={boundary:0,storage:0};return typeof T=="number"||typeof T=="boolean"?(E.boundary=4,E.storage=4):T.isVector2?(E.boundary=8,E.storage=8):T.isVector3||T.isColor?(E.boundary=16,E.storage=12):T.isVector4?(E.boundary=16,E.storage=16):T.isMatrix3?(E.boundary=48,E.storage=48):T.isMatrix4?(E.boundary=64,E.storage=64):T.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",T),E}function p(T){let E=T.target;E.removeEventListener("dispose",p);let S=a.indexOf(E.__bindingPointIndex);a.splice(S,1),i.deleteBuffer(s[E.id]),delete s[E.id],delete r[E.id]}function u(){for(let T in s)i.deleteBuffer(s[T]);a=[],s={},r={}}return{bind:l,update:c,dispose:u}}var Ma=class{constructor(t={}){let{canvas:e=dc(),context:n=null,depth:s=!0,stencil:r=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:c=!1,powerPreference:h="default",failIfMajorPerformanceCaveat:d=!1,reversedDepthBuffer:f=!1}=t;this.isWebGLRenderer=!0;let m;if(n!==null){if(typeof WebGLRenderingContext<"u"&&n instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");m=n.getContextAttributes().alpha}else m=a;let _=new Uint32Array(4),M=new Int32Array(4),p=null,u=null,T=[],E=[];this.domElement=e,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=Tn,this.toneMappingExposure=1,this.transmissionResolutionScale=1;let S=this,C=!1;this._outputColorSpace=Ce;let A=0,P=0,U=null,v=-1,y=null,R=new le,F=new le,k=null,H=new zt(0),q=0,W=e.width,et=e.height,V=1,rt=null,ct=null,bt=new le(0,0,W,et),kt=new le(0,0,W,et),Kt=!1,ie=new Fi,Xt=!1,Y=!1,$=new ue,ft=new N,It=new le,St={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},Ht=!1;function ye(){return U===null?V:1}let w=n;function se(x,D){return e.getContext(x,D)}try{let x={alpha:!0,depth:s,stencil:r,antialias:o,premultipliedAlpha:l,preserveDrawingBuffer:c,powerPreference:h,failIfMajorPerformanceCaveat:d};if("setAttribute"in e&&e.setAttribute("data-engine",`three.js r${"180"}`),e.addEventListener("webglcontextlost",it,!1),e.addEventListener("webglcontextrestored",ut,!1),e.addEventListener("webglcontextcreationerror",K,!1),w===null){let D="webgl2";if(w=se(D,x),w===null)throw se(D)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(x){throw console.error("THREE.WebGLRenderer: "+x.message),x}let Lt,Ct,gt,re,_t,Ft,_e,he,b,g,O,X,J,G,Mt,nt,xt,yt,Q,lt,At,vt,at,Nt;function I(){Lt=new Kf(w),Lt.init(),vt=new Cm(w,Lt),Ct=new Wf(w,Lt,t,vt),gt=new wm(w,Lt),Ct.reversedDepthBuffer&&f&>.buffers.depth.setReversed(!0),re=new tp(w),_t=new fm,Ft=new Am(w,Lt,gt,_t,Ct,vt,re),_e=new qf(S),he=new $f(S),b=new ru(w),at=new Hf(w,b),g=new jf(w,b,re,at),O=new np(w,g,b,re),Q=new ep(w,Ct,Ft),nt=new Xf(_t),X=new dm(S,_e,he,Lt,Ct,at,nt),J=new Dm(S,_t),G=new mm,Mt=new Mm(Lt),yt=new Vf(S,_e,he,gt,O,m,l),xt=new Em(S,O,Ct),Nt=new Lm(w,re,Ct,gt),lt=new Gf(w,Lt,re),At=new Qf(w,Lt,re),re.programs=X.programs,S.capabilities=Ct,S.extensions=Lt,S.properties=_t,S.renderLists=G,S.shadowMap=xt,S.state=gt,S.info=re}I();let tt=new Wo(S,w);this.xr=tt,this.getContext=function(){return w},this.getContextAttributes=function(){return w.getContextAttributes()},this.forceContextLoss=function(){let x=Lt.get("WEBGL_lose_context");x&&x.loseContext()},this.forceContextRestore=function(){let x=Lt.get("WEBGL_lose_context");x&&x.restoreContext()},this.getPixelRatio=function(){return V},this.setPixelRatio=function(x){x!==void 0&&(V=x,this.setSize(W,et,!1))},this.getSize=function(x){return x.set(W,et)},this.setSize=function(x,D,B=!0){if(tt.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}W=x,et=D,e.width=Math.floor(x*V),e.height=Math.floor(D*V),B===!0&&(e.style.width=x+"px",e.style.height=D+"px"),this.setViewport(0,0,x,D)},this.getDrawingBufferSize=function(x){return x.set(W*V,et*V).floor()},this.setDrawingBufferSize=function(x,D,B){W=x,et=D,V=B,e.width=Math.floor(x*B),e.height=Math.floor(D*B),this.setViewport(0,0,x,D)},this.getCurrentViewport=function(x){return x.copy(R)},this.getViewport=function(x){return x.copy(bt)},this.setViewport=function(x,D,B,z){x.isVector4?bt.set(x.x,x.y,x.z,x.w):bt.set(x,D,B,z),gt.viewport(R.copy(bt).multiplyScalar(V).round())},this.getScissor=function(x){return x.copy(kt)},this.setScissor=function(x,D,B,z){x.isVector4?kt.set(x.x,x.y,x.z,x.w):kt.set(x,D,B,z),gt.scissor(F.copy(kt).multiplyScalar(V).round())},this.getScissorTest=function(){return Kt},this.setScissorTest=function(x){gt.setScissorTest(Kt=x)},this.setOpaqueSort=function(x){rt=x},this.setTransparentSort=function(x){ct=x},this.getClearColor=function(x){return x.copy(yt.getClearColor())},this.setClearColor=function(){yt.setClearColor(...arguments)},this.getClearAlpha=function(){return yt.getClearAlpha()},this.setClearAlpha=function(){yt.setClearAlpha(...arguments)},this.clear=function(x=!0,D=!0,B=!0){let z=0;if(x){let L=!1;if(U!==null){let j=U.texture.format;L=j===Hr||j===Vr||j===kr}if(L){let j=U.texture.type,ot=j===an||j===qn||j===Vi||j===Gi||j===Br||j===zr,pt=yt.getClearColor(),ht=yt.getClearAlpha(),wt=pt.r,Rt=pt.g,Et=pt.b;ot?(_[0]=wt,_[1]=Rt,_[2]=Et,_[3]=ht,w.clearBufferuiv(w.COLOR,0,_)):(M[0]=wt,M[1]=Rt,M[2]=Et,M[3]=ht,w.clearBufferiv(w.COLOR,0,M))}else z|=w.COLOR_BUFFER_BIT}D&&(z|=w.DEPTH_BUFFER_BIT),B&&(z|=w.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),w.clear(z)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){e.removeEventListener("webglcontextlost",it,!1),e.removeEventListener("webglcontextrestored",ut,!1),e.removeEventListener("webglcontextcreationerror",K,!1),yt.dispose(),G.dispose(),Mt.dispose(),_t.dispose(),_e.dispose(),he.dispose(),O.dispose(),at.dispose(),Nt.dispose(),X.dispose(),tt.dispose(),tt.removeEventListener("sessionstart",on),tt.removeEventListener("sessionend",el),Zn.stop()};function it(x){x.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),C=!0}function ut(){console.log("THREE.WebGLRenderer: Context Restored."),C=!1;let x=re.autoReset,D=xt.enabled,B=xt.autoUpdate,z=xt.needsUpdate,L=xt.type;I(),re.autoReset=x,xt.enabled=D,xt.autoUpdate=B,xt.needsUpdate=z,xt.type=L}function K(x){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",x.statusMessage)}function Z(x){let D=x.target;D.removeEventListener("dispose",Z),mt(D)}function mt(x){Dt(x),_t.remove(x)}function Dt(x){let D=_t.get(x).programs;D!==void 0&&(D.forEach(function(B){X.releaseProgram(B)}),x.isShaderMaterial&&X.releaseShaderCache(x))}this.renderBufferDirect=function(x,D,B,z,L,j){D===null&&(D=St);let ot=L.isMesh&&L.matrixWorld.determinant()<0,pt=rh(x,D,B,z,L);gt.setMaterial(z,ot);let ht=B.index,wt=1;if(z.wireframe===!0){if(ht=g.getWireframeAttribute(B),ht===void 0)return;wt=2}let Rt=B.drawRange,Et=B.attributes.position,Vt=Rt.start*wt,Zt=(Rt.start+Rt.count)*wt;j!==null&&(Vt=Math.max(Vt,j.start*wt),Zt=Math.min(Zt,(j.start+j.count)*wt)),ht!==null?(Vt=Math.max(Vt,0),Zt=Math.min(Zt,ht.count)):Et!=null&&(Vt=Math.max(Vt,0),Zt=Math.min(Zt,Et.count));let ce=Zt-Vt;if(ce<0||ce===1/0)return;at.setup(L,z,pt,B,ht);let te,$t=lt;if(ht!==null&&(te=b.get(ht),$t=At,$t.setIndex(te)),L.isMesh)z.wireframe===!0?(gt.setLineWidth(z.wireframeLinewidth*ye()),$t.setMode(w.LINES)):$t.setMode(w.TRIANGLES);else if(L.isLine){let Tt=z.linewidth;Tt===void 0&&(Tt=1),gt.setLineWidth(Tt*ye()),L.isLineSegments?$t.setMode(w.LINES):L.isLineLoop?$t.setMode(w.LINE_LOOP):$t.setMode(w.LINE_STRIP)}else L.isPoints?$t.setMode(w.POINTS):L.isSprite&&$t.setMode(w.TRIANGLES);if(L.isBatchedMesh)if(L._multiDrawInstances!==null)Pi("THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),$t.renderMultiDrawInstances(L._multiDrawStarts,L._multiDrawCounts,L._multiDrawCount,L._multiDrawInstances);else if(Lt.get("WEBGL_multi_draw"))$t.renderMultiDraw(L._multiDrawStarts,L._multiDrawCounts,L._multiDrawCount);else{let Tt=L._multiDrawStarts,ae=L._multiDrawCounts,Wt=L._multiDrawCount,Ue=ht?b.get(ht).bytesPerElement:1,pi=_t.get(z).currentProgram.getUniforms();for(let Ne=0;Ne{function j(){if(z.forEach(function(ot){_t.get(ot).currentProgram.isReady()&&z.delete(ot)}),z.size===0){L(x);return}setTimeout(j,10)}Lt.get("KHR_parallel_shader_compile")!==null?j():setTimeout(j,10)})};let qt=null;function pn(x){qt&&qt(x)}function on(){Zn.stop()}function el(){Zn.start()}let Zn=new kc;Zn.setAnimationLoop(pn),typeof self<"u"&&Zn.setContext(self),this.setAnimationLoop=function(x){qt=x,tt.setAnimationLoop(x),x===null?Zn.stop():Zn.start()},tt.addEventListener("sessionstart",on),tt.addEventListener("sessionend",el),this.render=function(x,D){if(D!==void 0&&D.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(C===!0)return;if(x.matrixWorldAutoUpdate===!0&&x.updateMatrixWorld(),D.parent===null&&D.matrixWorldAutoUpdate===!0&&D.updateMatrixWorld(),tt.enabled===!0&&tt.isPresenting===!0&&(tt.cameraAutoUpdate===!0&&tt.updateCamera(D),D=tt.getCamera()),x.isScene===!0&&x.onBeforeRender(S,x,D,U),u=Mt.get(x,E.length),u.init(D),E.push(u),$.multiplyMatrices(D.projectionMatrix,D.matrixWorldInverse),ie.setFromProjectionMatrix($,en,D.reversedDepth),Y=this.localClippingEnabled,Xt=nt.init(this.clippingPlanes,Y),p=G.get(x,T.length),p.init(),T.push(p),tt.enabled===!0&&tt.isPresenting===!0){let j=S.xr.getDepthSensingMesh();j!==null&&Aa(j,D,-1/0,S.sortObjects)}Aa(x,D,0,S.sortObjects),p.finish(),S.sortObjects===!0&&p.sort(rt,ct),Ht=tt.enabled===!1||tt.isPresenting===!1||tt.hasDepthSensing()===!1,Ht&&yt.addToRenderList(p,x),this.info.render.frame++,Xt===!0&&nt.beginShadows();let B=u.state.shadowsArray;xt.render(B,x,D),Xt===!0&&nt.endShadows(),this.info.autoReset===!0&&this.info.reset();let z=p.opaque,L=p.transmissive;if(u.setupLights(),D.isArrayCamera){let j=D.cameras;if(L.length>0)for(let ot=0,pt=j.length;ot0&&il(z,L,x,D),Ht&&yt.render(x),nl(p,x,D);U!==null&&P===0&&(Ft.updateMultisampleRenderTarget(U),Ft.updateRenderTargetMipmap(U)),x.isScene===!0&&x.onAfterRender(S,x,D),at.resetDefaultState(),v=-1,y=null,E.pop(),E.length>0?(u=E[E.length-1],Xt===!0&&nt.setGlobalState(S.clippingPlanes,u.state.camera)):u=null,T.pop(),T.length>0?p=T[T.length-1]:p=null};function Aa(x,D,B,z){if(x.visible===!1)return;if(x.layers.test(D.layers)){if(x.isGroup)B=x.renderOrder;else if(x.isLOD)x.autoUpdate===!0&&x.update(D);else if(x.isLight)u.pushLight(x),x.castShadow&&u.pushShadow(x);else if(x.isSprite){if(!x.frustumCulled||ie.intersectsSprite(x)){z&&It.setFromMatrixPosition(x.matrixWorld).applyMatrix4($);let ot=O.update(x),pt=x.material;pt.visible&&p.push(x,ot,pt,B,It.z,null)}}else if((x.isMesh||x.isLine||x.isPoints)&&(!x.frustumCulled||ie.intersectsObject(x))){let ot=O.update(x),pt=x.material;if(z&&(x.boundingSphere!==void 0?(x.boundingSphere===null&&x.computeBoundingSphere(),It.copy(x.boundingSphere.center)):(ot.boundingSphere===null&&ot.computeBoundingSphere(),It.copy(ot.boundingSphere.center)),It.applyMatrix4(x.matrixWorld).applyMatrix4($)),Array.isArray(pt)){let ht=ot.groups;for(let wt=0,Rt=ht.length;wt0&&Fs(L,D,B),j.length>0&&Fs(j,D,B),ot.length>0&&Fs(ot,D,B),gt.buffers.depth.setTest(!0),gt.buffers.depth.setMask(!0),gt.buffers.color.setMask(!0),gt.setPolygonOffset(!1)}function il(x,D,B,z){if((B.isScene===!0?B.overrideMaterial:null)!==null)return;u.state.transmissionRenderTarget[z.id]===void 0&&(u.state.transmissionRenderTarget[z.id]=new cn(1,1,{generateMipmaps:!0,type:Lt.has("EXT_color_buffer_half_float")||Lt.has("EXT_color_buffer_float")?Hi:an,minFilter:Xn,samples:4,stencilBuffer:r,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Gt.workingColorSpace}));let j=u.state.transmissionRenderTarget[z.id],ot=z.viewport||R;j.setSize(ot.z*S.transmissionResolutionScale,ot.w*S.transmissionResolutionScale);let pt=S.getRenderTarget(),ht=S.getActiveCubeFace(),wt=S.getActiveMipmapLevel();S.setRenderTarget(j),S.getClearColor(H),q=S.getClearAlpha(),q<1&&S.setClearColor(16777215,.5),S.clear(),Ht&&yt.render(B);let Rt=S.toneMapping;S.toneMapping=Tn;let Et=z.viewport;if(z.viewport!==void 0&&(z.viewport=void 0),u.setupLightsView(z),Xt===!0&&nt.setGlobalState(S.clippingPlanes,z),Fs(x,B,z),Ft.updateMultisampleRenderTarget(j),Ft.updateRenderTargetMipmap(j),Lt.has("WEBGL_multisampled_render_to_texture")===!1){let Vt=!1;for(let Zt=0,ce=D.length;Zt0),Et=!!B.morphAttributes.position,Vt=!!B.morphAttributes.normal,Zt=!!B.morphAttributes.color,ce=Tn;z.toneMapped&&(U===null||U.isXRRenderTarget===!0)&&(ce=S.toneMapping);let te=B.morphAttributes.position||B.morphAttributes.normal||B.morphAttributes.color,$t=te!==void 0?te.length:0,Tt=_t.get(z),ae=u.state.lights;if(Xt===!0&&(Y===!0||x!==y)){let we=x===y&&z.id===v;nt.setState(z,x,we)}let Wt=!1;z.version===Tt.__version?(Tt.needsLights&&Tt.lightsStateVersion!==ae.state.version||Tt.outputColorSpace!==pt||L.isBatchedMesh&&Tt.batching===!1||!L.isBatchedMesh&&Tt.batching===!0||L.isBatchedMesh&&Tt.batchingColor===!0&&L.colorTexture===null||L.isBatchedMesh&&Tt.batchingColor===!1&&L.colorTexture!==null||L.isInstancedMesh&&Tt.instancing===!1||!L.isInstancedMesh&&Tt.instancing===!0||L.isSkinnedMesh&&Tt.skinning===!1||!L.isSkinnedMesh&&Tt.skinning===!0||L.isInstancedMesh&&Tt.instancingColor===!0&&L.instanceColor===null||L.isInstancedMesh&&Tt.instancingColor===!1&&L.instanceColor!==null||L.isInstancedMesh&&Tt.instancingMorph===!0&&L.morphTexture===null||L.isInstancedMesh&&Tt.instancingMorph===!1&&L.morphTexture!==null||Tt.envMap!==ht||z.fog===!0&&Tt.fog!==j||Tt.numClippingPlanes!==void 0&&(Tt.numClippingPlanes!==nt.numPlanes||Tt.numIntersection!==nt.numIntersection)||Tt.vertexAlphas!==wt||Tt.vertexTangents!==Rt||Tt.morphTargets!==Et||Tt.morphNormals!==Vt||Tt.morphColors!==Zt||Tt.toneMapping!==ce||Tt.morphTargetsCount!==$t)&&(Wt=!0):(Wt=!0,Tt.__version=z.version);let Ue=Tt.currentProgram;Wt===!0&&(Ue=Os(z,D,L));let pi=!1,Ne=!1,ji=!1,oe=Ue.getUniforms(),Ve=Tt.uniforms;if(gt.useProgram(Ue.program)&&(pi=!0,Ne=!0,ji=!0),z.id!==v&&(v=z.id,Ne=!0),pi||y!==x){gt.buffers.depth.getReversed()&&x.reversedDepth!==!0&&(x._reversedDepth=!0,x.updateProjectionMatrix()),oe.setValue(w,"projectionMatrix",x.projectionMatrix),oe.setValue(w,"viewMatrix",x.matrixWorldInverse);let Ie=oe.map.cameraPosition;Ie!==void 0&&Ie.setValue(w,ft.setFromMatrixPosition(x.matrixWorld)),Ct.logarithmicDepthBuffer&&oe.setValue(w,"logDepthBufFC",2/(Math.log(x.far+1)/Math.LN2)),(z.isMeshPhongMaterial||z.isMeshToonMaterial||z.isMeshLambertMaterial||z.isMeshBasicMaterial||z.isMeshStandardMaterial||z.isShaderMaterial)&&oe.setValue(w,"isOrthographic",x.isOrthographicCamera===!0),y!==x&&(y=x,Ne=!0,ji=!0)}if(L.isSkinnedMesh){oe.setOptional(w,L,"bindMatrix"),oe.setOptional(w,L,"bindMatrixInverse");let we=L.skeleton;we&&(we.boneTexture===null&&we.computeBoneTexture(),oe.setValue(w,"boneTexture",we.boneTexture,Ft))}L.isBatchedMesh&&(oe.setOptional(w,L,"batchingTexture"),oe.setValue(w,"batchingTexture",L._matricesTexture,Ft),oe.setOptional(w,L,"batchingIdTexture"),oe.setValue(w,"batchingIdTexture",L._indirectTexture,Ft),oe.setOptional(w,L,"batchingColorTexture"),L._colorsTexture!==null&&oe.setValue(w,"batchingColorTexture",L._colorsTexture,Ft));let He=B.morphAttributes;if((He.position!==void 0||He.normal!==void 0||He.color!==void 0)&&Q.update(L,B,Ue),(Ne||Tt.receiveShadow!==L.receiveShadow)&&(Tt.receiveShadow=L.receiveShadow,oe.setValue(w,"receiveShadow",L.receiveShadow)),z.isMeshGouraudMaterial&&z.envMap!==null&&(Ve.envMap.value=ht,Ve.flipEnvMap.value=ht.isCubeTexture&&ht.isRenderTargetTexture===!1?-1:1),z.isMeshStandardMaterial&&z.envMap===null&&D.environment!==null&&(Ve.envMapIntensity.value=D.environmentIntensity),Ne&&(oe.setValue(w,"toneMappingExposure",S.toneMappingExposure),Tt.needsLights&&ah(Ve,ji),j&&z.fog===!0&&J.refreshFogUniforms(Ve,j),J.refreshMaterialUniforms(Ve,z,V,et,u.state.transmissionRenderTarget[x.id]),Zi.upload(w,rl(Tt),Ve,Ft)),z.isShaderMaterial&&z.uniformsNeedUpdate===!0&&(Zi.upload(w,rl(Tt),Ve,Ft),z.uniformsNeedUpdate=!1),z.isSpriteMaterial&&oe.setValue(w,"center",L.center),oe.setValue(w,"modelViewMatrix",L.modelViewMatrix),oe.setValue(w,"normalMatrix",L.normalMatrix),oe.setValue(w,"modelMatrix",L.matrixWorld),z.isShaderMaterial||z.isRawShaderMaterial){let we=z.uniformsGroups;for(let Ie=0,Ca=we.length;Ie0&&Ft.useMultisampledRTT(x)===!1?L=_t.get(x).__webglMultisampledFramebuffer:Array.isArray(Rt)?L=Rt[B]:L=Rt,R.copy(x.viewport),F.copy(x.scissor),k=x.scissorTest}else R.copy(bt).multiplyScalar(V).floor(),F.copy(kt).multiplyScalar(V).floor(),k=Kt;if(B!==0&&(L=lh),gt.bindFramebuffer(w.FRAMEBUFFER,L)&&z&>.drawBuffers(x,L),gt.viewport(R),gt.scissor(F),gt.setScissorTest(k),j){let ht=_t.get(x.texture);w.framebufferTexture2D(w.FRAMEBUFFER,w.COLOR_ATTACHMENT0,w.TEXTURE_CUBE_MAP_POSITIVE_X+D,ht.__webglTexture,B)}else if(ot){let ht=D;for(let wt=0;wt=0&&D<=x.width-z&&B>=0&&B<=x.height-L&&(x.textures.length>1&&w.readBuffer(w.COLOR_ATTACHMENT0+pt),w.readPixels(D,B,z,L,vt.convert(Rt),vt.convert(Et),j))}finally{let wt=U!==null?_t.get(U).__webglFramebuffer:null;gt.bindFramebuffer(w.FRAMEBUFFER,wt)}}},this.readRenderTargetPixelsAsync=async function(x,D,B,z,L,j,ot,pt=0){if(!(x&&x.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let ht=_t.get(x).__webglFramebuffer;if(x.isWebGLCubeRenderTarget&&ot!==void 0&&(ht=ht[ot]),ht)if(D>=0&&D<=x.width-z&&B>=0&&B<=x.height-L){gt.bindFramebuffer(w.FRAMEBUFFER,ht);let wt=x.textures[pt],Rt=wt.format,Et=wt.type;if(!Ct.textureFormatReadable(Rt))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!Ct.textureTypeReadable(Et))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");let Vt=w.createBuffer();w.bindBuffer(w.PIXEL_PACK_BUFFER,Vt),w.bufferData(w.PIXEL_PACK_BUFFER,j.byteLength,w.STREAM_READ),x.textures.length>1&&w.readBuffer(w.COLOR_ATTACHMENT0+pt),w.readPixels(D,B,z,L,vt.convert(Rt),vt.convert(Et),0);let Zt=U!==null?_t.get(U).__webglFramebuffer:null;gt.bindFramebuffer(w.FRAMEBUFFER,Zt);let ce=w.fenceSync(w.SYNC_GPU_COMMANDS_COMPLETE,0);return w.flush(),await fc(w,ce,4),w.bindBuffer(w.PIXEL_PACK_BUFFER,Vt),w.getBufferSubData(w.PIXEL_PACK_BUFFER,0,j),w.deleteBuffer(Vt),w.deleteSync(ce),j}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(x,D=null,B=0){let z=Math.pow(2,-B),L=Math.floor(x.image.width*z),j=Math.floor(x.image.height*z),ot=D!==null?D.x:0,pt=D!==null?D.y:0;Ft.setTexture2D(x,0),w.copyTexSubImage2D(w.TEXTURE_2D,B,0,0,ot,pt,L,j),gt.unbindTexture()};let ch=w.createFramebuffer(),hh=w.createFramebuffer();this.copyTextureToTexture=function(x,D,B=null,z=null,L=0,j=null){j===null&&(L!==0?(Pi("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),j=L,L=0):j=0);let ot,pt,ht,wt,Rt,Et,Vt,Zt,ce,te=x.isCompressedTexture?x.mipmaps[j]:x.image;if(B!==null)ot=B.max.x-B.min.x,pt=B.max.y-B.min.y,ht=B.isBox3?B.max.z-B.min.z:1,wt=B.min.x,Rt=B.min.y,Et=B.isBox3?B.min.z:0;else{let He=Math.pow(2,-L);ot=Math.floor(te.width*He),pt=Math.floor(te.height*He),x.isDataArrayTexture?ht=te.depth:x.isData3DTexture?ht=Math.floor(te.depth*He):ht=1,wt=0,Rt=0,Et=0}z!==null?(Vt=z.x,Zt=z.y,ce=z.z):(Vt=0,Zt=0,ce=0);let $t=vt.convert(D.format),Tt=vt.convert(D.type),ae;D.isData3DTexture?(Ft.setTexture3D(D,0),ae=w.TEXTURE_3D):D.isDataArrayTexture||D.isCompressedArrayTexture?(Ft.setTexture2DArray(D,0),ae=w.TEXTURE_2D_ARRAY):(Ft.setTexture2D(D,0),ae=w.TEXTURE_2D),w.pixelStorei(w.UNPACK_FLIP_Y_WEBGL,D.flipY),w.pixelStorei(w.UNPACK_PREMULTIPLY_ALPHA_WEBGL,D.premultiplyAlpha),w.pixelStorei(w.UNPACK_ALIGNMENT,D.unpackAlignment);let Wt=w.getParameter(w.UNPACK_ROW_LENGTH),Ue=w.getParameter(w.UNPACK_IMAGE_HEIGHT),pi=w.getParameter(w.UNPACK_SKIP_PIXELS),Ne=w.getParameter(w.UNPACK_SKIP_ROWS),ji=w.getParameter(w.UNPACK_SKIP_IMAGES);w.pixelStorei(w.UNPACK_ROW_LENGTH,te.width),w.pixelStorei(w.UNPACK_IMAGE_HEIGHT,te.height),w.pixelStorei(w.UNPACK_SKIP_PIXELS,wt),w.pixelStorei(w.UNPACK_SKIP_ROWS,Rt),w.pixelStorei(w.UNPACK_SKIP_IMAGES,Et);let oe=x.isDataArrayTexture||x.isData3DTexture,Ve=D.isDataArrayTexture||D.isData3DTexture;if(x.isDepthTexture){let He=_t.get(x),we=_t.get(D),Ie=_t.get(He.__renderTarget),Ca=_t.get(we.__renderTarget);gt.bindFramebuffer(w.READ_FRAMEBUFFER,Ie.__webglFramebuffer),gt.bindFramebuffer(w.DRAW_FRAMEBUFFER,Ca.__webglFramebuffer);for(let Jn=0;JnMath.PI&&(n-=De),s<-Math.PI?s+=De:s>Math.PI&&(s-=De),n<=s?this._spherical.theta=Math.max(n,Math.min(s,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(n+s)/2?Math.max(n,this._spherical.theta):Math.min(s,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let r=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{let a=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),r=a!=this._spherical.radius}if(ge.setFromSpherical(this._spherical),ge.applyQuaternion(this._quatInverse),e.copy(this.target).add(ge),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let a=null;if(this.object.isPerspectiveCamera){let o=ge.length();a=this._clampDistance(o*this._scale);let l=o-a;this.object.position.addScaledVector(this._dollyDirection,l),this.object.updateMatrixWorld(),r=!!l}else if(this.object.isOrthographicCamera){let o=new N(this._mouse.x,this._mouse.y,0);o.unproject(this.object);let l=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),r=l!==this.object.zoom;let c=new N(this._mouse.x,this._mouse.y,0);c.unproject(this.object),this.object.position.sub(c).add(o),this.object.updateMatrixWorld(),a=ge.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;a!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(a).add(this.object.position):(ba.origin.copy(this.object.position),ba.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(ba.direction))qo||8*(1-this._lastQuaternion.dot(this.object.quaternion))>qo||this._lastTargetPosition.distanceToSquared(this.target)>qo?(this.dispatchEvent(Xc),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(t){return t!==null?De/60*this.autoRotateSpeed*t:De/60/60*this.autoRotateSpeed}_getZoomScale(t){let e=Math.abs(t*.01);return Math.pow(.95,this.zoomSpeed*e)}_rotateLeft(t){this._sphericalDelta.theta-=t}_rotateUp(t){this._sphericalDelta.phi-=t}_panLeft(t,e){ge.setFromMatrixColumn(e,0),ge.multiplyScalar(-t),this._panOffset.add(ge)}_panUp(t,e){this.screenSpacePanning===!0?ge.setFromMatrixColumn(e,1):(ge.setFromMatrixColumn(e,0),ge.crossVectors(this.object.up,ge)),ge.multiplyScalar(t),this._panOffset.add(ge)}_pan(t,e){let n=this.domElement;if(this.object.isPerspectiveCamera){let s=this.object.position;ge.copy(s).sub(this.target);let r=ge.length();r*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*t*r/n.clientHeight,this.object.matrix),this._panUp(2*e*r/n.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(t*(this.object.right-this.object.left)/this.object.zoom/n.clientWidth,this.object.matrix),this._panUp(e*(this.object.top-this.object.bottom)/this.object.zoom/n.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(t){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=t:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(t){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=t:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(t,e){if(!this.zoomToCursor)return;this._performCursorZoom=!0;let n=this.domElement.getBoundingClientRect(),s=t-n.left,r=e-n.top,a=n.width,o=n.height;this._mouse.x=s/a*2-1,this._mouse.y=-(r/o)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(t){return Math.max(this.minDistance,Math.min(this.maxDistance,t))}_handleMouseDownRotate(t){this._rotateStart.set(t.clientX,t.clientY)}_handleMouseDownDolly(t){this._updateZoomParameters(t.clientX,t.clientX),this._dollyStart.set(t.clientX,t.clientY)}_handleMouseDownPan(t){this._panStart.set(t.clientX,t.clientY)}_handleMouseMoveRotate(t){this._rotateEnd.set(t.clientX,t.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);let e=this.domElement;this._rotateLeft(De*this._rotateDelta.x/e.clientHeight),this._rotateUp(De*this._rotateDelta.y/e.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(t){this._dollyEnd.set(t.clientX,t.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(t){this._panEnd.set(t.clientX,t.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(t){this._updateZoomParameters(t.clientX,t.clientY),t.deltaY<0?this._dollyIn(this._getZoomScale(t.deltaY)):t.deltaY>0&&this._dollyOut(this._getZoomScale(t.deltaY)),this.update()}_handleKeyDown(t){let e=!1;switch(t.code){case this.keys.UP:t.ctrlKey||t.metaKey||t.shiftKey?this.enableRotate&&this._rotateUp(De*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),e=!0;break;case this.keys.BOTTOM:t.ctrlKey||t.metaKey||t.shiftKey?this.enableRotate&&this._rotateUp(-De*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),e=!0;break;case this.keys.LEFT:t.ctrlKey||t.metaKey||t.shiftKey?this.enableRotate&&this._rotateLeft(De*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),e=!0;break;case this.keys.RIGHT:t.ctrlKey||t.metaKey||t.shiftKey?this.enableRotate&&this._rotateLeft(-De*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),e=!0;break}e&&(t.preventDefault(),this.update())}_handleTouchStartRotate(t){if(this._pointers.length===1)this._rotateStart.set(t.pageX,t.pageY);else{let e=this._getSecondPointerPosition(t),n=.5*(t.pageX+e.x),s=.5*(t.pageY+e.y);this._rotateStart.set(n,s)}}_handleTouchStartPan(t){if(this._pointers.length===1)this._panStart.set(t.pageX,t.pageY);else{let e=this._getSecondPointerPosition(t),n=.5*(t.pageX+e.x),s=.5*(t.pageY+e.y);this._panStart.set(n,s)}}_handleTouchStartDolly(t){let e=this._getSecondPointerPosition(t),n=t.pageX-e.x,s=t.pageY-e.y,r=Math.sqrt(n*n+s*s);this._dollyStart.set(0,r)}_handleTouchStartDollyPan(t){this.enableZoom&&this._handleTouchStartDolly(t),this.enablePan&&this._handleTouchStartPan(t)}_handleTouchStartDollyRotate(t){this.enableZoom&&this._handleTouchStartDolly(t),this.enableRotate&&this._handleTouchStartRotate(t)}_handleTouchMoveRotate(t){if(this._pointers.length==1)this._rotateEnd.set(t.pageX,t.pageY);else{let n=this._getSecondPointerPosition(t),s=.5*(t.pageX+n.x),r=.5*(t.pageY+n.y);this._rotateEnd.set(s,r)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);let e=this.domElement;this._rotateLeft(De*this._rotateDelta.x/e.clientHeight),this._rotateUp(De*this._rotateDelta.y/e.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(t){if(this._pointers.length===1)this._panEnd.set(t.pageX,t.pageY);else{let e=this._getSecondPointerPosition(t),n=.5*(t.pageX+e.x),s=.5*(t.pageY+e.y);this._panEnd.set(n,s)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(t){let e=this._getSecondPointerPosition(t),n=t.pageX-e.x,s=t.pageY-e.y,r=Math.sqrt(n*n+s*s);this._dollyEnd.set(0,r),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);let a=(t.pageX+e.x)*.5,o=(t.pageY+e.y)*.5;this._updateZoomParameters(a,o)}_handleTouchMoveDollyPan(t){this.enableZoom&&this._handleTouchMoveDolly(t),this.enablePan&&this._handleTouchMovePan(t)}_handleTouchMoveDollyRotate(t){this.enableZoom&&this._handleTouchMoveDolly(t),this.enableRotate&&this._handleTouchMoveRotate(t)}_addPointer(t){this._pointers.push(t.pointerId)}_removePointer(t){delete this._pointerPositions[t.pointerId];for(let e=0;edocument.getElementById(i),Zc=64*1024*1024,Qt=(i,t)=>{if(!i)throw new Error(t)},Zo={"hinged-box":"The hinged box","tool-reach":"Beyond reach"},$e,Ke="hinged-box",ne,Ta,Le,Yn,Je,An,fn,$i,Ki=[],Jo=[],$o=[],Cn=0,Ls=!1,eh=0,Ko=!1,Jc=0,$c,Kc=new Map;function nh(i){return Qt(typeof i=="string"&&/^[a-zA-Z0-9_.-]+(?:\/[a-zA-Z0-9_.-]+)*$/.test(i)&&!i.split("/").some(t=>t==="."||t===".."),"Invalid export path"),i}async function ih(i,t){Qt(i,"Missing response body");let e=i.getReader(),n=[],s=0;try{for(;;){let{done:o,value:l}=await e.read();if(o)break;s+=l.byteLength,Qt(s<=t,"Asset exceeds byte limit"),n.push(l)}}finally{await e.cancel().catch(()=>{}),e.releaseLock()}let r=new Uint8Array(s),a=0;for(let o of n)r.set(o,a),a+=o.length;return r.buffer}async function sh(i,t){let e=new URL(nh(i),location.href),n=location.hostname==="dvidia-robot-simulation-lab.static.hf.space",s=n&&i.endsWith(".bin.gz")?[new URL("https://research.dvidia.org/downloads/topics/physical-grounding/runs/2026-10-13-skill-prerequisites-v01/lab/"+i),e]:[e],r;for(let[a,o]of s.entries()){let l=new AbortController,c=setTimeout(()=>l.abort(),a===0&&s.length>1?15e3:45e3);try{let h=await fetch(o,{signal:l.signal,credentials:"omit",referrerPolicy:"no-referrer",redirect:n?"follow":"error"}),d=new URL(h.url);return Qt(d.origin===o.origin||n&&d.protocol==="https:"&&(d.hostname.endsWith(".hf.co")||d.hostname==="huggingface.co"),"Unexpected asset redirect"),Qt(h.ok,"HTTP "+h.status+" loading "+i),await ih(h.body,t)}catch(h){r=h}finally{clearTimeout(c)}}throw new Error("Could not load "+i+". "+r.message)}async function jo(i){return JSON.parse(new TextDecoder().decode(await sh(i,8*1024*1024)))}async function jc(i){Qt(i?.compression==="gzip"&&Number.isInteger(i.bytes)&&i.bytes>0&&i.bytes<=Zc&&Number.isInteger(i.compressed_bytes)&&i.compressed_bytes>0&&i.compressed_bytes<=Zc,"Invalid binary descriptor");let t=await sh(i.href,i.compressed_bytes);Qt(t.byteLength===i.compressed_bytes,"Compressed length mismatch");let e=await ih(new Blob([t]).stream().pipeThrough(new DecompressionStream("gzip")),i.bytes);Qt(e.byteLength===i.bytes,"Decoded length mismatch"),Qt(crypto?.subtle,"This viewer requires a secure context or localhost");let n=[...new Uint8Array(await crypto.subtle.digest("SHA-256",e))].map(s=>s.toString(16).padStart(2,"0")).join("");return Qt(n===i.sha256,"Binary checksum mismatch"),e}function Zm(i,t,e,n){Qt(i.schema==="dvidia.prerequisite-scene/v1"&&t.schema==="dvidia.prerequisite-motion/v1","Unsupported replay schema"),Qt(Number.isInteger(t.body_count)&&t.body_count>0&&t.body_count<=128&&i.bodies.length===t.body_count&&Number.isInteger(t.frame_count)&&t.frame_count>=2&&t.frame_count<=1e4&&t.times.length===t.frame_count&&n.byteLength===t.frame_count*t.body_count*28,"Invalid pose layout"),Qt(t.times.every((o,l)=>Number.isFinite(o)&&o>=0&&(!l||o>t.times[l-1])),"Invalid timestamps"),Qt(i.meshes.length<=128&&i.geoms.length<=512,"Scene too large");let s=new DataView(e),r=new Set;for(let o of i.meshes){let l=o.vertex_count,c=o.index_count,h=o.position_byte_offset,d=o.index_byte_offset;Qt([o.id,l,c,h,d].every(Number.isInteger)&&!r.has(o.id)&&l>0&&c>=0&&c%3===0&&h>=0&&d>=0&&h+l*12<=e.byteLength&&d+c*4<=e.byteLength,"Invalid mesh range"),r.add(o.id);for(let f=0;f=0&&o.body_ide*2));case"sphere":return new Oi(i.size[0],20,12);case"ellipsoid":{let e=new Oi(1,24,16);return e.scale(...i.size),e}case"capsule":{let e=new ys(i.size[0],2*i.size[1],6,18);return e.rotateX(Math.PI/2),e}case"cylinder":{let e=new vs(i.size[0],i.size[0],i.size[1]*2,24);return e.rotateX(Math.PI/2),e}case"plane":return new ii(5,5)}}function fi(){!Ko&&Je&&(Ko=!0,requestAnimationFrame($m))}function Us(i){Cn=Math.min(Le.frame_count-1,Math.max(0,i)),dt("timeline").value=Cn;let t=Le.times[Cn];dt("clock").textContent=t.toFixed(2)+" / "+Le.times.at(-1).toFixed(2)+" s";for(let e=0;ee.classList.toggle("current",Math.abs(Number(e.dataset.time)-t)<.15)),dt("stage").dataset.frame=String(Cn),fi()}function di(){Ls=!1,dt("play").textContent="Play trial",dt("play").setAttribute("aria-pressed","false")}function $m(i){if(Ko=!1,Ls&&Le){let t=Math.max(0,(i-eh)/1e3),e=Cn;for(;e+1{e.geometry&&i.add(e.geometry),e.material&&t.add(e.material)}),i.forEach(e=>e.dispose()),t.forEach(e=>e.dispose())}function jm(i){Je||(Qt(dt("canvas").getContext("webgl2"),"WebGL2 is unavailable"),Je=new Ma({canvas:dt("canvas"),antialias:!0,powerPreference:"low-power"}),Je.setPixelRatio(Math.min(devicePixelRatio||1,1.5)),Je.outputColorSpace=Ce,Je.toneMapping=Lr,Je.toneMappingExposure=1.25,Je.shadowMap.enabled=!0,Je.shadowMap.type=Tr,fn=new Se(38,1,.01,20),fn.up.set(0,0,1),$i=new Ea(fn,dt("canvas")),$i.minDistance=.3,$i.maxDistance=4,$i.addEventListener("change",fi),$c=new ResizeObserver(()=>{let a=dt("stage").getBoundingClientRect();fn.aspect=a.width/a.height,fn.updateProjectionMatrix(),Je.setSize(a.width,a.height,!1),fi()}),$c.observe(dt("stage"))),Km(),An=new gs,An.background=new zt(15330015),An.add(new bs(16251903,9739389,2.6));let t=new zi(16775143,3.2);t.position.set(1,-1,3),t.castShadow=!0,t.shadow.mapSize.set(1024,1024),t.shadow.camera.left=-1.4,t.shadow.camera.right=1.4,t.shadow.camera.top=1.4,t.shadow.camera.bottom=-1.4,t.shadow.normalBias=.003,An.add(t);let e=new zi(15003135,.9);e.position.set(-1,1,2),An.add(e),Ki=Ta.bodies.map(()=>{let a=new vn;return An.add(a),a}),Jo=[],$o=[];let n=new Map,s=new DataView(i);for(let a of Ta.meshes){let o=new Float32Array(a.vertex_count*3),l=new Uint32Array(a.index_count);for(let h=0;h{let d=new Pe(o,h);d.position.fromArray(a.position);let f=a.quaternion_wxyz;return d.quaternion.set(f[1],f[2],f[3],f[0]),Ki[a.body_id].add(d),d};if(l[3]>0&&a.group<=2){let h=c(new Bi({color:new zt().setRGB(...l.slice(0,3),bn),roughness:.68,metalness:a.type==="mesh"?.12:0,transparent:l[3]<1,opacity:l[3],side:Ye}));h.castShadow=a.type!=="plane",h.receiveShadow=!0,Jo.push(h)}if(a.collision){let h=c(new Bi({color:12154699,transparent:!0,opacity:.4,depthWrite:!1}));h.visible=!1,$o.push(h)}}let r=dt("stage").getBoundingClientRect();fn.aspect=r.width/r.height,fn.updateProjectionMatrix(),Je.setSize(r.width,r.height,!1),Us(0),Qo("home"),dt("collision").setAttribute("aria-pressed","false"),dt("scene-state").textContent="NATIVE PHYSICS · RECORDED POSES"}function Ns(i){return i.replaceAll("_"," ")}function Qc(i){return typeof i=="number"?Number.isInteger(i)?String(i):i.toFixed(2):typeof i=="boolean"?i?"Yes":"No":String(i??"—")}function Qm(i){return Number(i.t??i.time_s??i.time??0)}function tg(){let i=dt("events");i.replaceChildren();for(let t of ne.events){let e=document.createElement("li"),n=document.createElement("button"),s=document.createElement("time"),r=document.createElement("span"),a=Qm(t);s.textContent=a.toFixed(2)+" s",r.textContent=t.message||Ns(t.type||t.event||"event"),n.dataset.time=a,n.append(s,r),n.addEventListener("click",()=>{di();let o=Le.times.findIndex(l=>l>=a);Us(o<0?Le.frame_count-1:o)}),e.append(n),i.append(e)}if(!ne.events.length){let t=document.createElement("li");t.className="events-empty",t.textContent="No discrete intervention events were recorded.",i.append(t)}}function eg(){let i=dt("results");i.replaceChildren();for(let t of $e.groups){let e=document.createElement("tr");for(let n of[Zo[t.task],t.policy==="baseline"?"Baseline":"Feedback & recovery",t.successes+" / "+t.attempts,t.valid+" / "+t.attempts,Object.entries(t.outcomes).map(([s,r])=>Ns(s)+": "+r).join(" · ")]){let s=document.createElement("td");s.textContent=n,e.append(s)}i.append(e)}}async function tl(){let i=++Jc;if(di(),document.querySelectorAll("#play,#timeline,#collision,#case,#policy,[data-task]").forEach(r=>r.disabled=!0),dt("loading").hidden=!1,dt("loading-message").textContent="Loading geometry and recorded motion.",dt("stage").dataset.ready="loading",ne=$e.attempts.find(r=>r.task===Ke&&r.case.id===dt("case").value&&r.policy===dt("policy").value),Qt(ne,"Trial not found"),dt("outcome").textContent=Ns(ne.valid?ne.metrics.outcome||(ne.success?"completed":"failed"):"invalid_attempt"),dt("outcome").dataset.success=ne.success&&ne.valid,dt("outcome").dataset.valid=ne.valid,dt("success").textContent=ne.success&&ne.valid?"Yes":"No",dt("details").textContent=JSON.stringify({case:ne.case,metrics:ne.metrics,errors:ne.errors},null,2),dt("receipt").href="trials/"+nh(ne.id)+".json",dt("metric-a-label").textContent=Ke==="tool-reach"?"Shoe retrieved":"Interventions",dt("metric-a").textContent=Qc(Ke==="tool-reach"?ne.metrics.retrieval_success:ne.metrics.intervention_count),dt("metric-b-label").textContent=Ke==="tool-reach"?"Retained lift":"Peak lid contact · N",dt("metric-b").textContent=Qc(Ke==="tool-reach"?ne.metrics.retained_lift_success:ne.metrics.peak_lid_robot_normal_force_n),!ne.replay)throw new Error("This attempt has no valid replay. Its failure receipt remains downloadable.");let[t,e]=await Promise.all([jo(ne.replay.model),jo(ne.replay.motion)]),n=Kc.get(t.geometry_binary.sha256);n||(n=await jc(t.geometry_binary),Kc.set(t.geometry_binary.sha256,n));let s=await jc(e.motion_binary);i===Jc&&(Zm(t,e,n,s),Ta=t,Le=e,Yn=new Float32Array(s),jm(n),tg(),dt("timeline").max=String(Le.frame_count-1),dt("duration").textContent=Le.times.at(-1).toFixed(2)+" s",dt("status").textContent=($e.split==="heldout"?"Held-out parameter case":"Development case")+" · "+Ns(ne.case.id)+" · "+(ne.policy==="baseline"?"Baseline":"Feedback & recovery"),dt("stage").dataset.ready="true",dt("loading").hidden=!0,document.querySelectorAll("#play,#timeline,#collision,#case,#policy,[data-task]").forEach(r=>r.disabled=!1))}function th(i){Ke=i,document.querySelectorAll("[data-task]").forEach(e=>e.setAttribute("aria-pressed",String(e.dataset.task===Ke))),dt("scene-title").textContent=Zo[Ke],dt("experiment-title").textContent=Zo[Ke],dt("task-description").textContent=Ke==="hinged-box"?"Reach toward the shoe, anticipate a closing lid, and withdraw when the clearance changes.":"A mounted rake brings a free shoe into the arm’s workspace. Retrieval and the subsequent grip are measured separately.",dt("scope-note").textContent=Ke==="hinged-box"?"Completion means reaching the shoe-access waypoint and withdrawing. A safe abort does not count as task completion. Contact thresholds are synthetic test criteria, not injury limits.":"The rake starts mounted to the arm. Tool pickup and selection are not evaluated. The baseline has no tool, so this measures a combined tool-and-strategy change.";let t=new Set;dt("case").replaceChildren();for(let e of $e.attempts.filter(n=>n.task===Ke)){if(t.has(e.case.id))continue;t.add(e.case.id);let n=document.createElement("option");n.value=e.case.id,n.textContent=Ns(e.case.id),dt("case").append(n)}tl().catch(wa)}function wa(i){di(),dt("loading").hidden=!1,dt("loading-message").textContent=i.message,dt("stage").dataset.ready="error",dt("status").textContent="Replay unavailable. The protocol and trial receipts remain accessible.",dt("case").disabled=!1,dt("policy").disabled=!1,document.querySelectorAll("[data-task]").forEach(t=>t.disabled=!1),console.error(i)}async function ng(){Qt(location.protocol!=="file:","Serve the export over HTTP"),$e=await jo("benchmark.json"),Qt($e.schema==="dvidia.skill-prerequisites/v1"&&Array.isArray($e.attempts)&&$e.attempts.length<=100,"Invalid benchmark"),eg();let i=$e.source.commit;i&&(Qt(/^[a-f0-9]{40}$/.test(i),"Invalid source commit"),dt("source").href="https://github.com/Dvidia-Inference/dvidia-training/tree/"+i),dt("command").textContent=`git clone https://github.com/Dvidia-Inference/dvidia-training.git +cd dvidia-training +`+(i?"git checkout "+i+` +`:"")+`python -m venv .venv +# Activate .venv using your shell, then: +python -m pip install ".[arm]" +dvidia-robot-sim fetch piper --output robot-assets +dvidia-prerequisites --assets robot-assets --output results --split `+$e.split+` +python -m http.server 8000 --directory results`,document.querySelectorAll("[data-task]").forEach(t=>t.addEventListener("click",()=>th(t.dataset.task))),document.querySelectorAll("[data-camera]").forEach(t=>t.addEventListener("click",()=>{fn&&Qo(t.dataset.camera)})),dt("case").addEventListener("change",()=>tl().catch(wa)),dt("policy").addEventListener("change",()=>tl().catch(wa)),dt("play").addEventListener("click",()=>{if(Ls){di();return}Cn===Le.frame_count-1&&Us(0),Ls=!0,eh=performance.now()-Le.times[Cn]*1e3,dt("play").textContent="Pause trial",dt("play").setAttribute("aria-pressed","true"),fi()}),dt("timeline").addEventListener("input",()=>{di(),Us(Number(dt("timeline").value))}),dt("collision").addEventListener("click",()=>{let t=dt("collision").getAttribute("aria-pressed")!=="true";dt("collision").setAttribute("aria-pressed",String(t)),Jo.forEach(e=>e.visible=!t),$o.forEach(e=>e.visible=t),dt("scene-state").textContent=t?"COLLISION GEOMETRY · RECORDED POSES":"NATIVE PHYSICS · RECORDED POSES",fi()}),dt("canvas").addEventListener("keydown",t=>{(t.key==="Home"||t.key==="h")&&(t.preventDefault(),Qo("home"))}),document.addEventListener("visibilitychange",()=>{document.hidden&&di()}),document.querySelectorAll("[data-task]").forEach(t=>t.hidden=!$e.attempts.some(e=>e.task===t.dataset.task)),th($e.attempts[0].task)}ng().catch(wa);})(); diff --git a/src/dvidia_training/prerequisite_lab.html b/src/dvidia_training/prerequisite_lab.html new file mode 100644 index 0000000..7a7a11f --- /dev/null +++ b/src/dvidia_training/prerequisite_lab.html @@ -0,0 +1,118 @@ + +Learning the prerequisites · DVIDIA +

DVIDIA ROBOTICS · EXPERIMENTS / 0.1

Learning the prerequisites.

A closing lid. A shoe beyond reach. Two experiments in knowing when to act, when to recover, and when to ask for help.

Recorded native simulation
+
+

Opening the published evidence…

PiPER / Hinged shoe box
NATIVE PHYSICS · RECORDED POSESEvery attempt is retained, including failures.
Opening the experimentLoading geometry and recorded motion.
0.00 s

Drag to orbit. Scroll to zoom. These are measured poses from a CPU simulation. The browser replays the experiment; it does not run physics or control hardware.

What happened

    +
    +

    The complete benchmark

    All planned trials are included. A safe stop or a retrieved shoe is reported separately from completing the task. Baseline and recovery share scene conditions; the reach experiment also changes whether a tool is fitted.

    ExperimentApproachCompleted / attemptedValid native runsOutcomes
    +

    Run it on your machine

    Native benchmarks run on the CPU. Install the optional simulation dependencies and pinned arm assets once; subsequent runs can be offline. Replay needs a browser with WebGL2. Minimum RAM has not been established across machines.

    Frozen protocol · All results · Artifact checksums · Source code · Licenses & scope

    Brand and font notices

    The DVIDIA mark and wordmark reproduce the existing DVIDIA website identity. The code license does not grant trademark rights. The embedded, unmodified IBM Plex Sans font retains its separate SIL Open Font License.

    Copyright © 2017 IBM Corp. with Reserved Font Name "Plex"
    +
    +This Font Software is licensed under the SIL Open Font License, Version 1.1.
    +
    +This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL
    +
    +
    +-----------------------------------------------------------
    +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
    +-----------------------------------------------------------
    +
    +PREAMBLE
    +The goals of the Open Font License (OFL) are to stimulate worldwide
    +development of collaborative font projects, to support the font creation
    +efforts of academic and linguistic communities, and to provide a free and
    +open framework in which fonts may be shared and improved in partnership
    +with others.
    +
    +The OFL allows the licensed fonts to be used, studied, modified and
    +redistributed freely as long as they are not sold by themselves. The
    +fonts, including any derivative works, can be bundled, embedded, 
    +redistributed and/or sold with any software provided that any reserved
    +names are not used by derivative works. The fonts and derivatives,
    +however, cannot be released under any other type of license. The
    +requirement for fonts to remain under this license does not apply
    +to any document created using the fonts or their derivatives.
    +
    +DEFINITIONS
    +"Font Software" refers to the set of files released by the Copyright
    +Holder(s) under this license and clearly marked as such. This may
    +include source files, build scripts and documentation.
    +
    +"Reserved Font Name" refers to any names specified as such after the
    +copyright statement(s).
    +
    +"Original Version" refers to the collection of Font Software components as
    +distributed by the Copyright Holder(s).
    +
    +"Modified Version" refers to any derivative made by adding to, deleting,
    +or substituting -- in part or in whole -- any of the components of the
    +Original Version, by changing formats or by porting the Font Software to a
    +new environment.
    +
    +"Author" refers to any designer, engineer, programmer, technical
    +writer or other person who contributed to the Font Software.
    +
    +PERMISSION & CONDITIONS
    +Permission is hereby granted, free of charge, to any person obtaining
    +a copy of the Font Software, to use, study, copy, merge, embed, modify,
    +redistribute, and sell modified and unmodified copies of the Font
    +Software, subject to the following conditions:
    +
    +1) Neither the Font Software nor any of its individual components,
    +in Original or Modified Versions, may be sold by itself.
    +
    +2) Original or Modified Versions of the Font Software may be bundled,
    +redistributed and/or sold with any software, provided that each copy
    +contains the above copyright notice and this license. These can be
    +included either as stand-alone text files, human-readable headers or
    +in the appropriate machine-readable metadata fields within text or
    +binary files as long as those fields can be easily viewed by the user.
    +
    +3) No Modified Version of the Font Software may use the Reserved Font
    +Name(s) unless explicit written permission is granted by the corresponding
    +Copyright Holder. This restriction only applies to the primary font name as
    +presented to the users.
    +
    +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
    +Software shall not be used to promote, endorse or advertise any
    +Modified Version, except to acknowledge the contribution(s) of the
    +Copyright Holder(s) and the Author(s) or with their explicit written
    +permission.
    +
    +5) The Font Software, modified or unmodified, in part or in whole,
    +must be distributed entirely under this license, and must not be
    +distributed under any other license. The requirement for fonts to
    +remain under this license does not apply to any document created
    +using the Font Software.
    +
    +TERMINATION
    +This license becomes null and void if any of the above conditions are
    +not met.
    +
    +DISCLAIMER
    +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
    +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
    +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
    +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
    +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
    +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
    +OTHER DEALINGS IN THE FONT SOFTWARE.
    +
    diff --git a/src/dvidia_training/prerequisite_lab.js b/src/dvidia_training/prerequisite_lab.js new file mode 100644 index 0000000..b4b5cc5 --- /dev/null +++ b/src/dvidia_training/prerequisite_lab.js @@ -0,0 +1,82 @@ +/* DVIDIA prerequisite experiment viewer. MIT. Recorded native poses only. */ +import * as THREE from 'three'; +import {OrbitControls} from 'three/addons/controls/OrbitControls.js'; +const $=id=>document.getElementById(id), MAX=64*1024*1024; +const assert=(ok,message)=>{if(!ok)throw new Error(message);}; +const names={'hinged-box':'The hinged box','tool-reach':'Beyond reach'}; +let report,task='hinged-box',trial,model,motion,pose,renderer,scene,camera,orbit,bodyGroups=[],visual=[],collision=[],frame=0,playing=false,started=0,queued=false,generation=0,resizeObserver; +const geometryCache=new Map(); +function localPath(path){assert(typeof path==='string'&&/^[a-zA-Z0-9_.-]+(?:\/[a-zA-Z0-9_.-]+)*$/.test(path)&&!path.split('/').some(p=>p==='.'||p==='..'),'Invalid export path');return path;} +async function bounded(stream,limit){assert(stream,'Missing response body');const reader=stream.getReader(),chunks=[];let length=0;try{for(;;){const {done,value}=await reader.read();if(done)break;length+=value.byteLength;assert(length<=limit,'Asset exceeds byte limit');chunks.push(value);}}finally{await reader.cancel().catch(()=>{});reader.releaseLock();}const out=new Uint8Array(length);let offset=0;for(const c of chunks){out.set(c,offset);offset+=c.length;}return out.buffer;} +async function resource(path,limit){ + const local=new URL(localPath(path),location.href), hosted=location.hostname==='dvidia-robot-simulation-lab.static.hf.space'; + const urls=hosted&&path.endsWith('.bin.gz')?[new URL('https://research.dvidia.org/downloads/topics/physical-grounding/runs/2026-10-13-skill-prerequisites-v01/lab/'+path),local]:[local]; + let last; + for(const [i,url] of urls.entries()){ + const controller=new AbortController(),timeout=setTimeout(()=>controller.abort(),i===0&&urls.length>1?15000:45000); + try{ + const r=await fetch(url,{signal:controller.signal,credentials:'omit',referrerPolicy:'no-referrer',redirect:hosted?'follow':'error'}); + const final=new URL(r.url); + assert(final.origin===url.origin||(hosted&&final.protocol==='https:'&&(final.hostname.endsWith('.hf.co')||final.hostname==='huggingface.co')),'Unexpected asset redirect'); + assert(r.ok,'HTTP '+r.status+' loading '+path); + return await bounded(r.body,limit); + }catch(error){last=error;}finally{clearTimeout(timeout);} + } + throw new Error('Could not load '+path+'. '+last.message); +} +async function json(path){return JSON.parse(new TextDecoder().decode(await resource(path,8*1024*1024)));} +async function binary(meta){ + assert(meta?.compression==='gzip'&&Number.isInteger(meta.bytes)&&meta.bytes>0&&meta.bytes<=MAX&&Number.isInteger(meta.compressed_bytes)&&meta.compressed_bytes>0&&meta.compressed_bytes<=MAX,'Invalid binary descriptor'); + const bytes=await resource(meta.href,meta.compressed_bytes);assert(bytes.byteLength===meta.compressed_bytes,'Compressed length mismatch'); + const unpacked=await bounded(new Blob([bytes]).stream().pipeThrough(new DecompressionStream('gzip')),meta.bytes);assert(unpacked.byteLength===meta.bytes,'Decoded length mismatch'); + assert(crypto?.subtle,'This viewer requires a secure context or localhost'); + const hash=[...new Uint8Array(await crypto.subtle.digest('SHA-256',unpacked))].map(x=>x.toString(16).padStart(2,'0')).join(''); + assert(hash===meta.sha256,'Binary checksum mismatch');return unpacked; +} +function validate(m,p,g,data){ + assert(m.schema==='dvidia.prerequisite-scene/v1'&&p.schema==='dvidia.prerequisite-motion/v1','Unsupported replay schema'); + assert(Number.isInteger(p.body_count)&&p.body_count>0&&p.body_count<=128&&m.bodies.length===p.body_count&&Number.isInteger(p.frame_count)&&p.frame_count>=2&&p.frame_count<=10000&&p.times.length===p.frame_count&&data.byteLength===p.frame_count*p.body_count*28,'Invalid pose layout'); + assert(p.times.every((t,i)=>Number.isFinite(t)&&t>=0&&(!i||t>p.times[i-1])),'Invalid timestamps'); + assert(m.meshes.length<=128&&m.geoms.length<=512,'Scene too large'); + const dv=new DataView(g),ids=new Set(); + for(const mesh of m.meshes){const n=mesh.vertex_count,k=mesh.index_count,v=mesh.position_byte_offset,f=mesh.index_byte_offset;assert([mesh.id,n,k,v,f].every(Number.isInteger)&&!ids.has(mesh.id)&&n>0&&k>=0&&k%3===0&&v>=0&&f>=0&&v+n*12<=g.byteLength&&f+k*4<=g.byteLength,'Invalid mesh range');ids.add(mesh.id);for(let i=0;i=0&&geom.body_idx*2));case'sphere':return new THREE.SphereGeometry(g.size[0],20,12);case'ellipsoid':{const shape=new THREE.SphereGeometry(1,24,16);shape.scale(...g.size);return shape;}case'capsule':{const shape=new THREE.CapsuleGeometry(g.size[0],2*g.size[1],6,18);shape.rotateX(Math.PI/2);return shape;}case'cylinder':{const shape=new THREE.CylinderGeometry(g.size[0],g.size[0],g.size[1]*2,24);shape.rotateX(Math.PI/2);return shape;}case'plane':return new THREE.PlaneGeometry(5,5);}} +function requestRender(){if(!queued&&renderer){queued=true;requestAnimationFrame(render);}} +function showFrame(index){ + frame=Math.min(motion.frame_count-1,Math.max(0,index));$('timeline').value=frame;const t=motion.times[frame];$('clock').textContent=t.toFixed(2)+' / '+motion.times.at(-1).toFixed(2)+' s'; + for(let i=0;ibutton.classList.toggle('current',Math.abs(Number(button.dataset.time)-t)<.15)); + $('stage').dataset.frame=String(frame);requestRender(); +} +function stop(){playing=false;$('play').textContent='Play trial';$('play').setAttribute('aria-pressed','false');} +function render(now){queued=false;if(playing&&motion){const t=Math.max(0,(now-started)/1000);let next=frame;while(next+1{if(o.geometry)geometries.add(o.geometry);if(o.material)materials.add(o.material);});geometries.forEach(g=>g.dispose());materials.forEach(m=>m.dispose());} +function setup(geometry){ + if(!renderer){assert($('canvas').getContext('webgl2'),'WebGL2 is unavailable');renderer=new THREE.WebGLRenderer({canvas:$('canvas'),antialias:true,powerPreference:'low-power'});renderer.setPixelRatio(Math.min(devicePixelRatio||1,1.5));renderer.outputColorSpace=THREE.SRGBColorSpace;renderer.toneMapping=THREE.ACESFilmicToneMapping;renderer.toneMappingExposure=1.25;renderer.shadowMap.enabled=true;renderer.shadowMap.type=THREE.PCFSoftShadowMap;camera=new THREE.PerspectiveCamera(38,1,.01,20);camera.up.set(0,0,1);orbit=new OrbitControls(camera,$('canvas'));orbit.minDistance=.3;orbit.maxDistance=4;orbit.addEventListener('change',requestRender);resizeObserver=new ResizeObserver(()=>{const r=$('stage').getBoundingClientRect();camera.aspect=r.width/r.height;camera.updateProjectionMatrix();renderer.setSize(r.width,r.height,false);requestRender();});resizeObserver.observe($('stage'));} + disposeScene();scene=new THREE.Scene();scene.background=new THREE.Color(0xe9eadf);scene.add(new THREE.HemisphereLight(0xf7fbff,0x949c7d,2.6));const sun=new THREE.DirectionalLight(0xfff7e7,3.2);sun.position.set(1,-1,3);sun.castShadow=true;sun.shadow.mapSize.set(1024,1024);sun.shadow.camera.left=-1.4;sun.shadow.camera.right=1.4;sun.shadow.camera.top=1.4;sun.shadow.camera.bottom=-1.4;sun.shadow.normalBias=.003;scene.add(sun);const fill=new THREE.DirectionalLight(0xe4edff,.9);fill.position.set(-1,1,2);scene.add(fill); + bodyGroups=model.bodies.map(()=>{const group=new THREE.Group();scene.add(group);return group;});visual=[];collision=[];const meshes=new Map(),dv=new DataView(geometry); + for(const mesh of model.meshes){const p=new Float32Array(mesh.vertex_count*3),idx=new Uint32Array(mesh.index_count);for(let i=0;i{const mesh=new THREE.Mesh(shape,material);mesh.position.fromArray(geom.position);const q=geom.quaternion_wxyz;mesh.quaternion.set(q[1],q[2],q[3],q[0]);bodyGroups[geom.body_id].add(mesh);return mesh;};if(rgba[3]>0&&geom.group<=2){const mesh=add(new THREE.MeshStandardMaterial({color:new THREE.Color().setRGB(...rgba.slice(0,3),THREE.LinearSRGBColorSpace),roughness:.68,metalness:geom.type==='mesh'?.12:0,transparent:rgba[3]<1,opacity:rgba[3],side:THREE.DoubleSide}));mesh.castShadow=geom.type!=='plane';mesh.receiveShadow=true;visual.push(mesh);}if(geom.collision){const mesh=add(new THREE.MeshStandardMaterial({color:0xb9774b,transparent:true,opacity:.4,depthWrite:false}));mesh.visible=false;collision.push(mesh);}} + const r=$('stage').getBoundingClientRect();camera.aspect=r.width/r.height;camera.updateProjectionMatrix();renderer.setSize(r.width,r.height,false);showFrame(0);cameraView('home');$('collision').setAttribute('aria-pressed','false');$('scene-state').textContent='NATIVE PHYSICS · RECORDED POSES'; +} +function human(key){return key.replaceAll('_',' ');} +function scalar(value){return typeof value==='number'?(Number.isInteger(value)?String(value):value.toFixed(2)):typeof value==='boolean'?(value?'Yes':'No'):String(value??'—');} +function eventTime(event){return Number(event.t??event.time_s??event.time??0);} +function renderEvents(){const ul=$('events');ul.replaceChildren();for(const event of trial.events){const li=document.createElement('li'),button=document.createElement('button'),time=document.createElement('time'),text=document.createElement('span');const t=eventTime(event);time.textContent=t.toFixed(2)+' s';text.textContent=event.message||human(event.type||event.event||'event');button.dataset.time=t;button.append(time,text);button.addEventListener('click',()=>{stop();let i=motion.times.findIndex(x=>x>=t);showFrame(i<0?motion.frame_count-1:i);});li.append(button);ul.append(li);}if(!trial.events.length){const li=document.createElement('li');li.className='events-empty';li.textContent='No discrete intervention events were recorded.';ul.append(li);}} +function fillResults(){const rows=$('results');rows.replaceChildren();for(const group of report.groups){const tr=document.createElement('tr');for(const value of [names[group.task],group.policy==='baseline'?'Baseline':'Feedback & recovery',group.successes+' / '+group.attempts,group.valid+' / '+group.attempts,Object.entries(group.outcomes).map(([k,n])=>human(k)+': '+n).join(' · ')]){const td=document.createElement('td');td.textContent=value;tr.append(td);}rows.append(tr);}} +async function loadTrial(){ + const gen=++generation;stop();document.querySelectorAll('#play,#timeline,#collision,#case,#policy,[data-task]').forEach(el=>el.disabled=true);$('loading').hidden=false;$('loading-message').textContent='Loading geometry and recorded motion.';$('stage').dataset.ready='loading'; + trial=report.attempts.find(row=>row.task===task&&row.case.id===$('case').value&&row.policy===$('policy').value);assert(trial,'Trial not found'); + $('outcome').textContent=human(trial.valid?(trial.metrics.outcome||(trial.success?'completed':'failed')):'invalid_attempt');$('outcome').dataset.success=trial.success&&trial.valid;$('outcome').dataset.valid=trial.valid;$('success').textContent=trial.success&&trial.valid?'Yes':'No';$('details').textContent=JSON.stringify({case:trial.case,metrics:trial.metrics,errors:trial.errors},null,2);$('receipt').href='trials/'+localPath(trial.id)+'.json'; + $('metric-a-label').textContent=task==='tool-reach'?'Shoe retrieved':'Interventions';$('metric-a').textContent=scalar(task==='tool-reach'?trial.metrics.retrieval_success:trial.metrics.intervention_count);$('metric-b-label').textContent=task==='tool-reach'?'Retained lift':'Peak lid contact · N';$('metric-b').textContent=scalar(task==='tool-reach'?trial.metrics.retained_lift_success:trial.metrics.peak_lid_robot_normal_force_n); + if(!trial.replay){throw new Error('This attempt has no valid replay. Its failure receipt remains downloadable.');} + const [m,p]=await Promise.all([json(trial.replay.model),json(trial.replay.motion)]);let geometry=geometryCache.get(m.geometry_binary.sha256);if(!geometry){geometry=await binary(m.geometry_binary);geometryCache.set(m.geometry_binary.sha256,geometry);}const positions=await binary(p.motion_binary);if(gen!==generation)return;validate(m,p,geometry,positions);model=m;motion=p;pose=new Float32Array(positions);setup(geometry);renderEvents();$('timeline').max=String(motion.frame_count-1);$('duration').textContent=motion.times.at(-1).toFixed(2)+' s';$('status').textContent=(report.split==='heldout'?'Held-out parameter case':'Development case')+' · '+human(trial.case.id)+' · '+(trial.policy==='baseline'?'Baseline':'Feedback & recovery');$('stage').dataset.ready='true';$('loading').hidden=true;document.querySelectorAll('#play,#timeline,#collision,#case,#policy,[data-task]').forEach(el=>el.disabled=false); +} +function setTask(next){task=next;document.querySelectorAll('[data-task]').forEach(button=>button.setAttribute('aria-pressed',String(button.dataset.task===task)));$('scene-title').textContent=names[task];$('experiment-title').textContent=names[task];$('task-description').textContent=task==='hinged-box'?'Reach toward the shoe, anticipate a closing lid, and withdraw when the clearance changes.':'A mounted rake brings a free shoe into the arm’s workspace. Retrieval and the subsequent grip are measured separately.';$('scope-note').textContent=task==='hinged-box'?'Completion means reaching the shoe-access waypoint and withdrawing. A safe abort does not count as task completion. Contact thresholds are synthetic test criteria, not injury limits.':'The rake starts mounted to the arm. Tool pickup and selection are not evaluated. The baseline has no tool, so this measures a combined tool-and-strategy change.';const seen=new Set();$('case').replaceChildren();for(const row of report.attempts.filter(r=>r.task===task)){if(seen.has(row.case.id))continue;seen.add(row.case.id);const option=document.createElement('option');option.value=row.case.id;option.textContent=human(row.case.id);$('case').append(option);}loadTrial().catch(fail);} +function fail(error){stop();$('loading').hidden=false;$('loading-message').textContent=error.message;$('stage').dataset.ready='error';$('status').textContent='Replay unavailable. The protocol and trial receipts remain accessible.';$('case').disabled=false;$('policy').disabled=false;document.querySelectorAll('[data-task]').forEach(el=>el.disabled=false);console.error(error);} +async function main(){assert(location.protocol!=='file:','Serve the export over HTTP');report=await json('benchmark.json');assert(report.schema==='dvidia.skill-prerequisites/v1'&&Array.isArray(report.attempts)&&report.attempts.length<=100,'Invalid benchmark');fillResults();const commit=report.source.commit;if(commit){assert(/^[a-f0-9]{40}$/.test(commit),'Invalid source commit');$('source').href='https://github.com/Dvidia-Inference/dvidia-training/tree/'+commit;}$('command').textContent='git clone https://github.com/Dvidia-Inference/dvidia-training.git\ncd dvidia-training\n'+(commit?'git checkout '+commit+'\n':'')+'python -m venv .venv\n# Activate .venv using your shell, then:\npython -m pip install ".[arm]"\ndvidia-robot-sim fetch piper --output robot-assets\ndvidia-prerequisites --assets robot-assets --output results --split '+report.split+'\npython -m http.server 8000 --directory results';document.querySelectorAll('[data-task]').forEach(button=>button.addEventListener('click',()=>setTask(button.dataset.task)));document.querySelectorAll('[data-camera]').forEach(button=>button.addEventListener('click',()=>{if(camera)cameraView(button.dataset.camera);}));$('case').addEventListener('change',()=>loadTrial().catch(fail));$('policy').addEventListener('change',()=>loadTrial().catch(fail));$('play').addEventListener('click',()=>{if(playing){stop();return;}if(frame===motion.frame_count-1)showFrame(0);playing=true;started=performance.now()-motion.times[frame]*1000;$('play').textContent='Pause trial';$('play').setAttribute('aria-pressed','true');requestRender();});$('timeline').addEventListener('input',()=>{stop();showFrame(Number($('timeline').value));});$('collision').addEventListener('click',()=>{const on=$('collision').getAttribute('aria-pressed')!=='true';$('collision').setAttribute('aria-pressed',String(on));visual.forEach(m=>m.visible=!on);collision.forEach(m=>m.visible=on);$('scene-state').textContent=on?'COLLISION GEOMETRY · RECORDED POSES':'NATIVE PHYSICS · RECORDED POSES';requestRender();});$('canvas').addEventListener('keydown',event=>{if(event.key==='Home'||event.key==='h'){event.preventDefault();cameraView('home');}});document.addEventListener('visibilitychange',()=>{if(document.hidden)stop();});document.querySelectorAll('[data-task]').forEach(el=>el.hidden=!report.attempts.some(row=>row.task===el.dataset.task));setTask(report.attempts[0].task);} +main().catch(fail); diff --git a/src/dvidia_training/tool_reach.py b/src/dvidia_training/tool_reach.py new file mode 100644 index 0000000..d82901c --- /dev/null +++ b/src/dvidia_training/tool_reach.py @@ -0,0 +1,228 @@ +"""Authored prerequisite experiment: pull an out-of-workspace shoe with a rake. + +The lightweight rake is a declared pre-equipped rigid fixture, not a discovered +or grasped tool. Shoes are free bodies throughout. Only native joint actuators +move the arm; no shoe weld, teleport, applied wrench, or hidden carrying force +is used. All observations are privileged simulator truth. The 0.54 m limit is +this controller's operating envelope, not a proof of global IK infeasibility. +""" +from __future__ import annotations +from copy import deepcopy +import math +import time +from . import workstation as ws, reference_sim as sim + +TASK = 'out-of-reach-shoe' +LIFT_HEIGHT = .28 # Uniform development-selected waypoint; within workstation bounds. +# Frozen before controller tuning. Heldout configurations must not be used to +# choose thresholds or waypoints; they vary several factors simultaneously. +_CASES = { + 'development': [ + dict(id='reach-dev-standard', shoe_x=.72, shoe_y=-.10, mass=.30, friction=.60, tool_length=.35, lateral_error=.00), + dict(id='reach-dev-offset', shoe_x=.72, shoe_y=-.12, mass=.30, friction=.70, tool_length=.35, lateral_error=.065), + dict(id='reach-dev-heavy', shoe_x=.73, shoe_y=-.08, mass=.50, friction=.95, tool_length=.36, lateral_error=.00), + dict(id='reach-dev-miss-retry', shoe_x=.72, shoe_y=-.10, mass=.30, friction=.60, tool_length=.35, lateral_error=.12, purpose='development recovery branch coverage added after first pilot'), + dict(id='reach-dev-short', shoe_x=.73, shoe_y=-.10, mass=.30, friction=.60, tool_length=.16, lateral_error=.00), + ], + 'heldout': [ + dict(id='reach-heldout-light', shoe_x=.705, shoe_y=-.09, mass=.22, friction=.45, tool_length=.34, lateral_error=.025), + dict(id='reach-heldout-offset', shoe_x=.725, shoe_y=-.115, mass=.38, friction=.80, tool_length=.36, lateral_error=-.075), + dict(id='reach-heldout-heavy', shoe_x=.735, shoe_y=-.075, mass=.55, friction=1.05, tool_length=.37, lateral_error=.035), + dict(id='reach-heldout-short', shoe_x=.72, shoe_y=-.105, mass=.27, friction=.55, tool_length=.18, lateral_error=.015), + ]} + + +def cases(split='development'): + if split not in _CASES: raise ValueError('split must be development or heldout') + return [dict(row, split=split) for row in deepcopy(_CASES[split])] + + +def _validate_case(case): + limits = {'shoe_x':(.69,.75), 'shoe_y':(-.15,-.05), 'mass':(.1,1.), + 'friction':(.1,1.5), 'tool_length':(.1,.4), 'lateral_error':(-.12,.12)} + if not isinstance(case,dict) or not isinstance(case.get('id'),str): raise ValueError('Expected a named case') + for key,(low,high) in limits.items(): + value=case.get(key) + if type(value) not in (int,float) or not math.isfinite(value) or not low<=value<=high: + raise ValueError('Invalid case parameter: '+key) + + +def build_model(assets, case, policy='recovery'): + """Build one native model. Baseline is explicitly the no-tool ablation.""" + if policy not in ('baseline', 'recovery'): raise ValueError('Unknown policy') + _validate_case(case) + mj, np = sim._native_imports() + spec=ws._spec(assets) + shoe=spec.body(ws.SHOE) + shoe.pos=[case['shoe_x'],case['shoe_y'],.012] + for geom in shoe.geoms: + geom.mass *= case['mass']/.30 + geom.friction=[case['friction'],.005,.0001] + if policy=='recovery': + # At the nominal TCP orientation this frame is aligned with the world. + # Its fixed mount is explicit. There is no tool/shoe equality constraint. + quat=list(ws.ORIENTATION);quat[1:]=[-q for q in quat[1:]] + tool=spec.body('link6').add_body(name='reach_rake',pos=[0,0,.12003],quat=quat) + length=case['tool_length'] + tool.add_geom(name='reach_rake_mount',type=mj.mjtGeom.mjGEOM_BOX, + pos=[-.03,0,.06],size=[.03,.009,.009],mass=.01,rgba=[.18,.27,.27,1],contype=1,conaffinity=1) + tool.add_geom(name='reach_rake_shaft',type=mj.mjtGeom.mjGEOM_BOX, + pos=[length/2,0,.060],size=[length/2,.009,.009],mass=.08, + rgba=[.72,.46,.20,1],contype=1,conaffinity=1,condim=4,friction=[.7,.005,.0001]) + tool.add_geom(name='reach_rake_paddle',type=mj.mjtGeom.mjGEOM_BOX, + pos=[length,0,.005],size=[.010,.035,.055],mass=.035, + rgba=[.18,.27,.27,1],contype=1,conaffinity=1,condim=4,friction=[.7,.005,.0001]) + return mj.MjModel.from_xml_string(spec.to_xml(),assets=spec.assets) + + +def run_case(assets, case, policy='baseline', record=True): + """Run a bounded authored policy with 2 ms evidence and 20 ms commands.""" + if policy not in ('baseline','recovery'): raise ValueError('Unknown policy') + mj,np=sim._native_imports() + wall=time.perf_counter() + model=build_model(assets,case,policy);data=ws.initialize(model) + tcp,shoe=ws._ids(model) + tool=mj.mj_name2id(model,mj.mjtObj.mjOBJ_BODY,'reach_rake') + fingers=[mj.mj_name2id(model,mj.mjtObj.mjOBJ_BODY,name) for name in ('link7','link8')] + events=[];frames=[];steps=0;phase='settle';target=np.array(ws.HOME_TARGET);jaw=.035 + desired=data.ctrl.copy();peak=0.;impulse=0.;contact_steps=0;peak_tick=0. + policy_ms=[];all_peak=0.;finger_forces=[0.,0.];force_peak_by_phase={};last_force=0.;native_trace=[];world_force=0. + max_delta=0.;max_tracking=0.;lift_peak=0.;recovery_attempts=0;help_requested=False + initial=np.array([case['shoe_x'],case['shoe_y'],0.]) + retrieved=False;grasp_attempted=False;lift_retained=False;valid=True + def event(kind,**values): + message=str(values.get('reason',values.get('name',kind))).replace('_',' ') + events.append({'t':round(float(data.time),6),'type':kind,'message':message,**values}) + def tick(): + nonlocal steps,desired,peak,impulse,contact_steps,peak_tick,max_delta,max_tracking,lift_peak,valid,all_peak,finger_forces,last_force,world_force + if steps%10==0: + started=time.perf_counter();desired=ws.controller_action(model,data,target.tolist(),jaw) + policy_ms.append((time.perf_counter()-started)*1000) + old=data.ctrl.copy() + data.ctrl[:6]+=np.clip(desired[:6]-data.ctrl[:6],-1.5*.002,1.5*.002) + data.ctrl[6]+=np.clip(desired[6]-data.ctrl[6],-.05*.002,.05*.002) + max_delta=max(max_delta,float(np.max(np.abs(data.ctrl[:6]-old[:6])))) + mj.mj_step(model,data);mj.mj_forward(model,data);steps+=1 + if not np.isfinite(data.qpos).all() or not np.isfinite(data.qvel).all() or any(w.number for w in data.warning): + valid=False;raise RuntimeError('Invalid native state') + force=0.;all_force=0.;finger_forces=[0.,0.];world_force=0. + for i in range(data.ncon): + c=data.contact[i]; b1=int(model.geom_bodyid[c.geom1]);b2=int(model.geom_bodyid[c.geom2]) + if shoe in (b1,b2): + other=b2 if b1==shoe else b1 + wrench=np.zeros(6);mj.mj_contactForce(model,data,i,wrench);normal=max(0.,float(wrench[0])) + if other!=0:all_force+=normal + else:world_force+=normal + if other==tool and tool>=0:force+=normal + if other in fingers:finger_forces[fingers.index(other)]+=normal + last_force=force;all_peak=max(all_peak,all_force) + force_peak_by_phase[phase]=max(force_peak_by_phase.get(phase,0.),all_force) + native_trace.append([round(float(data.time),6),force,all_force,*finger_forces,*data.xpos[shoe].tolist(),world_force]) + if force>0: + contact_steps+=1;impulse+=force*.002 + if force>peak:peak=force;peak_tick=float(data.time) + max_tracking=max(max_tracking,float(np.linalg.norm(data.site_xpos[tcp]-target))) + if phase in ('lift','direct_lift'):lift_peak=max(lift_peak,float(data.xpos[shoe,2])) + if record and steps%10==0: + frames.append({'t':round(float(data.time),6),'body_poses':np.column_stack((data.xpos,data.xquat)).tolist(), + 'phase':phase,'target':target.tolist(),'shoe_position':data.xpos[shoe].tolist(), + 'qpos_rad_m':data.qpos.tolist(),'qvel_rad_m_s':data.qvel.tolist(), + 'issued_ctrl':data.ctrl.tolist(),'requested_joint_target':desired.tolist(), + 'tcp_position':data.site_xpos[tcp].tolist(),'tool_shoe_force_n':force, + 'finger_normal_forces_n':list(finger_forces),'world_shoe_force_n':world_force}) + def go(name,point,seconds=1.5,opening=.035): + nonlocal phase,target,jaw + phase=name;target=np.array(point,dtype=float);jaw=opening;event('phase',name=name,target=target.tolist()) + for _ in range(round(seconds/.002)): tick() + def travel(name,end,seconds=2.,opening=.035): + nonlocal phase,target,jaw + phase=name;jaw=opening;start=np.clip(data.site_xpos[tcp], [b[0] for b in ws.BOUNDS], [b[1] for b in ws.BOUNDS]);end=np.asarray(end) + event('phase',name=name,target=end.tolist()) + for i in range(round(seconds/.002)): + f=(i+1)/round(seconds/.002);f=f*f*(3-2*f);target=start*(1-f)+end*f;tick() + event('assumptions',pre_equipped_rigid_tool=policy=='recovery',privileged_observations=True, + shoe_attachment=False,controller_reach_limit_x_m=.54,tool_acquisition_tested=False) + go('settle',ws.HOME_TARGET,.4) + if policy=='baseline': + grasp_attempted=True + event('direct_reach_attempt',desired_x_m=float(data.xpos[shoe,0]),clipped_x_m=.54) + travel('direct_reach',[.54,case['shoe_y'],.075],2.5) + go('direct_close',[.54,case['shoe_y'],.075],1.,0.) + go('direct_lift',[.50,case['shoe_y'],.20],1.5,0.) + event('direct_reach_failed',shoe_x_m=float(data.xpos[shoe,0])) + else: + length=case['tool_length'] + # Need room for the paddle behind the entire shoe, not merely its centre. + requested=float(data.xpos[shoe,0])+.14+.025-length + if requested>.54: + help_requested=True;event('help_requested',reason='tool_cannot_reach_far_edge',required_tcp_x_m=requested) + go('hold_for_help',ws.HOME_TARGET,.6) + else: + for attempt in range(2): + if attempt:recovery_attempts+=1 + y=float(data.xpos[shoe,1])+(case['lateral_error'] if attempt==0 else 0.) + far=float(data.xpos[shoe,0])+.14+.025-length + far=float(np.clip(far,.18,.54)) + travel('approach_tool',[far,y,.25],1.8) + travel('lower_tool',[far,y,.075],1.0) + travel('pull_shoe',[.20,y,.075],3.0) + go('verify_pull',[.20,y,.075],.4) + displacement=initial[0]-float(data.xpos[shoe,0]) + retrieved=bool(float(data.xpos[shoe,0])<=.53 and abs(float(data.xpos[shoe,1]))<=.21 and abs(float(data.xpos[shoe,2]))<.035) + event('retrieval_check',attempt=attempt+1,retrieved=retrieved,shoe_x_m=float(data.xpos[shoe,0]),displacement_m=displacement) + if retrieved: break + event('recovery',reason='insufficient_retrieval',action='recenter_and_retry' if attempt==0 else 'stop_and_ask') + go('release_tool',[.20,y,.22],1.) + if retrieved: + # With the rake lifted clear, try the actual jaw around the upper. + # This fixture reduces dexterity. Retained lift is measured, never + # inferred from retrieval or closure commands. + go('clear_rake',[.24,case['shoe_y'],.25],1.2) + sx,sy=float(data.xpos[shoe,0]),float(data.xpos[shoe,1]) + grasp_attempted=True + travel('grasp_approach',[float(np.clip(sx-.045,.18,.54)),sy,.060],1.8) + go('close_jaws',[float(np.clip(sx-.045,.18,.54)),sy,.060],1.,0.) + travel('lift',[float(np.clip(sx-.045,.18,.54)),sy,LIFT_HEIGHT],1.5,0.) + phase='lift';target=np.array([float(np.clip(sx-.045,.18,.54)),sy,LIFT_HEIGHT]);jaw=0. + retained=[] + for _ in range(250):tick();retained.append(float(data.xpos[shoe,2])>.035 and min(finger_forces)>.01 and last_force<.01 and world_force<.01) + lift_retained=all(retained) + event('lift_check',retained=lift_retained,shoe_bottom_z_m=float(data.xpos[shoe,2])) + if not lift_retained: + help_requested=True;event('help_requested',reason='retrieved_but_jaw_lift_not_retained') + else: + help_requested=True;event('help_requested',reason='bounded_recovery_exhausted') + final=data.xpos[shoe].copy() + shoe_dof=int(model.jnt_dofadr[int(model.body_jntadr[shoe])]) + final_speed=float(np.linalg.norm(data.qvel[shoe_dof:shoe_dof+3])) + success=retrieved and lift_retained + metrics={'retrieval_success':retrieved,'grasp_attempted':grasp_attempted,'retained_lift_success':lift_retained, + 'final_shoe_speed_m_s':final_speed, + 'shoe_displacement_x_m':float(initial[0]-final[0]),'final_shoe_position_m':final.tolist(), + 'peak_lift_m':lift_peak,'recovery_attempts':recovery_attempts,'help_requested':help_requested, + 'peak_tool_shoe_force_n':peak,'peak_tool_shoe_force_time_s':peak_tick,'tool_shoe_impulse_ns':impulse, + 'tool_shoe_contact_ticks':contact_steps,'physics_timestep_s':.002,'policy_interval_s':.02, + 'max_joint_command_delta_rad':max_delta,'max_tracking_error_m':max_tracking, + 'simulation_seconds':float(data.time),'wall_seconds':time.perf_counter()-wall, + 'solver_warnings':sum(int(w.number) for w in data.warning),'native_steps':steps, + 'shoe_external_force_used':bool(np.any(data.xfrc_applied) or np.any(data.qfrc_applied)), + 'shoe_equality_constraints':int(sum(shoe in (int(model.eq_obj1id[i]),int(model.eq_obj2id[i])) for i in range(model.neq) if int(model.eq_type[i]) in (0,1))), + 'recovery_count':recovery_attempts,'intervention_count':int(help_requested), + 'peak_contact_force_n':all_peak,'contact_force_scope':'sum of normal shoe-to-robot/tool forces, excluding table', + 'force_peak_by_phase_n':force_peak_by_phase, + 'policy_compute_p50_ms':float(np.percentile(policy_ms,50)), + 'policy_compute_p95_ms':float(np.percentile(policy_ms,95)), + 'policy_compute_max_ms':max(policy_ms),'wall_includes_model_compile':True, + 'recorded_state_scope':'privileged native state; qpos has 6 arm radians, 2 jaw metres, shoe XYZ metres and quaternion wxyz; qvel has 6 arm rad/s, 2 jaw m/s, shoe linear m/s and angular rad/s; controls are 6 joint radians plus jaw metres; requested targets update every20ms and issued controls are rate limited every2ms', + 'retention_criterion':'shoe bottom >35 mm with both fingers contacting, tool and world force each <0.01 N for final 500 ms', + 'no_tool_baseline':policy=='baseline','tool_pre_equipped':policy=='recovery'} + metrics['outcome']=('completed' if success else 'failed_direct_reach' if policy=='baseline' + else 'retrieved_lift_failed' if retrieved + else 'deferred_insufficient_reach' if any(e.get('reason')=='tool_cannot_reach_far_edge' for e in events) + else 'recovery_exhausted') + metrics['real_time_factor']=metrics['simulation_seconds']/metrics['wall_seconds'] + return {'task':TASK,'case':deepcopy(case),'policy':policy,'success':success,'valid':valid, + 'metrics':metrics,'events':events,'frames':frames,'model':model, + 'native_trace':native_trace,'native_trace_columns':['t_s','tool_shoe_force_n','shoe_robot_force_n', + 'left_finger_force_n','right_finger_force_n','shoe_x_m','shoe_y_m','shoe_z_m','world_shoe_force_n'], + 'control_compute_ms':policy_ms} diff --git a/tests/test_hinged_shoebox.py b/tests/test_hinged_shoebox.py new file mode 100644 index 0000000..e7a0ab8 --- /dev/null +++ b/tests/test_hinged_shoebox.py @@ -0,0 +1,113 @@ +"""Frozen inputs, native passive-hinge dynamics and failure/recovery evidence.""" +import math +import os +from pathlib import Path +import unittest + +from dvidia_training import hinged_shoebox as box, workstation as ws, reference_sim as sim + + +class HingedBoxProtocolTests(unittest.TestCase): + def test_cases_are_independent_frozen_and_split_specific(self): + development=box.cases();heldout=box.cases('heldout') + self.assertEqual(len(development),4) + self.assertEqual(len(heldout),4) + self.assertFalse({c['id'] for c in development}&{c['id'] for c in heldout}) + development[0]['lid_mass_kg']=99 + self.assertEqual(box.cases()[0]['lid_mass_kg'],.12) + for invalid in ('test','all',None): + with self.assertRaises(ValueError):box.cases(invalid) + for invalid in (None,{},development[0],{**box.cases()[0],'extra':True}): + with self.assertRaises(ValueError):box._validate_case(invalid) + + def test_guard_uses_motion_and_robot_volume_not_case_name(self): + self.assertTrue(box.risk_observation(math.radians(75),-.1,box.START)) + self.assertFalse(box.risk_observation(math.radians(75),.1,box.START)) + self.assertFalse(box.risk_observation(math.radians(118),-.1,box.START)) + self.assertFalse(box.risk_observation(math.radians(75),-.1,[.36,-.40,.2])) + self.assertFalse(box.risk_observation(math.radians(75),-.1,[.70,-.20,.2])) + self.assertFalse(box.risk_observation(math.radians(75),-.1,[.36,-.20,.50])) + + def test_policy_rejects_unknown_before_loading_assets(self): + with self.assertRaises(ValueError): + box.run_case('/missing',box.cases()[0],policy='learned') + with self.assertRaises(ValueError): + box.run_case('/missing',box.cases()[0],record='yes') + + +@unittest.skipUnless(os.environ.get('DVIDIA_ROBOT_PROFILE_ASSETS'),'Set DVIDIA_ROBOT_PROFILE_ASSETS to pinned PiPER assets') +class NativeHingedBoxTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.assets=Path(os.environ['DVIDIA_ROBOT_PROFILE_ASSETS']) + cls.mj,cls.np=sim._native_imports() + cls.results={} + for case in box.cases(): + for policy in ('baseline','recovery'): + cls.results[(case['id'],policy)]=box.run_case(cls.assets,case,policy) + + def test_exact_robot_actuators_and_unactuated_native_hinge(self): + baseline=ws.build_model(self.assets) + model=self.results[('open-light','baseline')]['model'] + self.assertEqual((model.nq,model.nv,model.nu,model.neq,model.nmocap),(16,15,7,1,0)) + for key in ('actuator_ctrlrange','actuator_forcerange','actuator_gainprm','actuator_biasprm','actuator_trnid'): + self.np.testing.assert_array_equal(getattr(model,key),getattr(baseline,key)) + hinge=model.joint(box.HINGE) + self.assertEqual(int(model.jnt_type[hinge.id]),int(self.mj.mjtJoint.mjJNT_HINGE)) + self.np.testing.assert_allclose(model.jnt_range[hinge.id],[0,math.radians(120)]) + self.assertNotIn(hinge.id,model.actuator_trnid[:,0]) + self.assertEqual(float(model.body_gravcomp[model.body(box.LID).id]),0.) + + def test_gravity_closes_lid_and_guard_counts_safe_abort_not_task_success(self): + baseline=self.results[('falling-light','baseline')] + recovery=self.results[('falling-light','recovery')] + self.assertTrue(baseline['valid'] and recovery['valid']) + self.assertTrue(baseline['metrics']['lid_robot_collision']) + self.assertTrue(any(e['type']=='hazardous_contact' for e in baseline['events'])) + self.assertFalse(recovery['success']) + self.assertTrue(recovery['metrics']['safe_abort']) + self.assertTrue(recovery['metrics']['help_requested']) + self.assertFalse(recovery['metrics']['lid_robot_collision']) + self.assertLess(recovery['frames'][-1]['lid_angle_rad'],math.radians(12)) + self.assertEqual(recovery['metrics']['outcome'],'safe_abort') + self.assertLessEqual(recovery['metrics']['first_response_latency_s'],box.CONTROL_DT) + + def test_open_box_completes_and_transient_can_resume_without_false_success(self): + for policy in ('baseline','recovery'): + result=self.results[('open-light',policy)] + self.assertTrue(result['success']) + self.assertFalse(result['metrics']['help_requested']) + result=self.results[('transient-closing','recovery')] + self.assertTrue(result['success']) + self.assertEqual(result['metrics']['resumed_count'],1) + kinds=[e['type'] for e in result['events']] + self.assertLess(kinds.index('withdrawal_started'),kinds.index('access_resumed')) + self.assertLess(kinds.index('access_resumed'),kinds.index('inspection_waypoint_reached')) + self.assertEqual(result['metrics']['outcome'],'recovered') + # Baseline also succeeds here: our conservative interruption is costly, + # not a task-success improvement. This deliberate tradeoff stays visible. + self.assertTrue(self.results[('transient-closing','baseline')]['success']) + + def test_every_native_step_is_observed_and_peak_matches_dense_trace(self): + result=self.results[('falling-heavy','baseline')] + trace=self.np.asarray(result['native_trace']) + self.assertEqual(len(trace),int(box.DURATION/box.TIMESTEP)+1) + self.np.testing.assert_allclose(self.np.diff(trace[:,0]),box.TIMESTEP,atol=1e-12) + self.assertAlmostEqual(float(trace[:,3].max()),result['metrics']['peak_lid_robot_normal_force_n']) + self.assertTrue(self.np.isfinite(trace).all()) + self.assertEqual(len(result['frames']),int(box.DURATION/box.CONTROL_DT)+1) + for frame in result['frames']: + self.assertTrue(self.np.isfinite(frame['body_poses']).all()) + self.assertEqual(len(frame['body_poses']),result['model'].nbody) + for key,size in (('qpos_rad_m',16),('qvel_rad_m_s',15),('issued_ctrl',7),('requested_joint_target',7)): + self.assertEqual(len(frame[key]),size) + self.assertTrue(self.np.isfinite(frame[key]).all()) + self.assertAlmostEqual(frame['qpos_rad_m'][-1],frame['lid_angle_rad']) + self.assertAlmostEqual(frame['qvel_rad_m_s'][-1],frame['lid_velocity_rad_s']) + # This contact force peak falls between 20 ms frames; dense observation + # protects precisely the failure information sparse episode tapes lose. + self.assertGreater(result['metrics']['peak_lid_robot_normal_force_n'],max(f['lid_robot_force_n'] for f in result['frames'])) + self.assertAlmostEqual(result['metrics']['peak_lid_robot_normal_force_n'],max(f['native_window_peak_force_n'] for f in result['frames'])) + + +if __name__=='__main__':unittest.main() diff --git a/tests/test_prerequisite_benchmark.py b/tests/test_prerequisite_benchmark.py new file mode 100644 index 0000000..f59077b --- /dev/null +++ b/tests/test_prerequisite_benchmark.py @@ -0,0 +1,93 @@ +"""Failure retention and comparison semantics for prerequisite experiments.""" +from pathlib import Path +import json +import tempfile +import unittest +from unittest.mock import patch +from dvidia_training import prerequisite_benchmark as bench + +class PrerequisiteBenchmarkTests(unittest.TestCase): + def test_frozen_protocol_has_every_matched_pair(self): + p=bench.protocol('heldout') + self.assertEqual(len(p['attempts']),16) + for task in bench.TASKS: + rows=[r for r in p['attempts'] if r['task']==task] + self.assertEqual(len(rows),8) + for case in {r['case']['id'] for r in rows}: + self.assertEqual({r['policy'] for r in rows if r['case']['id']==case},set(bench.POLICIES)) + for split in ('all',None,'training'): + with self.assertRaises(ValueError):bench.protocol(split) + + def test_safe_abort_is_not_task_success_and_nuisance_is_paired(self): + case={'id':'fixture'} + a={'task':'hinged-box','policy':'baseline','case':case,'valid':True,'success':True, + 'metrics':{'lid_robot_collision':False,'intervention_count':0,'completion_time_s':1.6},'wall_seconds':1} + b={**a,'policy':'recovery','metrics':{'lid_robot_collision':False,'intervention_count':1,'completion_time_s':2.32}} + pair=bench.paired_comparisons([a,b])[0] + self.assertTrue(pair['nuisance_interruption']) + self.assertFalse(pair['lid_contact_avoided']) + self.assertAlmostEqual(pair['completion_delay_s'],.72) + b.update(success=False,metrics={'outcome':'safe_abort'}) + group=bench.summarize([b])[0] + self.assertEqual(group['successes'],0) + self.assertEqual(group['outcomes'],{'safe_abort':1}) + + def test_bad_metric_does_not_drop_later_attempts_or_leak_private_path(self): + class Fake: + @staticmethod + def cases(split):return [{'id':'bad'},{'id':'exception'}] + @staticmethod + def run_case(assets,case,policy,record): + if case['id']=='exception':raise ValueError('/Users/private/secret') + return {'success':False,'valid':True,'metrics':{'peak':float('nan')},'events':[], + 'model':None,'frames':[], 'native_trace':[[0,float('nan')]]} + with tempfile.TemporaryDirectory() as directory: + out=Path(directory)/'evidence' + with patch.object(bench,'modules',return_value={'hinged-box':Fake}), \ + patch.object(bench,'export_trial',return_value={}), \ + patch.object(bench,'implementation_hashes',return_value={}), \ + patch.object(bench.asset_preview,'_licenses',return_value=({},{})): + result=bench.benchmark('/private/assets',out,split='development') + self.assertEqual(len(result['attempts']),4) + self.assertTrue(all(not r['valid'] and not r['success'] for r in result['attempts'])) + self.assertTrue(all(r['errors'] for r in result['attempts'])) + self.assertNotIn('/Users/',(out/'benchmark.json').read_text()) + self.assertEqual(len(list((out/'trials').glob('*.json'))),4) + seal=json.loads((out/'integrity.json').read_text()) + self.assertIn('benchmark.json',seal['files']) + + def test_export_failure_counts_invalid_and_preserves_reported_outcome(self): + class Fake: + @staticmethod + def cases(split):return [{'id':'completed-before-export'}] + @staticmethod + def run_case(assets,case,policy,record): + return {'success':True,'valid':True,'metrics':{'outcome':'completed','peak_force_n':2.5}, + 'events':[{'t':1.,'type':'completion','message':'Waypoint reached'}], + 'native_trace':[[1.,2.5]],'native_trace_columns':['t','force_n'], + 'model':None,'frames':[]} + with tempfile.TemporaryDirectory() as directory: + out=Path(directory)/'evidence' + with patch.object(bench,'modules',return_value={'hinged-box':Fake}), \ + patch.object(bench,'export_trial',side_effect=ValueError('Invalid replay')), \ + patch.object(bench,'implementation_hashes',return_value={}), \ + patch.object(bench.asset_preview,'_licenses',return_value=({},{})): + result=bench.benchmark('/private/assets',out,split='development') + self.assertEqual(len(result['attempts']),2) + for group in result['groups']: + self.assertEqual(group['valid'],0) + self.assertEqual(group['successes'],0) + self.assertEqual(group['outcomes'],{'invalid_attempt':1}) + for row in result['attempts']: + self.assertFalse(row['valid']);self.assertFalse(row['success']) + self.assertEqual(row['metrics'],{'outcome':'completed','peak_force_n':2.5}) + self.assertEqual(row['events'][0]['message'],'Waypoint reached') + receipt=json.loads((out/'trials'/(row['id']+'.json')).read_text()) + self.assertEqual(receipt['native_trace'],[[1.,2.5]]) + self.assertTrue(receipt['errors']) + + def test_output_refuses_existing_directory(self): + with tempfile.TemporaryDirectory() as directory: + with self.assertRaises(ValueError):bench.benchmark('/missing',directory) + +if __name__=='__main__':unittest.main() diff --git a/tests/test_tool_reach.py b/tests/test_tool_reach.py new file mode 100644 index 0000000..e3f6ba2 --- /dev/null +++ b/tests/test_tool_reach.py @@ -0,0 +1,109 @@ +"""Causal native checks for the out-of-workspace prerequisite pilot.""" +import math +import os +from pathlib import Path +import unittest +from unittest.mock import patch + +from dvidia_training import tool_reach as reach, reference_sim as sim + + +class ReachCaseTests(unittest.TestCase): + def test_frozen_splits_are_disjoint_and_return_independent_values(self): + dev, held = reach.cases(), reach.cases('heldout') + self.assertFalse({x['id'] for x in dev} & {x['id'] for x in held}) + dev[0]['shoe_x']=999 + self.assertLess(reach.cases()[0]['shoe_x'], 1.) + self.assertTrue(all(x['split']=='heldout' for x in held)) + with self.assertRaises(ValueError): reach.cases('test') + + def test_nonfinite_or_unbounded_case_is_rejected_before_loading_assets(self): + for key,value in [('mass',-1),('tool_length',float('nan')),('shoe_x',2),('friction',True)]: + case=dict(reach.cases()[0],**{key:value}) + with self.subTest(key=key),self.assertRaises(ValueError):reach.build_model('/missing',case) + with self.assertRaises(ValueError):reach.run_case('/missing',reach.cases()[0],'oracle') + + +@unittest.skipUnless(os.environ.get('DVIDIA_ROBOT_PROFILE_ASSETS'), 'Set DVIDIA_ROBOT_PROFILE_ASSETS to pinned assets') +class NativeReachTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.assets=Path(os.environ['DVIDIA_ROBOT_PROFILE_ASSETS']) + cls.mj,cls.np=sim._native_imports() + cls.standard=reach.run_case(cls.assets,reach.cases()[0],'recovery') + + def test_retrieval_requires_tool_contact_and_free_shoe_is_never_attached(self): + r=self.standard;m=r['model'];shoe=self.mj.mj_name2id(m,self.mj.mjtObj.mjOBJ_BODY,'shoe_trainer_left') + self.assertEqual(m.jnt_type[m.body_jntadr[shoe]],self.mj.mjtJoint.mjJNT_FREE) + self.assertEqual(m.body_gravcomp[shoe],0) + self.assertEqual(m.neq,1) # Original gripper coupling, not a shoe constraint. + self.assertTrue(r['metrics']['retrieval_success']) + self.assertGreater(r['metrics']['tool_shoe_contact_ticks'],0) + self.assertGreater(r['metrics']['shoe_displacement_x_m'],.20) + self.assertFalse(r['metrics']['shoe_external_force_used']) + self.assertEqual(r['metrics']['shoe_equality_constraints'],0) + disabled=reach.build_model(self.assets,reach.cases()[0]) + tool=self.mj.mj_name2id(disabled,self.mj.mjtObj.mjOBJ_BODY,'reach_rake') + disabled.geom_contype[disabled.geom_bodyid==tool]=0 + disabled.geom_conaffinity[disabled.geom_bodyid==tool]=0 + with patch.object(reach,'build_model',return_value=disabled): + control=reach.run_case(self.assets,reach.cases()[0],'recovery',False) + self.assertFalse(control['metrics']['retrieval_success']) + self.assertLess(abs(control['metrics']['shoe_displacement_x_m']),.001) + + def test_no_tool_control_fails_and_short_tool_aborts_without_claiming_success(self): + baseline=reach.run_case(self.assets,reach.cases()[0],'baseline',False) + self.assertFalse(baseline['success']) + self.assertFalse(baseline['metrics']['retrieval_success']) + self.assertTrue(baseline['metrics']['no_tool_baseline']) + short=next(c for c in reach.cases() if c['id']=='reach-dev-short') + result=reach.run_case(self.assets,short,'recovery',False) + self.assertFalse(result['success']);self.assertEqual(result['metrics']['outcome'],'deferred_insufficient_reach') + self.assertTrue(any(e.get('reason')=='tool_cannot_reach_far_edge' for e in result['events'])) + self.assertEqual(result['metrics']['tool_shoe_contact_ticks'],0) + + def test_actual_miss_is_detected_before_retry_and_recovers_retrieval(self): + case=next(c for c in reach.cases() if c['id']=='reach-dev-miss-retry') + r=reach.run_case(self.assets,case,'recovery',False) + checks=[e for e in r['events'] if e['type']=='retrieval_check'] + self.assertEqual([e['retrieved'] for e in checks],[False,True]) + self.assertEqual(r['metrics']['recovery_count'],1) + self.assertTrue(r['metrics']['retrieval_success']) + self.assertFalse(r['success']) # Retrieval does not imply retained lift. + + def test_lift_metric_requires_contact_retention_not_height_alone(self): + self.assertFalse(self.standard['success']) + self.assertFalse(self.standard['metrics']['retained_lift_success']) + self.assertGreater(self.standard['metrics']['peak_lift_m'],.005) + heavy=next(c for c in reach.cases() if c['id']=='reach-dev-heavy') + # Retain the observed false-positive as a regression: the original low + # lift tilted the shoe while the toe still received table support. + with patch.object(reach,'LIFT_HEIGHT',.20): + low=reach.run_case(self.assets,heavy,'recovery') + self.assertFalse(low['success']) + self.assertGreater(low['metrics']['peak_lift_m'],.07) + self.assertTrue(any(row[-1]>.01 for row in low['native_trace'][-250:])) + r=reach.run_case(self.assets,heavy,'recovery') + self.assertTrue(r['success']) + for row in r['native_trace'][-250:]: + self.assertGreater(row[7],.035) + self.assertGreater(min(row[3:5]),.01) + self.assertLess(row[1],.01) + self.assertLess(row[-1],.01) + + def test_native_state_finite_commands_bounded_and_replay_deterministic(self): + r=self.standard + self.assertEqual(r['metrics']['solver_warnings'],0) + self.assertLessEqual(r['metrics']['max_joint_command_delta_rad'],.00300000001) + self.assertEqual(r['metrics']['physics_timestep_s'],.002) + self.assertEqual(len(r['native_trace']),r['metrics']['native_steps']) + self.assertAlmostEqual(max(row[2] for row in r['native_trace']),r['metrics']['peak_contact_force_n']) + self.assertEqual(r['metrics']['policy_interval_s'],.02) + for frame in r['frames']: + self.assertTrue(all(math.isfinite(v) for row in frame['body_poses'] for v in row)) + self.assertEqual(len(frame['body_poses']),r['model'].nbody) + again=reach.run_case(self.assets,reach.cases()[0],'recovery') + self.assertEqual(r['events'],again['events']) + self.assertEqual(r['frames'],again['frames']) + +if __name__=='__main__': unittest.main() diff --git a/viewer/build-prerequisites.mjs b/viewer/build-prerequisites.mjs new file mode 100644 index 0000000..493a2d8 --- /dev/null +++ b/viewer/build-prerequisites.mjs @@ -0,0 +1,8 @@ +import {createRequire} from 'node:module'; +import {fileURLToPath} from 'node:url'; +import path from 'node:path'; +const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..'); +const require=createRequire(path.join(root,'viewer/package.json')); +const {build}=require('esbuild'); +await build({entryPoints:[path.join(root,'src/dvidia_training/prerequisite_lab.js')],outfile:path.join(root,'src/dvidia_training/prerequisite_lab.bundle.js'),bundle:true,minify:true,format:'iife',target:['es2020'],platform:'browser',alias:{'three':path.join(root,'viewer/node_modules/three/build/three.module.js'),'three/addons/controls/OrbitControls.js':path.join(root,'viewer/node_modules/three/examples/jsm/controls/OrbitControls.js')},nodePaths:[path.join(root,'viewer/node_modules')],legalComments:'none',charset:'utf8',banner:{js:'/* DVIDIA prerequisite experiments. MIT; bundled Three.js r180, MIT. See reference_replay.third-party.txt. */'}}); +console.log('Built prerequisite_lab.bundle.js using pinned local dependencies.'); diff --git a/viewer/package.json b/viewer/package.json index 8845ac0..e8fea49 100644 --- a/viewer/package.json +++ b/viewer/package.json @@ -8,7 +8,8 @@ "scripts": { "build": "node ../scripts/build-reference-viewer.mjs", "build:assets": "node build-assets.mjs", - "build:workstation": "node build-workstation.mjs" + "build:workstation": "node build-workstation.mjs", + "build:prerequisites": "node build-prerequisites.mjs" }, "devDependencies": { "@mujoco/mujoco": "3.15.0",